path
stringlengths 5
300
| repo_name
stringlengths 6
76
| content
stringlengths 26
1.05M
|
|---|---|---|
ajax/libs/yui/3.4.0pr2/event/event.js
|
itvsai/cdnjs
|
(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) {
/*
* 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;
c = e.keyCode || e.charCode;
if (ua.webkit && (c in webkitKeymap)) {
c = webkitKeymap[c];
}
this.keyCode = c;
this.charCode = c;
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
*/
/**
* The X location of the event on the page (including scroll)
* @property pageX
* @type int
*/
/**
* The Y location of the event on the page (including scroll)
* @property pageY
* @type int
*/
/**
* The keyCode for key events. Uses charCode if keyCode is not available
* @property keyCode
* @type int
*/
/**
* The charCode for key events. Same as keyCode
* @property charCode
* @type int
*/
/**
* The button that was pushed.
* @property button
* @type int
*/
/**
* The button that was pushed. Same as button.
* @property which
* @type int
*/
/**
* Node reference for the targeted element
* @propery target
* @type Node
*/
/**
* Node reference for the element that the listener was attached to.
* @propery currentTarget
* @type Node
*/
/**
* Node reference to the relatedTarget
* @propery 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 int
*/
/**
* 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() {
/**
* DOM event listener abstraction layer
* @module 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 {
return (o && typeof o !== "string" && Y.Lang.isNumber(o.length) &&
!o.tagName && !o.alert);
} catch(ex) {
return false;
}
},
// aliases to support DOM event subscription clean up when the last
// subscriber is detached. deleteAndClean overrides the DOM event's wrapper
// CustomEvent _delete method.
_ceProtoDelete = Y.CustomEvent.prototype._delete,
_deleteAndClean = function(s) {
var ret = _ceProtoDelete.apply(this, arguments);
if (!this.subCount && !this.afterCount) {
Y.Event._clean(this);
}
return ret;
},
Event = function() {
/**
* True after the onload event has fired
* @property _loadComplete
* @type boolean
* @static
* @private
*/
var _loadComplete = false,
/**
* The number of times to poll after window.onload. This number is
* increased if additional late-bound handlers are requested after
* the page load.
* @property _retryCount
* @static
* @private
*/
_retryCount = 0,
/**
* onAvailable listeners
* @property _avail
* @static
* @private
*/
_avail = [],
/**
* Custom event wrappers for DOM events. Key is
* 'event:' + Element uid stamp + event type
* @property _wrappers
* @type Y.Event.Custom
* @static
* @private
*/
_wrappers = _eventenv.dom_wrappers,
_windowLoadKey = null,
/**
* Custom event wrapper map DOM events. Key is
* Element uid stamp. Each item is a hash of custom event
* wrappers as provided in the _wrappers collection. This
* provides the infrastructure for getListeners.
* @property _el_events
* @static
* @private
*/
_el_events = _eventenv.dom_map;
return {
/**
* The number of times we should look for elements that are not
* in the DOM at the time the event is requested after the document
* has been loaded. The default is 1000@amp;40 ms, so it will poll
* for 40 seconds or until all outstanding handlers are bound
* (whichever comes first).
* @property POLL_RETRYS
* @type int
* @static
* @final
*/
POLL_RETRYS: 1000,
/**
* The poll interval in milliseconds
* @property POLL_INTERVAL
* @type int
* @static
* @final
*/
POLL_INTERVAL: 40,
/**
* addListener/removeListener can throw errors in unexpected scenarios.
* These errors are suppressed, the method returns false, and this property
* is set
* @property lastError
* @static
* @type Error
*/
lastError: null,
/**
* poll handle
* @property _interval
* @static
* @private
*/
_interval: null,
/**
* document readystate poll handle
* @property _dri
* @static
* @private
*/
_dri: null,
/**
* True when the document is initially usable
* @property DOMReady
* @type boolean
* @static
*/
DOMReady: false,
/**
* @method startInterval
* @static
* @private
*/
startInterval: function() {
if (!Event._interval) {
Event._interval = setInterval(Event._poll, Event.POLL_INTERVAL);
}
},
/**
* Executes the supplied callback when the item with the supplied
* id is found. This is meant to be used to execute behavior as
* soon as possible as the page loads. If you use this after the
* initial page load it will poll for a fixed time for the element.
* The number of times it will poll and the frequency are
* configurable. By default it will poll for 10 seconds.
*
* <p>The callback is executed with a single parameter:
* the custom object parameter, if provided.</p>
*
* @method onAvailable
*
* @param {string||string[]} id the id of the element, or an array
* of ids to look for.
* @param {function} fn what to execute when the element is found.
* @param {object} p_obj an optional object to be passed back as
* a parameter to fn.
* @param {boolean|object} p_override If set to true, fn will execute
* in the context of p_obj, if set to an object it
* will execute in the context of that object
* @param checkContent {boolean} check child node readiness (onContentReady)
* @static
* @deprecated Use Y.on("available")
*/
// @TODO fix arguments
onAvailable: function(id, fn, p_obj, p_override, checkContent, compat) {
var a = Y.Array(id), i, availHandle;
for (i=0; i<a.length; i=i+1) {
_avail.push({
id: a[i],
fn: fn,
obj: p_obj,
override: p_override,
checkReady: checkContent,
compat: compat
});
}
_retryCount = this.POLL_RETRYS;
// We want the first test to be immediate, but async
setTimeout(Event._poll, 0);
availHandle = new Y.EventHandle({
_delete: function() {
// set by the event system for lazy DOM listeners
if (availHandle.handle) {
availHandle.handle.detach();
return;
}
var i, j;
// otherwise try to remove the onAvailable listener(s)
for (i = 0; i < a.length; i++) {
for (j = 0; j < _avail.length; j++) {
if (a[i] === _avail[j].id) {
_avail.splice(j, 1);
}
}
}
}
});
return availHandle;
},
/**
* Works the same way as onAvailable, but additionally checks the
* state of sibling elements to determine if the content of the
* available element is safe to modify.
*
* <p>The callback is executed with a single parameter:
* the custom object parameter, if provided.</p>
*
* @method onContentReady
*
* @param {string} id the id of the element to look for.
* @param {function} fn what to execute when the element is ready.
* @param {object} obj an optional object to be passed back as
* a parameter to fn.
* @param {boolean|object} override If set to true, fn will execute
* in the context of p_obj. If an object, fn will
* exectute in the context of that object
*
* @static
* @deprecated Use Y.on("contentready")
*/
// @TODO fix arguments
onContentReady: function(id, fn, obj, override, compat) {
return Event.onAvailable(id, fn, obj, override, true, compat);
},
/**
* Adds an event listener
*
* @method attach
*
* @param {String} type The type of event to append
* @param {Function} fn The method the event invokes
* @param {String|HTMLElement|Array|NodeList} el An id, an element
* reference, or a collection of ids and/or elements to assign the
* listener to.
* @param {Object} context optional context object
* @param {Boolean|object} args 0..n arguments to pass to the callback
* @return {EventHandle} an object to that can be used to detach the listener
*
* @static
*/
attach: function(type, fn, el, context) {
return Event._attach(Y.Array(arguments, 0, true));
},
_createWrapper: function (el, type, capture, compat, facade) {
var cewrapper,
ek = Y.stamp(el),
key = 'event:' + ek + type;
if (false === facade) {
key += 'native';
}
if (capture) {
key += 'capture';
}
cewrapper = _wrappers[key];
if (!cewrapper) {
// create CE wrapper
cewrapper = Y.publish(key, {
silent: true,
bubbles: false,
contextFn: function() {
if (compat) {
return cewrapper.el;
} else {
cewrapper.nodeRef = cewrapper.nodeRef || Y.one(cewrapper.el);
return cewrapper.nodeRef;
}
}
});
cewrapper.overrides = {};
// for later removeListener calls
cewrapper.el = el;
cewrapper.key = key;
cewrapper.domkey = ek;
cewrapper.type = type;
cewrapper.fn = function(e) {
cewrapper.fire(Event.getEvent(e, el, (compat || (false === facade))));
};
cewrapper.capture = capture;
if (el == win && type == "load") {
// window load happens once
cewrapper.fireOnce = true;
_windowLoadKey = key;
}
cewrapper._delete = _deleteAndClean;
_wrappers[key] = cewrapper;
_el_events[ek] = _el_events[ek] || {};
_el_events[ek][key] = cewrapper;
add(el, type, cewrapper.fn, capture);
}
return cewrapper;
},
_attach: function(args, conf) {
var compat,
handles, oEl, cewrapper, context,
fireNow = false, ret,
type = args[0],
fn = args[1],
el = args[2] || win,
facade = conf && conf.facade,
capture = conf && conf.capture,
overrides = conf && conf.overrides;
if (args[args.length-1] === COMPAT_ARG) {
compat = true;
}
if (!fn || !fn.call) {
// throw new TypeError(type + " attach call failed, callback undefined");
return false;
}
// The el argument can be an array of elements or element ids.
if (shouldIterate(el)) {
handles=[];
Y.each(el, function(v, k) {
args[2] = v;
handles.push(Event._attach(args.slice(), conf));
});
// return (handles.length === 1) ? handles[0] : handles;
return new Y.EventHandle(handles);
// If the el argument is a string, we assume it is
// actually the id of the element. If the page is loaded
// we convert el to the actual element, otherwise we
// defer attaching the event until the element is
// ready
} else if (Y.Lang.isString(el)) {
// oEl = (compat) ? Y.DOM.byId(el) : Y.Selector.query(el);
if (compat) {
oEl = Y.DOM.byId(el);
} else {
oEl = Y.Selector.query(el);
switch (oEl.length) {
case 0:
oEl = null;
break;
case 1:
oEl = oEl[0];
break;
default:
args[2] = oEl;
return Event._attach(args, conf);
}
}
if (oEl) {
el = oEl;
// Not found = defer adding the event until the element is available
} else {
ret = Event.onAvailable(el, function() {
ret.handle = Event._attach(args, conf);
}, Event, true, false, compat);
return ret;
}
}
// Element should be an html element or node
if (!el) {
return false;
}
if (Y.Node && Y.instanceOf(el, Y.Node)) {
el = Y.Node.getDOMNode(el);
}
cewrapper = Event._createWrapper(el, type, capture, compat, facade);
if (overrides) {
Y.mix(cewrapper.overrides, overrides);
}
if (el == win && type == "load") {
// if the load is complete, fire immediately.
// all subscribers, including the current one
// will be notified.
if (YUI.Env.windowLoaded) {
fireNow = true;
}
}
if (compat) {
args.pop();
}
context = args[3];
// set context to the Node if not specified
// ret = cewrapper.on.apply(cewrapper, trimmedArgs);
ret = cewrapper._on(fn, context, (args.length > 4) ? args.slice(4) : null);
if (fireNow) {
cewrapper.fire();
}
return ret;
},
/**
* Removes an event listener. Supports the signature the event was bound
* with, but the preferred way to remove listeners is using the handle
* that is returned when using Y.on
*
* @method detach
*
* @param {String} type the type of event to remove.
* @param {Function} fn the method the event invokes. If fn is
* undefined, then all event handlers for the type of event are
* removed.
* @param {String|HTMLElement|Array|NodeList|EventHandle} el An
* event handle, an id, an element reference, or a collection
* of ids and/or elements to remove the listener from.
* @return {boolean} true if the unbind was successful, false otherwise.
* @static
*/
detach: function(type, fn, el, obj) {
var args=Y.Array(arguments, 0, true), compat, l, ok, i,
id, ce;
if (args[args.length-1] === COMPAT_ARG) {
compat = true;
// args.pop();
}
if (type && type.detach) {
return type.detach();
}
// The el argument can be a string
if (typeof el == "string") {
// el = (compat) ? Y.DOM.byId(el) : Y.all(el);
if (compat) {
el = Y.DOM.byId(el);
} else {
el = Y.Selector.query(el);
l = el.length;
if (l < 1) {
el = null;
} else if (l == 1) {
el = el[0];
}
}
// return Event.detach.apply(Event, args);
}
if (!el) {
return false;
}
if (el.detach) {
args.splice(2, 1);
return el.detach.apply(el, args);
// The el argument can be an array of elements or element ids.
} else if (shouldIterate(el)) {
ok = true;
for (i=0, l=el.length; i<l; ++i) {
args[2] = el[i];
ok = ( Y.Event.detach.apply(Y.Event, args) && ok );
}
return ok;
}
if (!type || !fn || !fn.call) {
return Event.purgeElement(el, false, type);
}
id = 'event:' + Y.stamp(el) + type;
ce = _wrappers[id];
if (ce) {
return ce.detach(fn);
} else {
return false;
}
},
/**
* Finds the event in the window object, the caller's arguments, or
* in the arguments of another method in the callstack. This is
* executed automatically for events registered through the event
* manager, so the implementer should not normally need to execute
* this function at all.
* @method getEvent
* @param {Event} e the event parameter from the handler
* @param {HTMLElement} el the element the listener was attached to
* @return {Event} the event
* @static
*/
getEvent: function(e, el, noFacade) {
var ev = e || win.event;
return (noFacade) ? ev :
new Y.DOMEventFacade(ev, el, _wrappers['event:' + Y.stamp(el) + e.type]);
},
/**
* Generates an unique ID for the element if it does not already
* have one.
* @method generateId
* @param el the element to create the id for
* @return {string} the resulting id of the element
* @static
*/
generateId: function(el) {
return Y.DOM.generateID(el);
},
/**
* We want to be able to use getElementsByTagName as a collection
* to attach a group of events to. Unfortunately, different
* browsers return different types of collections. This function
* tests to determine if the object is array-like. It will also
* fail if the object is an array, but is empty.
* @method _isValidCollection
* @param o the object to test
* @return {boolean} true if the object is array-like and populated
* @deprecated was not meant to be used directly
* @static
* @private
*/
_isValidCollection: shouldIterate,
/**
* hook up any deferred listeners
* @method _load
* @static
* @private
*/
_load: function(e) {
if (!_loadComplete) {
_loadComplete = true;
// Just in case DOMReady did not go off for some reason
// E._ready();
if (Y.fire) {
Y.fire(EVENT_READY);
}
// Available elements may not have been detected before the
// window load event fires. Try to find them now so that the
// the user is more likely to get the onAvailable notifications
// before the window load notification
Event._poll();
}
},
/**
* Polling function that runs before the onload event fires,
* attempting to attach to DOM Nodes as soon as they are
* available
* @method _poll
* @static
* @private
*/
_poll: function() {
if (Event.locked) {
return;
}
if (Y.UA.ie && !YUI.Env.DOMReady) {
// Hold off if DOMReady has not fired and check current
// readyState to protect against the IE operation aborted
// issue.
Event.startInterval();
return;
}
Event.locked = true;
// keep trying until after the page is loaded. We need to
// check the page load state prior to trying to bind the
// elements so that we can be certain all elements have been
// tested appropriately
var i, len, item, el, notAvail, executeItem,
tryAgain = !_loadComplete;
if (!tryAgain) {
tryAgain = (_retryCount > 0);
}
// onAvailable
notAvail = [];
executeItem = function (el, item) {
var context, ov = item.override;
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 : []);
}
};
// onAvailable
for (i=0,len=_avail.length; i<len; ++i) {
item = _avail[i];
if (item && !item.checkReady) {
// el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id);
el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true);
if (el) {
executeItem(el, item);
_avail[i] = null;
} else {
notAvail.push(item);
}
}
}
// onContentReady
for (i=0,len=_avail.length; i<len; ++i) {
item = _avail[i];
if (item && item.checkReady) {
// el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id);
el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true);
if (el) {
// The element is available, but not necessarily ready
// @todo should we test parentNode.nextSibling?
if (_loadComplete || (el.get && el.get('nextSibling')) || el.nextSibling) {
executeItem(el, item);
_avail[i] = null;
}
} else {
notAvail.push(item);
}
}
}
_retryCount = (notAvail.length === 0) ? 0 : _retryCount - 1;
if (tryAgain) {
// we may need to strip the nulled out items here
Event.startInterval();
} else {
clearInterval(Event._interval);
Event._interval = null;
}
Event.locked = false;
return;
},
/**
* Removes all listeners attached to the given element via addListener.
* Optionally, the node's children can also be purged.
* Optionally, you can specify a specific type of event to remove.
* @method purgeElement
* @param {HTMLElement} el the element to purge
* @param {boolean} recurse recursively purge this element's children
* as well. Use with caution.
* @param {string} type optional type of listener to purge. If
* left out, all listeners will be removed
* @static
*/
purgeElement: function(el, recurse, type) {
// var oEl = (Y.Lang.isString(el)) ? Y.one(el) : el,
var oEl = (Y.Lang.isString(el)) ? Y.Selector.query(el, null, true) : el,
lis = Event.getListeners(oEl, type), i, len, children, child;
if (recurse && oEl) {
lis = lis || [];
children = Y.Selector.query('*', oEl);
i = 0;
len = children.length;
for (; 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 {Y.Custom.Event} 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);
}
add(win, "unload", onUnload);
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']});
YUI.add('event-delegate', function(Y) {
/**
* 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 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 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
*/
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 }, context, filter, ...);
// and Y.delegate(['click', 'key'], fn, context, 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}, context, filter) =>
// Y.delegate('click', fn, context, filter)
args.unshift(null); // one arg becomes two; need to make space
for (i in type) {
if (type.hasOwnProperty(i)) {
args[0] = i;
args[1] = type[i];
handles.push(Y.delegate.apply(Y, args));
}
}
}
return new Y.EventHandle(handles);
}
typeBits = type.split(/\|/);
if (typeBits.length > 1) {
cat = typeBits.shift();
args[0] = type = typeBits.shift();
}
synth = Y.Node.DOM_EVENTS[type];
if (isObject(synth) && synth.delegate) {
handle = synth.delegate.apply(synth, arguments);
}
if (!handle) {
if (!type || !fn || !el || !filter) {
return;
}
container = (query) ? Y.Selector.query(query, null, true) : el;
if (!container && isString(el)) {
handle = Y.on('available', function () {
Y.mix(handle, Y.delegate.apply(Y, args), true);
}, el);
}
if (!handle && container) {
args.splice(2, 2, container); // remove the filter
handle = Y.Event._attach(args, { facade: false });
handle.sub.filter = filter;
handle.sub._notify = delegate.notifySub;
}
}
if (handle && cat) {
categories = detachCategories[cat] || (detachCategories[cat] = {});
categories = categories[type] || (categories[type] = []);
categories.push(handle);
}
return handle;
}
/**
* Overrides the <code>_notify</code> method on the normal DOM subscription to
* inject the filtering logic and only proceed in the case of a match.
*
* @method delegate.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;
}
};
/**
* <p>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.</p>
*
* <p>This function is memoized, so previously compiled filter functions are
* returned if the same selector string is provided.</p>
*
* <p>This function may be useful when defining synthetic events for delegate
* handling.</p>
*
* @method delegate.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._node);
};
});
/**
* 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.
*
* @method delegate._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;
}
// 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('event-synthetic', function(Y) {
/**
* Define new DOM events that can be subscribed to from Nodes.
*
* @module event
* @submodule event-synthetic
*/
var DOMMap = Y.Env.evt.dom_map,
toArray = Y.Array,
YLang = Y.Lang,
isObject = YLang.isObject,
isString = YLang.isString,
isArray = YLang.isArray,
query = Y.Selector.query,
noop = function () {};
/**
* <p>The triggering mechanism used by SyntheticEvents.</p>
*
* <p>Implementers should not instantiate these directly. Use the Notifier
* provided to the event's implemented <code>on(node, sub, notifier)</code> or
* <code>delegate(node, sub, notifier, filter)</code> methods.</p>
*
* @class SyntheticEvent.Notifier
* @constructor
* @param handle {EventHandle} the detach handle for the subscription to an
* internal custom event used to execute the callback passed to
* on(..) or delegate(..)
* @param emitFacade {Boolean} take steps to ensure the first arg received by
* the subscription callback is an event facade
* @private
* @since 3.2.0
*/
function Notifier(handle, emitFacade) {
this.handle = handle;
this.emitFacade = emitFacade;
}
/**
* <p>Executes the subscription callback, passing the firing arguments as the
* first parameters to that callback. For events that are configured with
* emitFacade=true, it is common practice to pass the triggering DOMEventFacade
* as the first parameter. Barring a proper DOMEventFacade or EventFacade
* (from a CustomEvent), a new EventFacade will be generated. In that case, if
* fire() is called with a simple object, it will be mixed into the facade.
* Otherwise, the facade will be prepended to the callback parameters.</p>
*
* <p>For notifiers provided to delegate logic, the first argument should be an
* object with a "currentTarget" property to identify what object to
* default as 'this' in the callback. Typically this is gleaned from the
* DOMEventFacade or EventFacade, but if configured with emitFacade=false, an
* object must be provided. In that case, the object will be removed from the
* callback parameters.</p>
*
* <p>Additional arguments passed during event subscription will be
* automatically added after those passed to fire().</p>
*
* @method fire
* @param e {EventFacade|DOMEventFacade|Object|any} (see description)
* @param arg* {any} additional arguments received by all subscriptions
* @private
*/
Notifier.prototype.fire = function (e) {
// first arg to delegate notifier should be an object with currentTarget
var args = toArray(arguments, 0, true),
handle = this.handle,
ce = handle.evt,
sub = handle.sub,
thisObj = sub.context,
delegate = sub.filter,
event = e || {},
ret;
if (this.emitFacade) {
if (!e || !e.preventDefault) {
event = ce._getFacade();
if (isObject(e) && !e.preventDefault) {
Y.mix(event, e, true);
args[0] = event;
} else {
args.unshift(event);
}
}
event.type = ce.type;
event.details = args.slice();
if (delegate) {
event.container = ce.host;
}
} else if (delegate && isObject(e) && e.currentTarget) {
args.shift();
}
sub.context = thisObj || event.currentTarget || ce.host;
ret = ce.fire.apply(ce, args);
sub.context = thisObj; // reset for future firing
// to capture callbacks that return false to stopPropagation.
// Useful for delegate implementations
return ret;
};
/**
* Manager object for synthetic event subscriptions to aggregate multiple synths on the same node without colliding with actual DOM subscription entries in the global map of DOM subscriptions. Also facilitates proper cleanup on page unload.
*
* @class SynthRegistry
* @constructor
* @param el {HTMLElement} the DOM element
* @param yuid {String} the yuid stamp for the element
* @param key {String} the generated id token used to identify an event type +
* element in the global DOM subscription map.
* @private
*/
function SynthRegistry(el, yuid, key) {
this.handles = [];
this.el = el;
this.key = key;
this.domkey = yuid;
}
SynthRegistry.prototype = {
constructor: SynthRegistry,
// A few object properties to fake the CustomEvent interface for page
// unload cleanup. DON'T TOUCH!
type : '_synth',
fn : noop,
capture : false,
/**
* Adds a subscription from the Notifier registry.
*
* @method register
* @param handle {EventHandle} the subscription
* @since 3.4.0
*/
register: function (handle) {
handle.evt.registry = this;
this.handles.push(handle);
},
/**
* Removes the subscription from the Notifier registry.
*
* @method _unregisterSub
* @param sub {Subscription} the subscription
* @since 3.4.0
*/
unregister: function (sub) {
var handles = this.handles,
events = DOMMap[this.domkey],
i;
for (i = handles.length - 1; i >= 0; --i) {
if (handles[i].sub === sub) {
handles.splice(i, 1);
break;
}
}
// Clean up left over objects when there are no more subscribers.
if (!handles.length) {
delete events[this.key];
if (!Y.Object.size(events)) {
delete DOMMap[this.domkey];
}
}
},
/**
* Used by the event system's unload cleanup process. When navigating
* away from the page, the event system iterates the global map of element
* subscriptions and detaches everything using detachAll(). Normally,
* the map is populated with custom events, so this object needs to
* at least support the detachAll method to duck type its way to
* cleanliness.
*
* @method detachAll
* @private
* @since 3.4.0
*/
detachAll : function () {
var handles = this.handles,
i = handles.length;
while (--i >= 0) {
handles[i].detach();
}
}
};
/**
* <p>Wrapper class for the integration of new events into the YUI event
* infrastructure. Don't instantiate this object directly, use
* <code>Y.Event.define(type, config)</code>. See that method for details.</p>
*
* <p>Properties that MAY or SHOULD be specified in the configuration are noted
* below and in the description of <code>Y.Event.define</code>.</p>
*
* @class SyntheticEvent
* @constructor
* @param cfg {Object} Implementation pieces and configuration
* @since 3.1.0
* @in event-synthetic
*/
function SyntheticEvent() {
this._init.apply(this, arguments);
}
Y.mix(SyntheticEvent, {
Notifier: Notifier,
SynthRegistry: SynthRegistry,
/**
* Returns the array of subscription handles for a node for the given event
* type. Passing true as the third argument will create a registry entry
* in the event system's DOM map to host the array if one doesn't yet exist.
*
* @method getRegistry
* @param node {Node} the node
* @param type {String} the event
* @param create {Boolean} create a registration entry to host a new array
* if one doesn't exist.
* @return {Array}
* @static
* @protected
* @since 3.2.0
*/
getRegistry: function (node, type, create) {
var el = node._node,
yuid = Y.stamp(el),
key = 'event:' + yuid + type + '_synth',
events = DOMMap[yuid];
if (create) {
if (!events) {
events = DOMMap[yuid] = {};
}
if (!events[key]) {
events[key] = new SynthRegistry(el, yuid, key);
}
}
return (events && events[key]) || null;
},
/**
* Alternate <code>_delete()</code> method for the CustomEvent object
* created to manage SyntheticEvent subscriptions.
*
* @method _deleteSub
* @param sub {Subscription} the subscription to clean up
* @private
* @since 3.2.0
*/
_deleteSub: function (sub) {
if (sub && sub.fn) {
var synth = this.eventDef,
method = (sub.filter) ? 'detachDelegate' : 'detach';
this.subscribers = {};
this.subCount = 0;
synth[method](sub.node, sub, this.notifier, sub.filter);
this.registry.unregister(sub);
delete sub.fn;
delete sub.node;
delete sub.context;
}
},
prototype: {
constructor: SyntheticEvent,
/**
* Construction logic for the event.
*
* @method _init
* @protected
*/
_init: function () {
var config = this.publishConfig || (this.publishConfig = {});
// The notification mechanism handles facade creation
this.emitFacade = ('emitFacade' in config) ?
config.emitFacade :
true;
config.emitFacade = false;
},
/**
* <p>Implementers MAY provide this method definition.</p>
*
* <p>Implement this function if the event supports a different
* subscription signature. This function is used by both
* <code>on()</code> and <code>delegate()</code>. The second parameter
* indicates that the event is being subscribed via
* <code>delegate()</code>.</p>
*
* <p>Implementations must remove extra arguments from the args list
* before returning. The required args for <code>on()</code>
* subscriptions are</p>
* <pre><code>[type, callback, target, context, argN...]</code></pre>
*
* <p>The required args for <code>delegate()</code>
* subscriptions are</p>
*
* <pre><code>[type, callback, target, filter, context, argN...]</code></pre>
*
* <p>The return value from this function will be stored on the
* subscription in the '_extra' property for reference elsewhere.</p>
*
* @method processArgs
* @param args {Array} parmeters passed to Y.on(..) or Y.delegate(..)
* @param delegate {Boolean} true if the subscription is from Y.delegate
* @return {any}
*/
processArgs: noop,
/**
* <p>Implementers MAY override this property.</p>
*
* <p>Whether to prevent multiple subscriptions to this event that are
* classified as being the same. By default, this means the subscribed
* callback is the same function. See the <code>subMatch</code>
* method. Setting this to true will impact performance for high volume
* events.</p>
*
* @property preventDups
* @type {Boolean}
* @default false
*/
//preventDups : false,
/**
* <p>Implementers SHOULD provide this method definition.</p>
*
* Implementation logic for subscriptions done via <code>node.on(type,
* fn)</code> or <code>Y.on(type, fn, target)</code>. This
* function should set up the monitor(s) that will eventually fire the
* event. Typically this involves subscribing to at least one DOM
* event. It is recommended to store detach handles from any DOM
* subscriptions to make for easy cleanup in the <code>detach</code>
* method. Typically these handles are added to the <code>sub</code>
* object. Also for SyntheticEvents that leverage a single DOM
* subscription under the hood, it is recommended to pass the DOM event
* object to <code>notifier.fire(e)</code>. (The event name on the
* object will be updated).
*
* @method on
* @param node {Node} the node the subscription is being applied to
* @param sub {Subscription} the object to track this subscription
* @param notifier {SyntheticEvent.Notifier} call notifier.fire(..) to
* trigger the execution of the subscribers
*/
on: noop,
/**
* <p>Implementers SHOULD provide this method definition.</p>
*
* <p>Implementation logic for detaching subscriptions done via
* <code>node.on(type, fn)</code>. This function should clean up any
* subscriptions made in the <code>on()</code> phase.</p>
*
* @method detach
* @param node {Node} the node the subscription was applied to
* @param sub {Subscription} the object tracking this subscription
* @param notifier {SyntheticEvent.Notifier} the Notifier used to
* trigger the execution of the subscribers
*/
detach: noop,
/**
* <p>Implementers SHOULD provide this method definition.</p>
*
* <p>Implementation logic for subscriptions done via
* <code>node.delegate(type, fn, filter)</code> or
* <code>Y.delegate(type, fn, container, filter)</code>. Like with
* <code>on()</code> above, this function should monitor the environment
* for the event being fired, and trigger subscription execution by
* calling <code>notifier.fire(e)</code>.</p>
*
* <p>This function receives a fourth argument, which is the filter
* used to identify which Node's are of interest to the subscription.
* The filter will be either a boolean function that accepts a target
* Node for each hierarchy level as the event bubbles, or a selector
* string. To translate selector strings into filter functions, use
* <code>Y.delegate.compileFilter(filter)</code>.</p>
*
* @method delegate
* @param node {Node} the node the subscription is being applied to
* @param sub {Subscription} the object to track this subscription
* @param notifier {SyntheticEvent.Notifier} call notifier.fire(..) to
* trigger the execution of the subscribers
* @param filter {String|Function} Selector string or function that
* accepts an event object and returns null, a Node, or an
* array of Nodes matching the criteria for processing.
* @since 3.2.0
*/
delegate : noop,
/**
* <p>Implementers SHOULD provide this method definition.</p>
*
* <p>Implementation logic for detaching subscriptions done via
* <code>node.delegate(type, fn, filter)</code> or
* <code>Y.delegate(type, fn, container, filter)</code>. This function
* should clean up any subscriptions made in the
* <code>delegate()</code> phase.</p>
*
* @method detachDelegate
* @param node {Node} the node the subscription was applied to
* @param sub {Subscription} the object tracking this subscription
* @param notifier {SyntheticEvent.Notifier} the Notifier used to
* trigger the execution of the subscribers
* @param filter {String|Function} Selector string or function that
* accepts an event object and returns null, a Node, or an
* array of Nodes matching the criteria for processing.
* @since 3.2.0
*/
detachDelegate : noop,
/**
* Sets up the boilerplate for detaching the event and facilitating the
* execution of subscriber callbacks.
*
* @method _on
* @param args {Array} array of arguments passed to
* <code>Y.on(...)</code> or <code>Y.delegate(...)</code>
* @param delegate {Boolean} true if called from
* <code>Y.delegate(...)</code>
* @return {EventHandle} the detach handle for this subscription
* @private
* since 3.2.0
*/
_on: function (args, delegate) {
var handles = [],
originalArgs = args.slice(),
extra = this.processArgs(args, delegate),
selector = args[2],
method = delegate ? 'delegate' : 'on',
nodes, handle;
// Can't just use Y.all because it doesn't support window (yet?)
nodes = (isString(selector)) ? query(selector) : toArray(selector);
if (!nodes.length && isString(selector)) {
handle = Y.on('available', function () {
Y.mix(handle, Y[method].apply(Y, originalArgs), true);
}, selector);
return handle;
}
Y.Array.each(nodes, function (node) {
var subArgs = args.slice(),
filter;
node = Y.one(node);
if (node) {
if (delegate) {
filter = subArgs.splice(3, 1)[0];
}
// (type, fn, el, thisObj, ...) => (fn, thisObj, ...)
subArgs.splice(0, 4, subArgs[1], subArgs[3]);
if (!this.preventDups ||
!this.getSubs(node, args, null, true))
{
handles.push(this._subscribe(node, method, subArgs, extra, filter));
}
}
}, this);
return (handles.length === 1) ?
handles[0] :
new Y.EventHandle(handles);
},
/**
* Creates a new Notifier object for use by this event's
* <code>on(...)</code> or <code>delegate(...)</code> implementation
* and register the custom event proxy in the DOM system for cleanup.
*
* @method _subscribe
* @param node {Node} the Node hosting the event
* @param method {String} "on" or "delegate"
* @param args {Array} the subscription arguments passed to either
* <code>Y.on(...)</code> or <code>Y.delegate(...)</code>
* after running through <code>processArgs(args)</code> to
* normalize the argument signature
* @param extra {any} Extra data parsed from
* <code>processArgs(args)</code>
* @param filter {String|Function} the selector string or function
* filter passed to <code>Y.delegate(...)</code> (not
* present when called from <code>Y.on(...)</code>)
* @return {EventHandle}
* @private
* @since 3.2.0
*/
_subscribe: function (node, method, args, extra, filter) {
var dispatcher = new Y.CustomEvent(this.type, this.publishConfig),
handle = dispatcher.on.apply(dispatcher, args),
notifier = new Notifier(handle, this.emitFacade),
registry = SyntheticEvent.getRegistry(node, this.type, true),
sub = handle.sub;
sub.node = node;
sub.filter = filter;
if (extra) {
this.applyArgExtras(extra, sub);
}
Y.mix(dispatcher, {
eventDef : this,
notifier : notifier,
host : node, // I forget what this is for
currentTarget: node, // for generating facades
target : node, // for generating facades
el : node._node, // For category detach
_delete : SyntheticEvent._deleteSub
}, true);
handle.notifier = notifier;
registry.register(handle);
// Call the implementation's "on" or "delegate" method
this[method](node, sub, notifier, filter);
return handle;
},
/**
* <p>Implementers MAY provide this method definition.</p>
*
* <p>Implement this function if you want extra data extracted during
* processArgs to be propagated to subscriptions on a per-node basis.
* That is to say, if you call <code>Y.on('xyz', fn, xtra, 'div')</code>
* the data returned from processArgs will be shared
* across the subscription objects for all the divs. If you want each
* subscription to receive unique information, do that processing
* here.</p>
*
* <p>The default implementation adds the data extracted by processArgs
* to the subscription object as <code>sub._extra</code>.</p>
*
* @method applyArgExtras
* @param extra {any} Any extra data extracted from processArgs
* @param sub {Subscription} the individual subscription
*/
applyArgExtras: function (extra, sub) {
sub._extra = extra;
},
/**
* Removes the subscription(s) from the internal subscription dispatch
* mechanism. See <code>SyntheticEvent._deleteSub</code>.
*
* @method _detach
* @param args {Array} The arguments passed to
* <code>node.detach(...)</code>
* @private
* @since 3.2.0
*/
_detach: function (args) {
// Can't use Y.all because it doesn't support window (yet?)
// TODO: Does Y.all support window now?
var target = args[2],
els = (isString(target)) ?
query(target) : toArray(target),
node, i, len, handles, j;
// (type, fn, el, context, filter?) => (type, fn, context, filter?)
args.splice(2, 1);
for (i = 0, len = els.length; i < len; ++i) {
node = Y.one(els[i]);
if (node) {
handles = this.getSubs(node, args);
if (handles) {
for (j = handles.length - 1; j >= 0; --j) {
handles[j].detach();
}
}
}
}
},
/**
* Returns the detach handles of subscriptions on a node that satisfy a
* search/filter function. By default, the filter used is the
* <code>subMatch</code> method.
*
* @method getSubs
* @param node {Node} the node hosting the event
* @param args {Array} the array of original subscription args passed
* to <code>Y.on(...)</code> (before
* <code>processArgs</code>
* @param filter {Function} function used to identify a subscription
* for inclusion in the returned array
* @param first {Boolean} stop after the first match (used to check for
* duplicate subscriptions)
* @return {EventHandle[]} detach handles for the matching subscriptions
*/
getSubs: function (node, args, filter, first) {
var registry = SyntheticEvent.getRegistry(node, this.type),
handles = [],
allHandles, i, len, handle;
if (registry) {
allHandles = registry.handles;
if (!filter) {
filter = this.subMatch;
}
for (i = 0, len = allHandles.length; i < len; ++i) {
handle = allHandles[i];
if (filter.call(this, handle.sub, args)) {
if (first) {
return handle;
} else {
handles.push(allHandles[i]);
}
}
}
}
return handles.length && handles;
},
/**
* <p>Implementers MAY override this to define what constitutes a
* "same" subscription. Override implementations should
* consider the lack of a comparator as a match, so calling
* <code>getSubs()</code> with no arguments will return all subs.</p>
*
* <p>Compares a set of subscription arguments against a Subscription
* object to determine if they match. The default implementation
* compares the callback function against the second argument passed to
* <code>Y.on(...)</code> or <code>node.detach(...)</code> etc.</p>
*
* @method subMatch
* @param sub {Subscription} the existing subscription
* @param args {Array} the calling arguments passed to
* <code>Y.on(...)</code> etc.
* @return {Boolean} true if the sub can be described by the args
* present
* @since 3.2.0
*/
subMatch: function (sub, args) {
// Default detach cares only about the callback matching
return !args[1] || sub.fn === args[1];
}
}
}, true);
Y.SyntheticEvent = SyntheticEvent;
/**
* <p>Defines a new event in the DOM event system. Implementers are
* responsible for monitoring for a scenario whereby the event is fired. A
* notifier object is provided to the functions identified below. When the
* criteria defining the event are met, call notifier.fire( [args] ); to
* execute event subscribers.</p>
*
* <p>The first parameter is the name of the event. The second parameter is a
* configuration object which define the behavior of the event system when the
* new event is subscribed to or detached from. The methods that should be
* defined in this configuration object are <code>on</code>,
* <code>detach</code>, <code>delegate</code>, and <code>detachDelegate</code>.
* You are free to define any other methods or properties needed to define your
* event. Be aware, however, that since the object is used to subclass
* SyntheticEvent, you should avoid method names used by SyntheticEvent unless
* your intention is to override the default behavior.</p>
*
* <p>This is a list of properties and methods that you can or should specify
* in the configuration object:</p>
*
* <dl>
* <dt><code>on</code></dt>
* <dd><code>function (node, subscription, notifier)</code> The
* implementation logic for subscription. Any special setup you need to
* do to create the environment for the event being fired--E.g. native
* DOM event subscriptions. Store subscription related objects and
* state on the <code>subscription</code> object. When the
* criteria have been met to fire the synthetic event, call
* <code>notifier.fire(e)</code>. See Notifier's <code>fire()</code>
* method for details about what to pass as parameters.</dd>
*
* <dt><code>detach</code></dt>
* <dd><code>function (node, subscription, notifier)</code> The
* implementation logic for cleaning up a detached subscription. E.g.
* detach any DOM subscriptions added in <code>on</code>.</dd>
*
* <dt><code>delegate</code></dt>
* <dd><code>function (node, subscription, notifier, filter)</code> The
* implementation logic for subscription via <code>Y.delegate</code> or
* <code>node.delegate</code>. The filter is typically either a selector
* string or a function. You can use
* <code>Y.delegate.compileFilter(selectorString)</code> to create a
* filter function from a selector string if needed. The filter function
* expects an event object as input and should output either null, a
* matching Node, or an array of matching Nodes. Otherwise, this acts
* like <code>on</code> DOM event subscriptions. Store subscription
* related objects and information on the <code>subscription</code>
* object. When the criteria have been met to fire the synthetic event,
* call <code>notifier.fire(e)</code> as noted above.</dd>
*
* <dt><code>detachDelegate</code></dt>
* <dd><code>function (node, subscription, notifier)</code> The
* implementation logic for cleaning up a detached delegate subscription.
* E.g. detach any DOM delegate subscriptions added in
* <code>delegate</code>.</dd>
*
* <dt><code>publishConfig</code></dt>
* <dd>(Object) The configuration object that will be used to instantiate
* the underlying CustomEvent. See Notifier's <code>fire</code> method
* for details.</dd>
*
* <dt><code>processArgs</code></dt
* <dd>
* <p><code>function (argArray, fromDelegate)</code> Optional method
* to extract any additional arguments from the subscription
* signature. Using this allows <code>on</code> or
* <code>delegate</code> signatures like
* <code>node.on("hover", overCallback,
* outCallback)</code>.</p>
* <p>When processing an atypical argument signature, make sure the
* args array is returned to the normal signature before returning
* from the function. For example, in the "hover" example
* above, the <code>outCallback</code> needs to be <code>splice</code>d
* out of the array. The expected signature of the args array for
* <code>on()</code> subscriptions is:</p>
* <pre>
* <code>[type, callback, target, contextOverride, argN...]</code>
* </pre>
* <p>And for <code>delegate()</code>:</p>
* <pre>
* <code>[type, callback, target, filter, contextOverride, argN...]</code>
* </pre>
* <p>where <code>target</code> is the node the event is being
* subscribed for. You can see these signatures documented for
* <code>Y.on()</code> and <code>Y.delegate()</code> respectively.</p>
* <p>Whatever gets returned from the function will be stored on the
* <code>subscription</code> object under
* <code>subscription._extra</code>.</p></dd>
* <dt><code>subMatch</code></dt>
* <dd>
* <p><code>function (sub, args)</code> Compares a set of
* subscription arguments against a Subscription object to determine
* if they match. The default implementation compares the callback
* function against the second argument passed to
* <code>Y.on(...)</code> or <code>node.detach(...)</code> etc.</p>
* </dd>
* </dl>
*
* @method Event.define
* @param type {String} the name of the event
* @param config {Object} the prototype definition for the new event (see above)
* @param force {Boolean} override an existing event (use with caution)
* @static
* @return {SyntheticEvent} the subclass implementation instance created to
* handle event subscriptions of this type
* @for Event
* @since 3.1.0
* @in event-synthetic
*/
Y.Event.define = function (type, config, force) {
var eventDef, Impl, synth;
if (config) {
eventDef = (isObject(type)) ? type : Y.merge({ type: type }, config);
if (force || !Y.Node.DOM_EVENTS[eventDef.type]) {
Impl = function () {
SyntheticEvent.apply(this, arguments);
};
Y.extend(Impl, SyntheticEvent, eventDef);
synth = new Impl();
type = synth.type;
Y.Node.DOM_EVENTS[type] = Y.Env.evt.plugins[type] = {
eventDef: synth,
on: function () {
return synth._on(toArray(arguments));
},
delegate: function () {
return synth._on(toArray(arguments), true);
},
detach: function () {
return synth._detach(toArray(arguments));
}
};
}
} else if (isString(type) || isArray(type)) {
Y.Array.each(toArray(type), function (t) {
Y.Node.DOM_EVENTS[t] = 1;
});
}
return synth;
};
}, '@VERSION@' ,{requires:['node-base', 'event-custom-complex']});
YUI.add('event-mousewheel', function(Y) {
/**
* Adds mousewheel event support
* @module event
* @submodule event-mousewheel
*/
var DOM_MOUSE_SCROLL = 'DOMMouseScroll',
fixArgs = function(args) {
var a = Y.Array(args, 0, true), target;
if (Y.UA.gecko) {
a[0] = DOM_MOUSE_SCROLL;
target = Y.config.win;
} else {
target = Y.config.doc;
}
if (a.length < 3) {
a[2] = target;
} else {
a.splice(2, 0, target);
}
return a;
};
/**
* Mousewheel event. This listener is automatically attached to the
* correct target, so one should not be supplied. Mouse wheel
* direction and velocity is stored in the 'mouseDelta' field.
* @event mousewheel
* @param type {string} 'mousewheel'
* @param fn {function} the callback to execute
* @param context optional context object
* @param args 0..n additional arguments to provide to the listener.
* @return {EventHandle} the detach handle
* @for YUI
*/
Y.Env.evt.plugins.mousewheel = {
on: function() {
return Y.Event._attach(fixArgs(arguments));
},
detach: function() {
return Y.Event.detach.apply(Y.Event, fixArgs(arguments));
}
};
}, '@VERSION@' ,{requires:['node-base']});
YUI.add('event-mouseenter', function(Y) {
/**
* <p>Adds subscription and delegation support for mouseenter and mouseleave
* events. Unlike mouseover and mouseout, these events aren't fired from child
* elements of a subscribed node.</p>
*
* <p>This avoids receiving three mouseover notifications from a setup like</p>
*
* <pre><code>div#container > p > a[href]</code></pre>
*
* <p>where</p>
*
* <pre><code>Y.one('#container').on('mouseover', callback)</code></pre>
*
* <p>When the mouse moves over the link, one mouseover event is fired from
* #container, then when the mouse moves over the p, another mouseover event is
* fired and bubbles to #container, causing a second notification, and finally
* when the mouse moves over the link, a third mouseover event is fired and
* bubbles to #container for a third notification.</p>
*
* <p>By contrast, using mouseenter instead of mouseover, the callback would be
* executed only once when the mouse moves over #container.</p>
*
* @module event
* @submodule event-mouseenter
*/
var domEventProxies = Y.Env.evt.dom_wrappers,
contains = Y.DOM.contains,
toArray = Y.Array,
noop = function () {},
config = {
proxyType: "mouseover",
relProperty: "fromElement",
_notify: function (e, property, notifier) {
var el = this._node,
related = e.relatedTarget || e[property];
if (el !== related && !contains(el, related)) {
notifier.fire(new Y.DOMEventFacade(e, el,
domEventProxies['event:' + Y.stamp(el) + e.type]));
}
},
on: function (node, sub, notifier) {
var el = Y.Node.getDOMNode(node),
args = [
this.proxyType,
this._notify,
el,
null,
this.relProperty,
notifier];
sub.handle = Y.Event._attach(args, { facade: false });
// node.on(this.proxyType, notify, null, notifier);
},
detach: function (node, sub) {
sub.handle.detach();
},
delegate: function (node, sub, notifier, filter) {
var el = Y.Node.getDOMNode(node),
args = [
this.proxyType,
noop,
el,
null,
notifier
];
sub.handle = Y.Event._attach(args, { facade: false });
sub.handle.sub.filter = filter;
sub.handle.sub.relProperty = this.relProperty;
sub.handle.sub._notify = this._filterNotify;
},
_filterNotify: function (thisObj, args, ce) {
args = args.slice();
if (this.args) {
args.push.apply(args, this.args);
}
var currentTarget = Y.delegate._applyFilter(this.filter, args, ce),
related = args[0].relatedTarget || args[0][this.relProperty],
e, i, len, ret, ct;
if (currentTarget) {
currentTarget = toArray(currentTarget);
for (i = 0, len = currentTarget.length && (!e || !e.stopped); i < len; ++i) {
ct = currentTarget[0];
if (!contains(ct, related)) {
if (!e) {
e = new Y.DOMEventFacade(args[0], ct, ce);
e.container = Y.one(ce.el);
}
e.currentTarget = Y.one(ct);
// TODO: where is notifier? args? this.notifier?
ret = args[1].fire(e);
if (ret === false) {
break;
}
}
}
}
return ret;
},
detachDelegate: function (node, sub) {
sub.handle.detach();
}
};
Y.Event.define("mouseenter", config, true);
Y.Event.define("mouseleave", Y.merge(config, {
proxyType: "mouseout",
relProperty: "toElement"
}), true);
}, '@VERSION@' ,{requires:['event-synthetic']});
YUI.add('event-key', function(Y) {
/**
* Functionality to listen for one or more specific key combinations.
* @module event
* @submodule event-key
*/
var ALT = "+alt",
CTRL = "+ctrl",
META = "+meta",
SHIFT = "+shift",
isString = Y.Lang.isString,
trim = Y.Lang.trim,
eventDef = {
KEY_MAP: {
enter : 13,
esc : 27,
backspace: 8,
tab : 9,
pageup : 33,
pagedown : 34
},
_typeRE: /^(up|down|press):/,
processArgs: function (args) {
var spec = args.splice(3,1)[0],
mods = Y.Array.hash(spec.match(/\+(?:alt|ctrl|meta|shift)\b/g) || []),
config = {
type: this._typeRE.test(spec) ? RegExp.$1 : null,
keys: null
},
bits = spec
.replace(/^(?:up|down|press):|\+(alt|ctrl|meta|shift)/g, '')
.split(/,/),
chr, uc, lc, i;
spec = spec.replace(this._typeRE, '');
if (bits.length) {
config.keys = {};
// FIXME: need to support '65,esc' => keypress, keydown
for (i = bits.length - 1; i >= 0; --i) {
chr = trim(bits[i]);
// non-numerics are single characters or key names
if (+chr == chr) {
config.keys[chr] = mods;
} else {
lc = chr.toLowerCase();
if (this.KEY_MAP[lc]) {
config.keys[this.KEY_MAP[lc]] = mods;
// FIXME: '65,enter' defaults to keydown for both
if (!config.type) {
config.type = "down"; // safest
}
} else {
uc = chr.charAt(0).toUpperCase();
lc = lc.charAt(0);
// FIXME: possibly stupid assumption that
// the keycode of the lower case == the
// charcode of the upper case
// a (key:65,char:97), A (key:65,char:65)
config.keys[uc.charCodeAt(0)] =
(lc !== uc && chr === uc) ?
// upper case chars get +shift free
Y.merge(mods, { "+shift": true }) :
mods;
}
}
}
}
if (!config.type) {
config.type = "press";
}
return config;
},
on: function (node, sub, notifier, filter) {
var spec = sub._extra,
type = "key" + spec.type,
keys = spec.keys,
method = (filter) ? "delegate" : "on";
if (keys) {
sub._detach = node[method](type, function (e) {
var key = keys[e.keyCode];
if (key &&
(!key[ALT] || (key[ALT] && e.altKey)) &&
(!key[CTRL] || (key[CTRL] && e.ctrlKey)) &&
(!key[META] || (key[META] && e.metaKey)) &&
(!key[SHIFT] || (key[SHIFT] && e.shiftKey)))
{
notifier.fire(e);
}
}, filter);
} else {
// Pass through to a plain old key(up|down|press)
// Note: this is horribly inefficient, but I can't abort this
// subscription for a simple Y.on('keypress', ...);
sub._detach = node[method](type,
Y.bind(notifier.fire, notifier),
filter);
}
},
detach: function (node, sub, notifier) {
sub._detach.detach();
}
};
eventDef.delegate = eventDef.on;
eventDef.detachDelegate = eventDef.detach;
/**
* <p>Add a key listener. The listener will only be notified if the
* keystroke detected meets the supplied specification. The
* specification is a string that is defined as:</p>
*
* <dl>
* <dt>spec</dt>
* <dd><code>[{type}:]{code}[,{code}]*</dd>
* <dt>type</dt>
* <dd><code>"down", "up", or "press"</code></dd>
* <dt>code</dt>
* <dd><code>{keyCode|character|keyName}[+{modifier}]*</code></dd>
* <dt>modifier</dt>
* <dd><code>"shift", "ctrl", "alt", or "meta"</code></dd>
* <dt>keyName</dt>
* <dd><code>"enter", "backspace", "esc", "tab", "pageup", or "pagedown"</code></dd>
* </dl>
*
* <p>Examples:</p>
* <ul>
* <li><code>Y.on("key", callback, "press:12,65+shift+ctrl", "#my-input");</code></li>
* <li><code>Y.delegate("key", preventSubmit, "enter", "#forms", "input[type=text]");</code></li>
* <li><code>Y.one("doc").on("key", viNav, "j,k,l,;");</code></li>
* </ul>
*
* @event key
* @for YUI
* @param type {string} 'key'
* @param fn {function} the function to execute
* @param id {string|HTMLElement|collection} the element(s) to bind
* @param spec {string} the keyCode and modifier specification
* @param o optional context object
* @param args 0..n additional arguments to provide to the listener.
* @return {Event.Handle} the detach handle
*/
Y.Event.define('key', eventDef, true);
}, '@VERSION@' ,{requires:['event-synthetic']});
YUI.add('event-focus', function(Y) {
/**
* Adds bubbling and delegation support to DOM events focus and blur.
*
* @module event
* @submodule event-focus
*/
var Event = Y.Event,
YLang = Y.Lang,
isString = YLang.isString,
useActivate = YLang.isFunction(
Y.DOM.create('<p onbeforeactivate=";"/>').onbeforeactivate);
function define(type, proxy, directEvent) {
var nodeDataKey = '_' + type + 'Notifiers';
Y.Event.define(type, {
_attach: function (el, notifier, delegate) {
if (Y.DOM.isWindow(el)) {
return Event._attach([type, function (e) {
notifier.fire(e);
}, el]);
} else {
return Event._attach(
[proxy, this._proxy, el, this, notifier, delegate],
{ capture: true });
}
},
_proxy: function (e, notifier, delegate) {
var node = e.target,
notifiers = node.getData(nodeDataKey),
yuid = Y.stamp(e.currentTarget._node),
defer = (useActivate || e.target !== e.currentTarget),
sub = notifier.handle.sub,
filterArgs = [node, e].concat(sub.args || []),
directSub;
notifier.currentTarget = (delegate) ? node : e.currentTarget;
notifier.container = (delegate) ? e.currentTarget : null;
if (!sub.filter || sub.filter.apply(node, filterArgs)) {
// Maintain a list to handle subscriptions from nested
// containers div#a>div#b>input #a.on(focus..) #b.on(focus..),
// use one focus or blur subscription that fires notifiers from
// #b then #a to emulate bubble sequence.
if (!notifiers) {
notifiers = {};
node.setData(nodeDataKey, notifiers);
// only subscribe to the element's focus if the target is
// not the current target (
if (defer) {
directSub = Event._attach(
[directEvent, this._notify, node._node]).sub;
directSub.once = true;
}
}
if (!notifiers[yuid]) {
notifiers[yuid] = [];
}
notifiers[yuid].push(notifier);
if (!defer) {
this._notify(e);
}
}
},
_notify: function (e, container) {
var node = e.currentTarget,
notifiers = node.getData(nodeDataKey),
// document.get('ownerDocument') returns null
doc = node.get('ownerDocument') || node,
target = node,
nots = [],
notifier, i, len;
if (notifiers) {
// Walk up the parent axis until the origin node,
while (target && target !== doc) {
nots.push.apply(nots, notifiers[Y.stamp(target)] || []);
target = target.get('parentNode');
}
nots.push.apply(nots, notifiers[Y.stamp(doc)] || []);
for (i = 0, len = nots.length; i < len; ++i) {
notifier = nots[i];
e.currentTarget = nots[i].currentTarget;
if (notifier.container) {
e.container = notifier.container;
}
notifier.fire(e);
}
// clear the notifications list (mainly for delegation)
node.clearData(nodeDataKey);
}
},
on: function (node, sub, notifier) {
sub.onHandle = this._attach(node._node, notifier);
},
detach: function (node, sub) {
sub.onHandle.detach();
},
delegate: function (node, sub, notifier, filter) {
if (isString(filter)) {
sub.filter = Y.delegate.compileFilter(filter);
}
sub.delegateHandle = this._attach(node._node, notifier, true);
},
detachDelegate: function (node, sub) {
sub.delegateHandle.detach();
}
}, true);
}
// For IE, we need to defer to focusin rather than focus because
// `el.focus(); doSomething();` executes el.onbeforeactivate, el.onactivate,
// el.onfocusin, doSomething, then el.onfocus. All others support capture
// phase focus, which executes before doSomething. To guarantee consistent
// behavior for this use case, IE's direct subscriptions are made against
// focusin so subscribers will be notified before js following el.focus() is
// executed.
if (useActivate) {
// name capture phase direct subscription
define("focus", "beforeactivate", "focusin");
define("blur", "beforedeactivate", "focusout");
} else {
define("focus", "focus", "focus");
define("blur", "blur", "blur");
}
}, '@VERSION@' ,{requires:['event-synthetic']});
YUI.add('event-resize', function(Y) {
/**
* Adds a window resize event that has its behavior normalized to fire at the
* end of the resize rather than constantly during the resize.
* @module event
* @submodule event-resize
*/
(function() {
var detachHandle,
timerHandle,
CE_NAME = 'window:resize',
handler = function(e) {
if (Y.UA.gecko) {
Y.fire(CE_NAME, e);
} else {
if (timerHandle) {
timerHandle.cancel();
}
timerHandle = Y.later(Y.config.windowResizeDelay || 40, Y, function() {
Y.fire(CE_NAME, e);
});
}
};
/**
* Firefox fires the window resize event once when the resize action
* finishes, other browsers fire the event periodically during the
* resize. This code uses timeout logic to simulate the Firefox
* behavior in other browsers.
* @event windowresize
* @for YUI
*/
Y.Env.evt.plugins.windowresize = {
on: function(type, fn) {
// check for single window listener and add if needed
if (!detachHandle) {
detachHandle = Y.Event._attach(['resize', handler]);
}
var a = Y.Array(arguments, 0, true);
a[0] = CE_NAME;
return Y.on.apply(Y, a);
}
};
})();
}, '@VERSION@' ,{requires:['node-base']});
YUI.add('event-hover', function(Y) {
/**
* Adds support for a "hover" event. The event provides a convenience wrapper
* for subscribing separately to mouseenter and mouseleave. The signature for
* subscribing to the event is</p>
*
* <pre><code>node.on("hover", overFn, outFn);
* node.delegate("hover", overFn, outFn, ".filterSelector");
* Y.on("hover", overFn, outFn, ".targetSelector");
* Y.delegate("hover", overFn, outFn, "#container", ".filterSelector");
* </code></pre>
*
* <p>Additionally, for compatibility with a more typical subscription
* signature, the following are also supported:</p>
*
* <pre><code>Y.on("hover", overFn, ".targetSelector", outFn);
* Y.delegate("hover", overFn, "#container", outFn, ".filterSelector");
* </code></pre>
*
* @module event
* @submodule event-hover
*/
var isFunction = Y.Lang.isFunction,
noop = function () {},
conf = {
processArgs: function (args) {
// Y.delegate('hover', over, out, '#container', '.filter')
// comes in as ['hover', over, out, '#container', '.filter'], but
// node.delegate('hover', over, out, '.filter')
// comes in as ['hover', over, containerEl, out, '.filter']
var i = isFunction(args[2]) ? 2 : 3;
return (isFunction(args[i])) ? args.splice(i,1)[0] : noop;
},
on: function (node, sub, notifier, filter) {
sub._detach = node[(filter) ? "delegate" : "on"]({
mouseenter: function (e) {
e.phase = 'over';
notifier.fire(e);
},
mouseleave: function (e) {
var thisObj = sub.context || this;
e.type = 'hover';
e.phase = 'out';
sub._extra.apply(thisObj, [e].concat(sub.args));
}
}, filter);
},
detach: function (node, sub, notifier) {
sub._detach.detach();
}
};
conf.delegate = conf.on;
conf.detachDelegate = conf.detach;
Y.Event.define("hover", conf);
}, '@VERSION@' ,{requires:['event-mouseenter']});
YUI.add('event', function(Y){}, '@VERSION@' ,{use:['event-base', 'event-delegate', 'event-synthetic', 'event-mousewheel', 'event-mouseenter', 'event-key', 'event-focus', 'event-resize', 'event-hover']});
|
new-lamassu-admin/src/pages/Wizard/components/Commissions.js
|
lamassu/lamassu-server
|
import { useQuery, useMutation } from '@apollo/react-hooks'
import { makeStyles } from '@material-ui/core'
import gql from 'graphql-tag'
import * as R from 'ramda'
import React from 'react'
import { Table as EditableTable } from 'src/components/editableTable'
import Section from 'src/components/layout/Section'
import TitleSection from 'src/components/layout/TitleSection'
import styles from 'src/pages/AddMachine/styles'
import { mainFields, defaults, getSchema } from 'src/pages/Commissions/helper'
import { fromNamespace, toNamespace, namespaces } from 'src/utils/config'
const useStyles = makeStyles(styles)
const useCommissionStyles = makeStyles({
autoComplete: {
width: '100%'
}
})
const GET_DATA = gql`
query getData {
config
}
`
const SAVE_CONFIG = gql`
mutation Save($config: JSONObject) {
saveConfig(config: $config)
}
`
function Commissions({ isActive, doContinue }) {
const classes = useStyles()
const commissionClasses = useCommissionStyles()
const { data } = useQuery(GET_DATA)
const [saveConfig] = useMutation(SAVE_CONFIG, {
onCompleted: doContinue
})
const save = it => {
const config = toNamespace('commissions')(it.commissions[0])
return saveConfig({ variables: { config } })
}
const currency = R.path(['fiatCurrency'])(
fromNamespace(namespaces.LOCALE)(data?.config)
)
const locale = fromNamespace(namespaces.LOCALE)(data?.config)
return (
<div className={classes.wrapper}>
<TitleSection title="Commissions" />
<Section>
<EditableTable
title="Default setup"
rowSize="lg"
titleLg
name="commissions"
initialValues={defaults}
enableEdit
forceAdd={isActive}
save={save}
validationSchema={getSchema(locale)}
data={[]}
elements={mainFields(currency, locale, commissionClasses)}
/>
</Section>
</div>
)
}
export default Commissions
|
ajax/libs/primereact/6.6.0-rc.1/dock/dock.min.js
|
cdnjs/cdnjs
|
this.primereact=this.primereact||{},this.primereact.dock=function(e,t,n){"use strict";function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=r(t);function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function c(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function s(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function u(e,t){return(u=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&u(e,t)}function l(e){return(l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function f(e,t){return!t||"object"!==l(t)&&"function"!=typeof t?s(e):t}function p(e){return(p=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function m(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}var d,y,h,b=function(e){a(h,e);var t,r,u,l,d,y=(t=h,r=m(),function(){var e,n=p(t);if(r){var o=p(this).constructor;e=Reflect.construct(n,arguments,o)}else e=n.apply(this,arguments);return f(this,e)});function h(e){var t;return i(this,h),(t=y.call(this,e)).state={currentIndex:-3},t.onListMouseLeave=t.onListMouseLeave.bind(s(t)),t}return u=h,(l=[{key:"onListMouseLeave",value:function(){this.setState({currentIndex:-3})}},{key:"onItemMouseEnter",value:function(e){this.setState({currentIndex:e})}},{key:"onItemClick",value:function(e,t){t.command&&t.command({originalEvent:e,item:t}),e.preventDefault()}},{key:"renderItem",value:function(e,t){var r=this,i=e.disabled,c=e.icon,s=e.label,u=e.template,a=e.url,l=e.target,f=n.classNames("p-dock-item",{"p-dock-item-second-prev":this.state.currentIndex-2===t,"p-dock-item-prev":this.state.currentIndex-1===t,"p-dock-item-current":this.state.currentIndex===t,"p-dock-item-next":this.state.currentIndex+1===t,"p-dock-item-second-next":this.state.currentIndex+2===t}),p=n.classNames("p-dock-action",{"p-disabled":i}),m=n.classNames("p-dock-action-icon",c),d="string"==typeof c?o.default.createElement("span",{className:m}):n.ObjectUtils.getJSXElement(c,this.props),y=o.default.createElement("a",{href:a||"#",role:"menuitem",className:p,target:l,"data-pr-tooltip":s,onClick:function(t){return r.onItemClick(t,e)}},d,o.default.createElement(n.Ripple,null));return u&&(y=n.ObjectUtils.getJSXElement(u,e,{onClick:function(t){return r.onItemClick(t,e)},className:p,iconClassName:m,element:y,props:this.props,index:t})),o.default.createElement("li",{key:t,className:f,role:"none",onMouseEnter:function(){return r.onItemMouseEnter(t)}},y)}},{key:"renderItems",value:function(){var e=this;return this.props.model?this.props.model.map((function(t,n){return e.renderItem(t,n)})):null}},{key:"renderList",value:function(){var e=this,t=this.renderItems();return o.default.createElement("ul",{ref:function(t){return e.list=t},className:"p-dock-list",role:"menu",onMouseLeave:this.onListMouseLeave},t)}},{key:"render",value:function(){var e=n.classNames("p-dock p-component p-dock-".concat(this.props.position),this.props.className),t=this.renderList();return o.default.createElement("div",{id:this.props.id,className:e,style:this.props.style},o.default.createElement("div",{className:"p-dock-list-container"},t))}}])&&c(u.prototype,l),d&&c(u,d),h}(t.Component);return h={id:null,style:null,className:null,model:null,position:"bottom"},(y="defaultProps")in(d=b)?Object.defineProperty(d,y,{value:h,enumerable:!0,configurable:!0,writable:!0}):d[y]=h,e.Dock=b,Object.defineProperty(e,"__esModule",{value:!0}),e}({},React,primereact.core);
|
ajax/libs/react-modal/1.7.7/react-modal.js
|
froala/cdnjs
|
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"), require("react-dom"));
else if(typeof define === 'function' && define.amd)
define(["react", "react-dom"], factory);
else if(typeof exports === 'object')
exports["ReactModal"] = factory(require("react"), require("react-dom"));
else
root["ReactModal"] = factory(root["React"], root["ReactDOM"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_2__, __WEBPACK_EXTERNAL_MODULE_3__) {
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';
module.exports = __webpack_require__(1);
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var ReactDOM = __webpack_require__(3);
var PropTypes = __webpack_require__(4);
var ExecutionEnvironment = __webpack_require__(12);
var ModalPortal = React.createFactory(__webpack_require__(13));
var ariaAppHider = __webpack_require__(22);
var refCount = __webpack_require__(23);
var elementClass = __webpack_require__(24);
var renderSubtreeIntoContainer = __webpack_require__(3).unstable_renderSubtreeIntoContainer;
var Assign = __webpack_require__(17);
var createReactClass = __webpack_require__(18);
var SafeHTMLElement = ExecutionEnvironment.canUseDOM ? window.HTMLElement : {};
var AppElement = ExecutionEnvironment.canUseDOM ? document.body : { appendChild: function appendChild() {} };
function getParentElement(parentSelector) {
return parentSelector();
}
var Modal = createReactClass({
displayName: 'Modal',
statics: {
setAppElement: function setAppElement(element) {
AppElement = ariaAppHider.setElement(element);
},
injectCSS: function injectCSS() {
"production" !== (undefined) && console.warn('React-Modal: injectCSS has been deprecated ' + 'and no longer has any effect. It will be removed in a later version');
}
},
propTypes: {
isOpen: PropTypes.bool.isRequired,
style: PropTypes.shape({
content: PropTypes.object,
overlay: PropTypes.object
}),
portalClassName: PropTypes.string,
appElement: PropTypes.instanceOf(SafeHTMLElement),
onAfterOpen: PropTypes.func,
onRequestClose: PropTypes.func,
closeTimeoutMS: PropTypes.number,
ariaHideApp: PropTypes.bool,
shouldCloseOnOverlayClick: PropTypes.bool,
parentSelector: PropTypes.func,
role: PropTypes.string,
contentLabel: PropTypes.string.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
isOpen: false,
portalClassName: 'ReactModalPortal',
ariaHideApp: true,
closeTimeoutMS: 0,
shouldCloseOnOverlayClick: true,
parentSelector: function parentSelector() {
return document.body;
}
};
},
componentDidMount: function componentDidMount() {
this.node = document.createElement('div');
this.node.className = this.props.portalClassName;
if (this.props.isOpen) refCount.add(this);
var parent = getParentElement(this.props.parentSelector);
parent.appendChild(this.node);
this.renderPortal(this.props);
},
componentWillReceiveProps: function componentWillReceiveProps(newProps) {
if (newProps.isOpen) refCount.add(this);
if (!newProps.isOpen) refCount.remove(this);
var currentParent = getParentElement(this.props.parentSelector);
var newParent = getParentElement(newProps.parentSelector);
if (newParent !== currentParent) {
currentParent.removeChild(this.node);
newParent.appendChild(this.node);
}
this.renderPortal(newProps);
},
componentWillUnmount: function componentWillUnmount() {
refCount.remove(this);
if (this.props.ariaHideApp) {
ariaAppHider.show(this.props.appElement);
}
var state = this.portal.state;
var now = Date.now();
var closesAt = state.isOpen && this.props.closeTimeoutMS && (state.closesAt || now + this.props.closeTimeoutMS);
if (closesAt) {
if (!state.beforeClose) {
this.portal.closeWithTimeout();
}
var that = this;
setTimeout(function () {
that.removePortal();
}, closesAt - now);
} else {
this.removePortal();
}
},
removePortal: function removePortal() {
ReactDOM.unmountComponentAtNode(this.node);
var parent = getParentElement(this.props.parentSelector);
parent.removeChild(this.node);
if (refCount.count() === 0) {
elementClass(document.body).remove('ReactModal__Body--open');
}
},
renderPortal: function renderPortal(props) {
if (props.isOpen || refCount.count() > 0) {
elementClass(document.body).add('ReactModal__Body--open');
} else {
elementClass(document.body).remove('ReactModal__Body--open');
}
if (props.ariaHideApp) {
ariaAppHider.toggle(props.isOpen, props.appElement);
}
this.portal = renderSubtreeIntoContainer(this, ModalPortal(Assign({}, props, { defaultStyles: Modal.defaultStyles })), this.node);
},
render: function render() {
return React.DOM.noscript();
}
});
Modal.defaultStyles = {
overlay: {
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'rgba(255, 255, 255, 0.75)'
},
content: {
position: 'absolute',
top: '40px',
left: '40px',
right: '40px',
bottom: '40px',
border: '1px solid #ccc',
background: '#fff',
overflow: 'auto',
WebkitOverflowScrolling: 'touch',
borderRadius: '4px',
outline: 'none',
padding: '20px'
}
};
module.exports = Modal;
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_2__;
/***/ },
/* 3 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_3__;
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
/**
* 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.
*/
if ((undefined) !== 'production') {
var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' &&
Symbol.for &&
Symbol.for('react.element')) ||
0xeac7;
var isValidElement = function(object) {
return typeof object === 'object' &&
object !== null &&
object.$$typeof === REACT_ELEMENT_TYPE;
};
// By explicitly using `prop-types` you are opting into new development behavior.
// http://fb.me/prop-types-in-prod
var throwOnDirectAccess = true;
module.exports = __webpack_require__(5)(isValidElement, throwOnDirectAccess);
} else {
// By explicitly using `prop-types` you are opting into new production behavior.
// http://fb.me/prop-types-in-prod
module.exports = __webpack_require__(11)();
}
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
/**
* 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.
*/
'use strict';
var emptyFunction = __webpack_require__(6);
var invariant = __webpack_require__(7);
var warning = __webpack_require__(8);
var ReactPropTypesSecret = __webpack_require__(9);
var checkPropTypes = __webpack_require__(10);
module.exports = function(isValidElement, throwOnDirectAccess) {
/* global Symbol */
var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
/**
* Returns the iterator method function contained on the iterable object.
*
* Be sure to invoke the function with the iterable as context:
*
* var iteratorFn = getIteratorFn(myIterable);
* if (iteratorFn) {
* var iterator = iteratorFn.call(myIterable);
* ...
* }
*
* @param {?object} maybeIterable
* @return {?function}
*/
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
/**
* 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>>';
// Important!
// Keep this list in sync with production version in `./factoryWithThrowingShims.js`.
var ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
symbol: createPrimitiveTypeChecker('symbol'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker
};
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
/*eslint-disable no-self-compare*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/*eslint-enable no-self-compare*/
/**
* We use an Error-like object for backward compatibility as people may call
* PropTypes directly and inspect their output. However, we don't use real
* Errors anymore. We don't inspect their stack anyway, and creating them
* is prohibitively expensive if they are created too often, such as what
* happens in oneOfType() for any type before the one that matched.
*/
function PropTypeError(message) {
this.message = message;
this.stack = '';
}
// Make `instanceof Error` still work for returned errors.
PropTypeError.prototype = Error.prototype;
function createChainableTypeChecker(validate) {
if ((undefined) !== 'production') {
var manualPropTypeCallCache = {};
}
function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (secret !== ReactPropTypesSecret) {
if (throwOnDirectAccess) {
// New behavior only for users of `prop-types` package
invariant(
false,
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use `PropTypes.checkPropTypes()` to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
} else if ((undefined) !== 'production' && typeof console !== 'undefined') {
// Old behavior for people using React.PropTypes
var cacheKey = componentName + ':' + propName;
if (!manualPropTypeCallCache[cacheKey]) {
warning(
false,
'You are manually calling a React.PropTypes validation ' +
'function for the `%s` prop on `%s`. This is deprecated ' +
'and will throw in the standalone `prop-types` package. ' +
'You may be seeing this warning due to a third-party PropTypes ' +
'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.',
propFullName,
componentName
);
manualPropTypeCallCache[cacheKey] = true;
}
}
}
if (props[propName] == null) {
if (isRequired) {
if (props[propName] === null) {
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));
}
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));
}
return null;
} else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location, propFullName, secret) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
// `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 PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunction.thatReturnsNull);
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
}
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret);
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!isValidElement(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location, propFullName) {
if (!(props[propName] instanceof expectedClass)) {
var expectedClassName = expectedClass.name || ANONYMOUS;
var actualClassName = getClassName(props[propName]);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
if (!Array.isArray(expectedValues)) {
(undefined) !== 'production' ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0;
return emptyFunction.thatReturnsNull;
}
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (is(propValue, expectedValues[i])) {
return null;
}
}
var valuesString = JSON.stringify(expectedValues);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
}
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` 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, propFullName + '.' + key, ReactPropTypesSecret);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
(undefined) !== 'production' ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0;
return emptyFunction.thatReturnsNull;
}
function validate(props, propName, componentName, location, propFullName) {
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) {
return null;
}
}
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!isNode(props[propName])) {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` 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, propFullName + '.' + key, ReactPropTypesSecret);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case 'number':
case 'string':
case 'undefined':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isNode);
}
if (propValue === null || isValidElement(propValue)) {
return true;
}
var iteratorFn = getIteratorFn(propValue);
if (iteratorFn) {
var iterator = iteratorFn.call(propValue);
var step;
if (iteratorFn !== propValue.entries) {
while (!(step = iterator.next()).done) {
if (!isNode(step.value)) {
return false;
}
}
} else {
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
if (!isNode(entry[1])) {
return false;
}
}
}
}
} else {
return false;
}
return true;
default:
return false;
}
}
function isSymbol(propType, propValue) {
// Native Symbol.
if (propType === 'symbol') {
return true;
}
// 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
if (propValue['@@toStringTag'] === 'Symbol') {
return true;
}
// Fallback for non-spec compliant Symbols which are polyfilled.
if (typeof Symbol === 'function' && propValue instanceof Symbol) {
return true;
}
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';
}
if (isSymbol(propType, propValue)) {
return 'symbol';
}
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;
}
// Returns class name of the object, if any.
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return ANONYMOUS;
}
return propValue.constructor.name;
}
ReactPropTypes.checkPropTypes = checkPropTypes;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
/***/ },
/* 6 */
/***/ function(module, exports) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
function makeEmptyFunction(arg) {
return function () {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
var emptyFunction = function emptyFunction() {};
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function () {
return this;
};
emptyFunction.thatReturnsArgument = function (arg) {
return arg;
};
module.exports = emptyFunction;
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'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 validateFormat = function validateFormat(format) {};
if ((undefined) !== 'production') {
validateFormat = function validateFormat(format) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
};
}
function invariant(condition, format, a, b, c, d, e, f) {
validateFormat(format);
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
/***/ },
/* 8 */
/***/ 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';
var emptyFunction = __webpack_require__(6);
/**
* 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 ((undefined) !== 'production') {
(function () {
var printWarning = function printWarning(format) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// 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) {}
};
warning = function warning(condition, format) {
if (format === undefined) {
throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (format.indexOf('Failed Composite propType: ') === 0) {
return; // Ignore CompositeComponent proptype check.
}
if (!condition) {
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
printWarning.apply(undefined, [format].concat(args));
}
};
})();
}
module.exports = warning;
/***/ },
/* 9 */
/***/ function(module, exports) {
/**
* 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.
*/
'use strict';
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
module.exports = ReactPropTypesSecret;
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
/**
* 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.
*/
'use strict';
if ((undefined) !== 'production') {
var invariant = __webpack_require__(7);
var warning = __webpack_require__(8);
var ReactPropTypesSecret = __webpack_require__(9);
var loggedTypeFailures = {};
}
/**
* Assert that the values match with the type specs.
* Error messages are memorized and will only be shown once.
*
* @param {object} typeSpecs Map of name to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @param {string} componentName Name of the component for error messages.
* @param {?Function} getStack Returns the component stack.
* @private
*/
function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
if ((undefined) !== 'production') {
for (var typeSpecName in typeSpecs) {
if (typeSpecs.hasOwnProperty(typeSpecName)) {
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 {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
invariant(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', location, typeSpecName);
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
} catch (ex) {
error = ex;
}
warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error);
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;
var stack = getStack ? getStack() : '';
warning(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : '');
}
}
}
}
}
module.exports = checkPropTypes;
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
/**
* 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.
*/
'use strict';
var emptyFunction = __webpack_require__(6);
var invariant = __webpack_require__(7);
module.exports = function() {
// Important!
// Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
function shim() {
invariant(
false,
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use PropTypes.checkPropTypes() to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
};
shim.isRequired = shim;
function getShim() {
return shim;
};
var ReactPropTypes = {
array: shim,
bool: shim,
func: shim,
number: shim,
object: shim,
string: shim,
symbol: shim,
any: shim,
arrayOf: getShim,
element: shim,
instanceOf: getShim,
node: shim,
objectOf: getShim,
oneOf: getShim,
oneOfType: getShim,
shape: getShim
};
ReactPropTypes.checkPropTypes = emptyFunction;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;/*!
Copyright (c) 2015 Jed Watson.
Based on code that is Copyright 2013-2015, Facebook, Inc.
All rights reserved.
*/
(function () {
'use strict';
var canUseDOM = !!(
typeof window !== 'undefined' &&
window.document &&
window.document.createElement
);
var ExecutionEnvironment = {
canUseDOM: canUseDOM,
canUseWorkers: typeof Worker !== 'undefined',
canUseEventListeners:
canUseDOM && !!(window.addEventListener || window.attachEvent),
canUseViewport: canUseDOM && !!window.screen
};
if (true) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = function () {
return ExecutionEnvironment;
}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = ExecutionEnvironment;
} else {
window.ExecutionEnvironment = ExecutionEnvironment;
}
}());
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var div = React.DOM.div;
var focusManager = __webpack_require__(14);
var scopeTab = __webpack_require__(16);
var Assign = __webpack_require__(17);
var createReactClass = __webpack_require__(18);
// so that our CSS is statically analyzable
var CLASS_NAMES = {
overlay: {
base: 'ReactModal__Overlay',
afterOpen: 'ReactModal__Overlay--after-open',
beforeClose: 'ReactModal__Overlay--before-close'
},
content: {
base: 'ReactModal__Content',
afterOpen: 'ReactModal__Content--after-open',
beforeClose: 'ReactModal__Content--before-close'
}
};
var ModalPortal = module.exports = createReactClass({
displayName: 'ModalPortal',
shouldClose: null,
getDefaultProps: function getDefaultProps() {
return {
style: {
overlay: {},
content: {}
}
};
},
getInitialState: function getInitialState() {
return {
afterOpen: false,
beforeClose: false
};
},
componentDidMount: function componentDidMount() {
// Focus needs to be set when mounting and already open
if (this.props.isOpen) {
this.setFocusAfterRender(true);
this.open();
}
},
componentWillUnmount: function componentWillUnmount() {
clearTimeout(this.closeTimer);
},
componentWillReceiveProps: function componentWillReceiveProps(newProps) {
// Focus only needs to be set once when the modal is being opened
if (!this.props.isOpen && newProps.isOpen) {
this.setFocusAfterRender(true);
this.open();
} else if (this.props.isOpen && !newProps.isOpen) {
this.close();
}
},
componentDidUpdate: function componentDidUpdate() {
if (this.focusAfterRender) {
this.focusContent();
this.setFocusAfterRender(false);
}
},
setFocusAfterRender: function setFocusAfterRender(focus) {
this.focusAfterRender = focus;
},
afterClose: function afterClose() {
focusManager.returnFocus();
focusManager.teardownScopedFocus();
},
open: function open() {
if (this.state.afterOpen && this.state.beforeClose) {
clearTimeout(this.closeTimer);
this.setState({ beforeClose: false });
} else {
focusManager.setupScopedFocus(this.node);
focusManager.markForFocusLater();
this.setState({ isOpen: true }, function () {
this.setState({ afterOpen: true });
if (this.props.isOpen && this.props.onAfterOpen) {
this.props.onAfterOpen();
}
}.bind(this));
}
},
close: function close() {
if (this.props.closeTimeoutMS > 0) this.closeWithTimeout();else this.closeWithoutTimeout();
},
focusContent: function focusContent() {
// Don't steal focus from inner elements
if (!this.contentHasFocus()) {
this.refs.content.focus();
}
},
closeWithTimeout: function closeWithTimeout() {
var closesAt = Date.now() + this.props.closeTimeoutMS;
this.setState({ beforeClose: true, closesAt: closesAt }, function () {
this.closeTimer = setTimeout(this.closeWithoutTimeout, this.state.closesAt - Date.now());
}.bind(this));
},
closeWithoutTimeout: function closeWithoutTimeout() {
this.setState({
beforeClose: false,
isOpen: false,
afterOpen: false,
closesAt: null
}, this.afterClose);
},
handleKeyDown: function handleKeyDown(event) {
if (event.keyCode == 9 /*tab*/) scopeTab(this.refs.content, event);
if (event.keyCode == 27 /*esc*/) {
event.preventDefault();
this.requestClose(event);
}
},
handleOverlayOnClick: function handleOverlayOnClick(event) {
if (this.shouldClose === null) {
this.shouldClose = true;
}
if (this.shouldClose && this.props.shouldCloseOnOverlayClick) {
if (this.ownerHandlesClose()) this.requestClose(event);else this.focusContent();
}
this.shouldClose = null;
},
handleContentOnClick: function handleContentOnClick() {
this.shouldClose = false;
},
requestClose: function requestClose(event) {
if (this.ownerHandlesClose()) this.props.onRequestClose(event);
},
ownerHandlesClose: function ownerHandlesClose() {
return this.props.onRequestClose;
},
shouldBeClosed: function shouldBeClosed() {
return !this.state.isOpen && !this.state.beforeClose;
},
contentHasFocus: function contentHasFocus() {
return document.activeElement === this.refs.content || this.refs.content.contains(document.activeElement);
},
buildClassName: function buildClassName(which, additional) {
var className = CLASS_NAMES[which].base;
if (this.state.afterOpen) className += ' ' + CLASS_NAMES[which].afterOpen;
if (this.state.beforeClose) className += ' ' + CLASS_NAMES[which].beforeClose;
return additional ? className + ' ' + additional : className;
},
render: function render() {
var contentStyles = this.props.className ? {} : this.props.defaultStyles.content;
var overlayStyles = this.props.overlayClassName ? {} : this.props.defaultStyles.overlay;
return this.shouldBeClosed() ? div() : div({
ref: "overlay",
className: this.buildClassName('overlay', this.props.overlayClassName),
style: Assign({}, overlayStyles, this.props.style.overlay || {}),
onClick: this.handleOverlayOnClick
}, div({
ref: "content",
style: Assign({}, contentStyles, this.props.style.content || {}),
className: this.buildClassName('content', this.props.className),
tabIndex: "-1",
onKeyDown: this.handleKeyDown,
onClick: this.handleContentOnClick,
role: this.props.role,
"aria-label": this.props.contentLabel
}, this.props.children));
}
});
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var findTabbable = __webpack_require__(15);
var focusLaterElements = [];
var modalElement = null;
var needToFocus = false;
function handleBlur(event) {
needToFocus = true;
}
function handleFocus(event) {
if (needToFocus) {
needToFocus = false;
if (!modalElement) {
return;
}
// need to see how jQuery shims document.on('focusin') so we don't need the
// setTimeout, firefox doesn't support focusin, if it did, we could focus
// the element outside of a setTimeout. Side-effect of this implementation
// is that the document.body gets focus, and then we focus our element right
// after, seems fine.
setTimeout(function () {
if (modalElement.contains(document.activeElement)) return;
var el = findTabbable(modalElement)[0] || modalElement;
el.focus();
}, 0);
}
}
exports.markForFocusLater = function () {
focusLaterElements.push(document.activeElement);
};
exports.returnFocus = function () {
var toFocus = null;
try {
toFocus = focusLaterElements.pop();
toFocus.focus();
return;
} catch (e) {
console.warn('You tried to return focus to ' + toFocus + ' but it is not in the DOM anymore');
}
};
exports.setupScopedFocus = function (element) {
modalElement = element;
if (window.addEventListener) {
window.addEventListener('blur', handleBlur, false);
document.addEventListener('focus', handleFocus, true);
} else {
window.attachEvent('onBlur', handleBlur);
document.attachEvent('onFocus', handleFocus);
}
};
exports.teardownScopedFocus = function () {
modalElement = null;
if (window.addEventListener) {
window.removeEventListener('blur', handleBlur);
document.removeEventListener('focus', handleFocus);
} else {
window.detachEvent('onBlur', handleBlur);
document.detachEvent('onFocus', handleFocus);
}
};
/***/ },
/* 15 */
/***/ function(module, exports) {
'use strict';
/*!
* Adapted from jQuery UI core
*
* http://jqueryui.com
*
* Copyright 2014 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/category/ui-core/
*/
function focusable(element, isTabIndexNotNaN) {
var nodeName = element.nodeName.toLowerCase();
return (/input|select|textarea|button|object/.test(nodeName) ? !element.disabled : "a" === nodeName ? element.href || isTabIndexNotNaN : isTabIndexNotNaN) && visible(element);
}
function hidden(el) {
return el.offsetWidth <= 0 && el.offsetHeight <= 0 || el.style.display === 'none';
}
function visible(element) {
while (element) {
if (element === document.body) break;
if (hidden(element)) return false;
element = element.parentNode;
}
return true;
}
function tabbable(element) {
var tabIndex = element.getAttribute('tabindex');
if (tabIndex === null) tabIndex = undefined;
var isTabIndexNaN = isNaN(tabIndex);
return (isTabIndexNaN || tabIndex >= 0) && focusable(element, !isTabIndexNaN);
}
function findTabbableDescendants(element) {
return [].slice.call(element.querySelectorAll('*'), 0).filter(function (el) {
return tabbable(el);
});
}
module.exports = findTabbableDescendants;
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var findTabbable = __webpack_require__(15);
module.exports = function (node, event) {
var tabbable = findTabbable(node);
if (!tabbable.length) {
event.preventDefault();
return;
}
var finalTabbable = tabbable[event.shiftKey ? 0 : tabbable.length - 1];
var leavingFinalTabbable = finalTabbable === document.activeElement ||
// handle immediate shift+tab after opening with mouse
node === document.activeElement;
if (!leavingFinalTabbable) return;
event.preventDefault();
var target = tabbable[event.shiftKey ? tabbable.length - 1 : 0];
target.focus();
};
/***/ },
/* 17 */
/***/ function(module, exports) {
/**
* lodash (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]';
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/**
* A faster alternative to `Function#apply`, this function invokes `func`
* with the `this` binding of `thisArg` and the arguments of `args`.
*
* @private
* @param {Function} func The function to invoke.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} args The arguments to invoke `func` with.
* @returns {*} Returns the result of `func`.
*/
function apply(func, thisArg, args) {
switch (args.length) {
case 0: return func.call(thisArg);
case 1: return func.call(thisArg, args[0]);
case 2: return func.call(thisArg, args[0], args[1]);
case 3: return func.call(thisArg, args[0], args[1], args[2]);
}
return func.apply(thisArg, args);
}
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = overArg(Object.keys, Object),
nativeMax = Math.max;
/** Detect if properties shadowing those on `Object.prototype` are non-enumerable. */
var nonEnumShadows = !propertyIsEnumerable.call({ 'valueOf': 1 }, 'valueOf');
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
// Safari 8.1 makes `arguments.callee` enumerable in strict mode.
// Safari 9 makes `arguments.length` enumerable in strict mode.
var result = (isArray(value) || isArguments(value))
? baseTimes(value.length, String)
: [];
var length = result.length,
skipIndexes = !!length;
for (var key in value) {
if ((inherited || hasOwnProperty.call(value, key)) &&
!(skipIndexes && (key == 'length' || isIndex(key, length)))) {
result.push(key);
}
}
return result;
}
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignValue(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
(value === undefined && !(key in object))) {
object[key] = value;
}
}
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
/**
* The base implementation of `_.rest` which doesn't validate or coerce arguments.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
*/
function baseRest(func, start) {
start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
index = -1;
var otherArgs = Array(start + 1);
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
};
}
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @param {Function} [customizer] The function to customize copied values.
* @returns {Object} Returns `object`.
*/
function copyObject(source, props, object, customizer) {
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
var newValue = customizer
? customizer(object[key], source[key], key, object, source)
: undefined;
assignValue(object, key, newValue === undefined ? source[key] : newValue);
}
return object;
}
/**
* Creates a function like `_.assign`.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return baseRest(function(object, sources) {
var index = -1,
length = sources.length,
customizer = length > 1 ? sources[length - 1] : undefined,
guard = length > 2 ? sources[2] : undefined;
customizer = (assigner.length > 3 && typeof customizer == 'function')
? (length--, customizer)
: undefined;
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? undefined : customizer;
length = 1;
}
object = Object(object);
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, index, customizer);
}
}
return object;
});
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length &&
(typeof value == 'number' || reIsUint.test(value)) &&
(value > -1 && value % 1 == 0 && value < length);
}
/**
* Checks if the given arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call,
* else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike(object) && isIndex(index, object.length))
: (type == 'string' && index in object)
) {
return eq(object[index], value);
}
return false;
}
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
// Safari 8.1 makes `arguments.callee` enumerable in strict mode.
return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
(!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
}
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 8-9 which returns 'object' for typed array and other constructors.
var tag = isObject(value) ? objectToString.call(value) : '';
return tag == funcTag || tag == genTag;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Assigns own enumerable string keyed properties of source objects to the
* destination object. Source objects are applied from left to right.
* Subsequent sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object` and is loosely based on
* [`Object.assign`](https://mdn.io/Object/assign).
*
* @static
* @memberOf _
* @since 0.10.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.assignIn
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* function Bar() {
* this.c = 3;
* }
*
* Foo.prototype.b = 2;
* Bar.prototype.d = 4;
*
* _.assign({ 'a': 0 }, new Foo, new Bar);
* // => { 'a': 1, 'c': 3 }
*/
var assign = createAssigner(function(object, source) {
if (nonEnumShadows || isPrototype(source) || isArrayLike(source)) {
copyObject(source, keys(source), object);
return;
}
for (var key in source) {
if (hasOwnProperty.call(source, key)) {
assignValue(object, key, source[key]);
}
}
});
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
module.exports = assign;
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
/**
* 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.
*
*/
'use strict';
var React = __webpack_require__(2);
var factory = __webpack_require__(19);
// Hack to grab NoopUpdateQueue from isomorphic React
var ReactNoopUpdateQueue = new React.Component().updater;
module.exports = factory(
React.Component,
React.isValidElement,
ReactNoopUpdateQueue
);
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
/**
* 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.
*
*/
'use strict';
var _assign = __webpack_require__(20);
var emptyObject = __webpack_require__(21);
var _invariant = __webpack_require__(7);
if ((undefined) !== 'production') {
var warning = __webpack_require__(8);
}
var MIXINS_KEY = 'mixins';
// Helper function to allow the creation of anonymous functions which do not
// have .name set to the name of the variable being assigned to.
function identity(fn) {
return fn;
}
var ReactPropTypeLocationNames;
if ((undefined) !== 'production') {
ReactPropTypeLocationNames = {
prop: 'prop',
context: 'context',
childContext: 'child context',
};
} else {
ReactPropTypeLocationNames = {};
}
function factory(ReactComponent, isValidElement, ReactNoopUpdateQueue) {
/**
* Policies that describe methods in `ReactClassInterface`.
*/
var injectedMixins = [];
/**
* Composite components are higher-level components that compose other composite
* or host components.
*
* To create a new type of `ReactClass`, 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 `ReactClassInterface` for
* more the comprehensive protocol. Any other properties and methods in the
* class specification will be available on the prototype.
*
* @interface ReactClassInterface
* @internal
*/
var ReactClassInterface = {
/**
* An array of Mixin objects to include when defining your component.
*
* @type {array}
* @optional
*/
mixins: '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: 'DEFINE_MANY',
/**
* Definition of prop types for this component.
*
* @type {object}
* @optional
*/
propTypes: 'DEFINE_MANY',
/**
* Definition of context types for this component.
*
* @type {object}
* @optional
*/
contextTypes: 'DEFINE_MANY',
/**
* Definition of context types this component sets for its children.
*
* @type {object}
* @optional
*/
childContextTypes: '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: '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: 'DEFINE_MANY_MERGED',
/**
* @return {object}
* @optional
*/
getChildContext: '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: '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: '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: '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: '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: '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: '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: '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: '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: '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) {
if ((undefined) !== 'production') {
validateTypeDef(Constructor, childContextTypes, 'childContext');
}
Constructor.childContextTypes = _assign({}, Constructor.childContextTypes, childContextTypes);
},
contextTypes: function (Constructor, contextTypes) {
if ((undefined) !== 'production') {
validateTypeDef(Constructor, contextTypes, 'context');
}
Constructor.contextTypes = _assign({}, 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) {
if ((undefined) !== 'production') {
validateTypeDef(Constructor, propTypes, 'prop');
}
Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes);
},
statics: function (Constructor, statics) {
mixStaticSpecIntoComponent(Constructor, statics);
},
autobind: function () {} };
function validateTypeDef(Constructor, typeDef, location) {
for (var propName in typeDef) {
if (typeDef.hasOwnProperty(propName)) {
// use a warning instead of an _invariant so components
// don't show up in prod but only in __DEV__
(undefined) !== 'production' ? warning(typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName) : void 0;
}
}
}
function validateMethodOverride(isAlreadyDefined, name) {
var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null;
// Disallow overriding of base class methods unless explicitly allowed.
if (ReactClassMixin.hasOwnProperty(name)) {
_invariant(specPolicy === 'OVERRIDE_BASE', 'ReactClassInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name);
}
// Disallow defining methods more than once unless explicitly allowed.
if (isAlreadyDefined) {
_invariant(specPolicy === 'DEFINE_MANY' || specPolicy === 'DEFINE_MANY_MERGED', 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name);
}
}
/**
* Mixin helper which handles policy validation and reserved
* specification keys when building React classes.
*/
function mixSpecIntoComponent(Constructor, spec) {
if (!spec) {
if ((undefined) !== 'production') {
var typeofSpec = typeof spec;
var isMixinValid = typeofSpec === 'object' && spec !== null;
(undefined) !== 'production' ? warning(isMixinValid, '%s: You\'re attempting to include a mixin that is either null ' + 'or not an object. Check the mixins included by the component, ' + 'as well as any mixins they include themselves. ' + 'Expected object but got %s.', Constructor.displayName || 'ReactClass', spec === null ? null : typeofSpec) : void 0;
}
return;
}
_invariant(typeof spec !== 'function', 'ReactClass: You\'re attempting to ' + 'use a component class or function as a mixin. Instead, just use a ' + 'regular object.');
_invariant(!isValidElement(spec), 'ReactClass: You\'re attempting to ' + 'use a component as a mixin. Instead, just use a regular object.');
var proto = Constructor.prototype;
var autoBindPairs = proto.__reactAutoBindPairs;
// By handling mixins before any other properties, we ensure the same
// chaining order is applied to methods with DEFINE_MANY policy, whether
// mixins are listed before or after these methods in the spec.
if (spec.hasOwnProperty(MIXINS_KEY)) {
RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins);
}
for (var name in spec) {
if (!spec.hasOwnProperty(name)) {
continue;
}
if (name === MIXINS_KEY) {
// We have already handled mixins in a special case above.
continue;
}
var property = spec[name];
var isAlreadyDefined = proto.hasOwnProperty(name);
validateMethodOverride(isAlreadyDefined, 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 ReactClass methods (in the "interface").
// 2. Overridden methods (that were mixed in).
var isReactClassMethod = ReactClassInterface.hasOwnProperty(name);
var isFunction = typeof property === 'function';
var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false;
if (shouldAutoBind) {
autoBindPairs.push(name, property);
proto[name] = property;
} else {
if (isAlreadyDefined) {
var specPolicy = ReactClassInterface[name];
// These cases should already be caught by validateMethodOverride.
_invariant(isReactClassMethod && (specPolicy === 'DEFINE_MANY_MERGED' || specPolicy === 'DEFINE_MANY'), 'ReactClass: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name);
// For methods which are defined more than once, call the existing
// methods before calling the new property, merging if appropriate.
if (specPolicy === 'DEFINE_MANY_MERGED') {
proto[name] = createMergedResultFunction(proto[name], property);
} else if (specPolicy === 'DEFINE_MANY') {
proto[name] = createChainedFunction(proto[name], property);
}
} else {
proto[name] = property;
if ((undefined) !== 'production') {
// 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 isReserved = name in RESERVED_SPEC_KEYS;
_invariant(!isReserved, 'ReactClass: You are attempting to define a reserved ' + 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' + 'as an instance property instead; it will still be accessible on the ' + 'constructor.', name);
var isInherited = name in Constructor;
_invariant(!isInherited, 'ReactClass: You are attempting to define ' + '`%s` on your component more than once. This conflict may be ' + 'due to a mixin.', name);
Constructor[name] = property;
}
}
/**
* 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 mergeIntoWithNoDuplicateKeys(one, two) {
_invariant(one && two && typeof one === 'object' && typeof two === 'object', 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.');
for (var key in two) {
if (two.hasOwnProperty(key)) {
_invariant(one[key] === undefined, 'mergeIntoWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: `%s`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.', key);
one[key] = two[key];
}
}
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;
}
var c = {};
mergeIntoWithNoDuplicateKeys(c, a);
mergeIntoWithNoDuplicateKeys(c, b);
return c;
};
}
/**
* 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);
};
}
/**
* Binds a method to the component.
*
* @param {object} component Component whose method is going to be bound.
* @param {function} method Method to be bound.
* @return {function} The bound method.
*/
function bindAutoBindMethod(component, method) {
var boundMethod = method.bind(component);
if ((undefined) !== 'production') {
boundMethod.__reactBoundContext = component;
boundMethod.__reactBoundMethod = method;
boundMethod.__reactBoundArguments = null;
var componentName = component.constructor.displayName;
var _bind = boundMethod.bind;
boundMethod.bind = function (newThis) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
// 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) {
(undefined) !== 'production' ? warning(false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName) : void 0;
} else if (!args.length) {
(undefined) !== 'production' ? warning(false, '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 %s', componentName) : void 0;
return boundMethod;
}
var reboundMethod = _bind.apply(boundMethod, arguments);
reboundMethod.__reactBoundContext = component;
reboundMethod.__reactBoundMethod = method;
reboundMethod.__reactBoundArguments = args;
return reboundMethod;
};
}
return boundMethod;
}
/**
* Binds all auto-bound methods in a component.
*
* @param {object} component Component whose method is going to be bound.
*/
function bindAutoBindMethods(component) {
var pairs = component.__reactAutoBindPairs;
for (var i = 0; i < pairs.length; i += 2) {
var autoBindKey = pairs[i];
var method = pairs[i + 1];
component[autoBindKey] = bindAutoBindMethod(component, method);
}
}
var IsMountedMixin = {
componentDidMount: function () {
this.__isMounted = true;
},
componentWillUnmount: function () {
this.__isMounted = false;
}
};
/**
* Add more to the ReactClass base class. These are all legacy features and
* therefore not already part of the modern ReactComponent.
*/
var ReactClassMixin = {
/**
* TODO: This will be deprecated because state should always keep a consistent
* type signature and the only use case for this, is to avoid that.
*/
replaceState: function (newState, callback) {
this.updater.enqueueReplaceState(this, newState, callback);
},
/**
* Checks whether or not this composite component is mounted.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function () {
if ((undefined) !== 'production') {
(undefined) !== 'production' ? warning(this.__didWarnIsMounted, '%s: isMounted is deprecated. Instead, make sure to clean up ' + 'subscriptions and pending requests in componentWillUnmount to ' + 'prevent memory leaks.', this.constructor && this.constructor.displayName || this.name || 'Component') : void 0;
this.__didWarnIsMounted = true;
}
return !!this.__isMounted;
}
};
var ReactClassComponent = function () {};
_assign(ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin);
/**
* Creates a composite component class given a class specification.
* See https://facebook.github.io/react/docs/top-level-api.html#react.createclass
*
* @param {object} spec Class specification (which must define `render`).
* @return {function} Component constructor function.
* @public
*/
function createClass(spec) {
// To keep our warnings more understandable, we'll use a little hack here to
// ensure that Constructor.name !== 'Constructor'. This makes sure we don't
// unnecessarily identify a class without displayName as 'Constructor'.
var Constructor = identity(function (props, context, updater) {
// This constructor gets overridden by mocks. The argument is used
// by mocks to assert on what gets mounted.
if ((undefined) !== 'production') {
(undefined) !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory') : void 0;
}
// Wire up auto-binding
if (this.__reactAutoBindPairs.length) {
bindAutoBindMethods(this);
}
this.props = props;
this.context = context;
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
this.state = null;
// ReactClasses doesn't have constructors. Instead, they use the
// getInitialState and componentWillMount methods for initialization.
var initialState = this.getInitialState ? this.getInitialState() : null;
if ((undefined) !== 'production') {
// We allow auto-mocks to proceed as if they're returning null.
if (initialState === undefined && this.getInitialState._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
initialState = null;
}
}
_invariant(typeof initialState === 'object' && !Array.isArray(initialState), '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent');
this.state = initialState;
});
Constructor.prototype = new ReactClassComponent();
Constructor.prototype.constructor = Constructor;
Constructor.prototype.__reactAutoBindPairs = [];
injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor));
mixSpecIntoComponent(Constructor, IsMountedMixin);
mixSpecIntoComponent(Constructor, spec);
// Initialize the defaultProps property after all mixins have been merged.
if (Constructor.getDefaultProps) {
Constructor.defaultProps = Constructor.getDefaultProps();
}
if ((undefined) !== 'production') {
// This is a tag to indicate that the use of these method names is ok,
// since it's used with createClass. If it's not, then it's likely a
// mistake so we'll warn you to use the static property, property
// initializer or constructor respectively.
if (Constructor.getDefaultProps) {
Constructor.getDefaultProps.isReactClassApproved = {};
}
if (Constructor.prototype.getInitialState) {
Constructor.prototype.getInitialState.isReactClassApproved = {};
}
}
_invariant(Constructor.prototype.render, 'createClass(...): Class specification must implement a `render` method.');
if ((undefined) !== 'production') {
(undefined) !== 'production' ? warning(!Constructor.prototype.componentShouldUpdate, '%s 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.', spec.displayName || 'A component') : void 0;
(undefined) !== 'production' ? warning(!Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component') : void 0;
}
// Reduce time spent doing lookups by setting these on the prototype.
for (var methodName in ReactClassInterface) {
if (!Constructor.prototype[methodName]) {
Constructor.prototype[methodName] = null;
}
}
return Constructor;
}
return createClass;
}
module.exports = factory;
/***/ },
/* 20 */
/***/ function(module, exports) {
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
'use strict';
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
module.exports = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var emptyObject = {};
if ((undefined) !== 'production') {
Object.freeze(emptyObject);
}
module.exports = emptyObject;
/***/ },
/* 22 */
/***/ function(module, exports) {
'use strict';
var _element = typeof document !== 'undefined' ? document.body : null;
function setElement(element) {
if (typeof element === 'string') {
var el = document.querySelectorAll(element);
element = 'length' in el ? el[0] : el;
}
_element = element || _element;
return _element;
}
function hide(appElement) {
validateElement(appElement);
(appElement || _element).setAttribute('aria-hidden', 'true');
}
function show(appElement) {
validateElement(appElement);
(appElement || _element).removeAttribute('aria-hidden');
}
function toggle(shouldHide, appElement) {
if (shouldHide) hide(appElement);else show(appElement);
}
function validateElement(appElement) {
if (!appElement && !_element) throw new Error('react-modal: You must set an element with `Modal.setAppElement(el)` to make this accessible');
}
function resetForTesting() {
_element = document.body;
}
exports.toggle = toggle;
exports.setElement = setElement;
exports.show = show;
exports.hide = hide;
exports.resetForTesting = resetForTesting;
/***/ },
/* 23 */
/***/ function(module, exports) {
"use strict";
var modals = [];
module.exports = {
add: function add(element) {
if (modals.indexOf(element) === -1) {
modals.push(element);
}
},
remove: function remove(element) {
var index = modals.indexOf(element);
if (index === -1) {
return;
}
modals.splice(index, 1);
},
count: function count() {
return modals.length;
}
};
/***/ },
/* 24 */
/***/ function(module, exports) {
module.exports = function(opts) {
return new ElementClass(opts)
}
function indexOf(arr, prop) {
if (arr.indexOf) return arr.indexOf(prop)
for (var i = 0, len = arr.length; i < len; i++)
if (arr[i] === prop) return i
return -1
}
function ElementClass(opts) {
if (!(this instanceof ElementClass)) return new ElementClass(opts)
var self = this
if (!opts) opts = {}
// similar doing instanceof HTMLElement but works in IE8
if (opts.nodeType) opts = {el: opts}
this.opts = opts
this.el = opts.el || document.body
if (typeof this.el !== 'object') this.el = document.querySelector(this.el)
}
ElementClass.prototype.add = function(className) {
var el = this.el
if (!el) return
if (el.className === "") return el.className = className
var classes = el.className.split(' ')
if (indexOf(classes, className) > -1) return classes
classes.push(className)
el.className = classes.join(' ')
return classes
}
ElementClass.prototype.remove = function(className) {
var el = this.el
if (!el) return
if (el.className === "") return
var classes = el.className.split(' ')
var idx = indexOf(classes, className)
if (idx > -1) classes.splice(idx, 1)
el.className = classes.join(' ')
return classes
}
ElementClass.prototype.has = function(className) {
var el = this.el
if (!el) return
var classes = el.className.split(' ')
return indexOf(classes, className) > -1
}
ElementClass.prototype.toggle = function(className) {
var el = this.el
if (!el) return
if (this.has(className)) this.remove(className)
else this.add(className)
}
/***/ }
/******/ ])
});
;
|
js/jquery-1.10.2.min.js
|
racoonman/multiSelectOrder
|
/*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery-1.10.2.min.map
*/
(function(e,t){var n,r,i=typeof t,o=e.location,a=e.document,s=a.documentElement,l=e.jQuery,u=e.$,c={},p=[],f="1.10.2",d=p.concat,h=p.push,g=p.slice,m=p.indexOf,y=c.toString,v=c.hasOwnProperty,b=f.trim,x=function(e,t){return new x.fn.init(e,t,r)},w=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=/\S+/g,C=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,k=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,E=/^[\],:{}\s]*$/,S=/(?:^|:|,)(?:\s*\[)+/g,A=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,j=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,D=/^-ms-/,L=/-([\da-z])/gi,H=function(e,t){return t.toUpperCase()},q=function(e){(a.addEventListener||"load"===e.type||"complete"===a.readyState)&&(_(),x.ready())},_=function(){a.addEventListener?(a.removeEventListener("DOMContentLoaded",q,!1),e.removeEventListener("load",q,!1)):(a.detachEvent("onreadystatechange",q),e.detachEvent("onload",q))};x.fn=x.prototype={jquery:f,constructor:x,init:function(e,n,r){var i,o;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 x?n[0]:n,x.merge(this,x.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:a,!0)),k.test(i[1])&&x.isPlainObject(n))for(i in n)x.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(o=a.getElementById(i[2]),o&&o.parentNode){if(o.id!==i[2])return r.find(e);this.length=1,this[0]=o}return this.context=a,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return g.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(g.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(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},l=2),"object"==typeof s||x.isFunction(s)||(s={}),u===l&&(s=this,--l);u>l;l++)if(null!=(o=arguments[l]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(x.isPlainObject(r)||(n=x.isArray(r)))?(n?(n=!1,a=e&&x.isArray(e)?e:[]):a=e&&x.isPlainObject(e)?e:{},s[i]=x.extend(c,a,r)):r!==t&&(s[i]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=l),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){if(e===!0?!--x.readyWait:!x.isReady){if(!a.body)return setTimeout(x.ready);x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(a,[x]),x.fn.trigger&&x(a).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray||function(e){return"array"===x.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?c[y.call(e)]||"object":typeof e},isPlainObject:function(e){var n;if(!e||"object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!v.call(e,"constructor")&&!v.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(r){return!1}if(x.support.ownLast)for(n in e)return v.call(e,n);for(n in e);return n===t||v.call(e,n)},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||a;var r=k.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=x.trim(n),n&&E.test(n.replace(A,"@").replace(j,"]").replace(S,"")))?Function("return "+n)():(x.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||x.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&x.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(D,"ms-").replace(L,H)},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:b&&!b.call("\ufeff\u00a0")?function(e){return null==e?"":b.call(e)}:function(e){return null==e?"":(e+"").replace(C,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(m)return m.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 d.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),x.isFunction(e)?(r=g.call(arguments,2),i=function(){return e.apply(n||this,r.concat(g.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):t},access:function(e,n,r,i,o,a,s){var l=0,u=e.length,c=null==r;if("object"===x.type(r)){o=!0;for(l in r)x.access(e,n,l,r[l],!0,a,s)}else if(i!==t&&(o=!0,x.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(x(e),n)})),n))for(;u>l;l++)n(e[l],r,s?i:i.call(e[l],l,n(e[l],r)));return o?e:c?n.call(e):u?n(e[0],r):a},now:function(){return(new Date).getTime()},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}}),x.ready.promise=function(t){if(!n)if(n=x.Deferred(),"complete"===a.readyState)setTimeout(x.ready);else if(a.addEventListener)a.addEventListener("DOMContentLoaded",q,!1),e.addEventListener("load",q,!1);else{a.attachEvent("onreadystatechange",q),e.attachEvent("onload",q);var r=!1;try{r=null==e.frameElement&&a.documentElement}catch(i){}r&&r.doScroll&&function o(){if(!x.isReady){try{r.doScroll("left")}catch(e){return setTimeout(o,50)}_(),x.ready()}}()}return n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){c["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=x(a),function(e,t){var n,r,i,o,a,s,l,u,c,p,f,d,h,g,m,y,v,b="sizzle"+-new Date,w=e.document,T=0,C=0,N=st(),k=st(),E=st(),S=!1,A=function(e,t){return e===t?(S=!0,0):0},j=typeof t,D=1<<31,L={}.hasOwnProperty,H=[],q=H.pop,_=H.push,M=H.push,O=H.slice,F=H.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},B="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",P="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",W=R.replace("w","w#"),$="\\["+P+"*("+R+")"+P+"*(?:([*^$|!~]?=)"+P+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+W+")|)|)"+P+"*\\]",I=":("+R+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+$.replace(3,8)+")*)|.*)\\)|)",z=RegExp("^"+P+"+|((?:^|[^\\\\])(?:\\\\.)*)"+P+"+$","g"),X=RegExp("^"+P+"*,"+P+"*"),U=RegExp("^"+P+"*([>+~]|"+P+")"+P+"*"),V=RegExp(P+"*[+~]"),Y=RegExp("="+P+"*([^\\]'\"]*)"+P+"*\\]","g"),J=RegExp(I),G=RegExp("^"+W+"$"),Q={ID:RegExp("^#("+R+")"),CLASS:RegExp("^\\.("+R+")"),TAG:RegExp("^("+R.replace("w","w*")+")"),ATTR:RegExp("^"+$),PSEUDO:RegExp("^"+I),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+P+"*(even|odd|(([+-]|)(\\d*)n|)"+P+"*(?:([+-]|)"+P+"*(\\d+)|))"+P+"*\\)|)","i"),bool:RegExp("^(?:"+B+")$","i"),needsContext:RegExp("^"+P+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+P+"*((?:-\\d)?\\d*)"+P+"*\\)|)(?=[^-]|$)","i")},K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,et=/^(?:input|select|textarea|button)$/i,tt=/^h\d$/i,nt=/'|\\/g,rt=RegExp("\\\\([\\da-f]{1,6}"+P+"?|("+P+")|.)","ig"),it=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(55296|r>>10,56320|1023&r)};try{M.apply(H=O.call(w.childNodes),w.childNodes),H[w.childNodes.length].nodeType}catch(ot){M={apply:H.length?function(e,t){_.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function at(e,t,n,i){var o,a,s,l,u,c,d,m,y,x;if((t?t.ownerDocument||t:w)!==f&&p(t),t=t||f,n=n||[],!e||"string"!=typeof e)return n;if(1!==(l=t.nodeType)&&9!==l)return[];if(h&&!i){if(o=Z.exec(e))if(s=o[1]){if(9===l){if(a=t.getElementById(s),!a||!a.parentNode)return n;if(a.id===s)return n.push(a),n}else if(t.ownerDocument&&(a=t.ownerDocument.getElementById(s))&&v(t,a)&&a.id===s)return n.push(a),n}else{if(o[2])return M.apply(n,t.getElementsByTagName(e)),n;if((s=o[3])&&r.getElementsByClassName&&t.getElementsByClassName)return M.apply(n,t.getElementsByClassName(s)),n}if(r.qsa&&(!g||!g.test(e))){if(m=d=b,y=t,x=9===l&&e,1===l&&"object"!==t.nodeName.toLowerCase()){c=mt(e),(d=t.getAttribute("id"))?m=d.replace(nt,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",u=c.length;while(u--)c[u]=m+yt(c[u]);y=V.test(e)&&t.parentNode||t,x=c.join(",")}if(x)try{return M.apply(n,y.querySelectorAll(x)),n}catch(T){}finally{d||t.removeAttribute("id")}}}return kt(e.replace(z,"$1"),t,n,i)}function st(){var e=[];function t(n,r){return e.push(n+=" ")>o.cacheLength&&delete t[e.shift()],t[n]=r}return t}function lt(e){return e[b]=!0,e}function ut(e){var t=f.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ct(e,t){var n=e.split("|"),r=e.length;while(r--)o.attrHandle[n[r]]=t}function pt(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function ft(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function dt(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function ht(e){return lt(function(t){return t=+t,lt(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]))})})}s=at.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},r=at.support={},p=at.setDocument=function(e){var n=e?e.ownerDocument||e:w,i=n.defaultView;return n!==f&&9===n.nodeType&&n.documentElement?(f=n,d=n.documentElement,h=!s(n),i&&i.attachEvent&&i!==i.top&&i.attachEvent("onbeforeunload",function(){p()}),r.attributes=ut(function(e){return e.className="i",!e.getAttribute("className")}),r.getElementsByTagName=ut(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),r.getElementsByClassName=ut(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),r.getById=ut(function(e){return d.appendChild(e).id=b,!n.getElementsByName||!n.getElementsByName(b).length}),r.getById?(o.find.ID=function(e,t){if(typeof t.getElementById!==j&&h){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){return e.getAttribute("id")===t}}):(delete o.find.ID,o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),o.find.TAG=r.getElementsByTagName?function(e,n){return typeof n.getElementsByTagName!==j?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},o.find.CLASS=r.getElementsByClassName&&function(e,n){return typeof n.getElementsByClassName!==j&&h?n.getElementsByClassName(e):t},m=[],g=[],(r.qsa=K.test(n.querySelectorAll))&&(ut(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||g.push("\\["+P+"*(?:value|"+B+")"),e.querySelectorAll(":checked").length||g.push(":checked")}),ut(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&g.push("[*^$]="+P+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||g.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),g.push(",.*:")})),(r.matchesSelector=K.test(y=d.webkitMatchesSelector||d.mozMatchesSelector||d.oMatchesSelector||d.msMatchesSelector))&&ut(function(e){r.disconnectedMatch=y.call(e,"div"),y.call(e,"[s!='']:x"),m.push("!=",I)}),g=g.length&&RegExp(g.join("|")),m=m.length&&RegExp(m.join("|")),v=K.test(d.contains)||d.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},A=d.compareDocumentPosition?function(e,t){if(e===t)return S=!0,0;var i=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t);return i?1&i||!r.sortDetached&&t.compareDocumentPosition(e)===i?e===n||v(w,e)?-1:t===n||v(w,t)?1:c?F.call(c,e)-F.call(c,t):0:4&i?-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 S=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:c?F.call(c,e)-F.call(c,t):0;if(o===a)return pt(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?pt(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},n):f},at.matches=function(e,t){return at(e,null,null,t)},at.matchesSelector=function(e,t){if((e.ownerDocument||e)!==f&&p(e),t=t.replace(Y,"='$1']"),!(!r.matchesSelector||!h||m&&m.test(t)||g&&g.test(t)))try{var n=y.call(e,t);if(n||r.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(i){}return at(t,f,null,[e]).length>0},at.contains=function(e,t){return(e.ownerDocument||e)!==f&&p(e),v(e,t)},at.attr=function(e,n){(e.ownerDocument||e)!==f&&p(e);var i=o.attrHandle[n.toLowerCase()],a=i&&L.call(o.attrHandle,n.toLowerCase())?i(e,n,!h):t;return a===t?r.attributes||!h?e.getAttribute(n):(a=e.getAttributeNode(n))&&a.specified?a.value:null:a},at.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},at.uniqueSort=function(e){var t,n=[],i=0,o=0;if(S=!r.detectDuplicates,c=!r.sortStable&&e.slice(0),e.sort(A),S){while(t=e[o++])t===e[o]&&(i=n.push(o));while(i--)e.splice(n[i],1)}return e},a=at.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+=a(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=a(t);return n},o=at.selectors={cacheLength:50,createPseudo:lt,match:Q,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(rt,it),e[3]=(e[4]||e[5]||"").replace(rt,it),"~="===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]||at.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]&&at.error(e[0]),e},PSEUDO:function(e){var n,r=!e[5]&&e[2];return Q.CHILD.test(e[0])?null:(e[3]&&e[4]!==t?e[2]=e[4]:r&&J.test(r)&&(n=mt(r,!0))&&(n=r.indexOf(")",r.length-n)-r.length)&&(e[0]=e[0].slice(0,n),e[2]=r.slice(0,n)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(rt,it).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=N[e+" "];return t||(t=RegExp("(^|"+P+")"+e+"("+P+"|$)"))&&N(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==j&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=at.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,l){var u,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!l&&!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[b]||(m[b]={}),u=c[e]||[],d=u[0]===T&&u[1],f=u[0]===T&&u[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]=[T,d,f];break}}else if(v&&(u=(t[b]||(t[b]={}))[e])&&u[0]===T)f=u[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[b]||(p[b]={}))[e]=[T,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=o.pseudos[e]||o.setFilters[e.toLowerCase()]||at.error("unsupported pseudo: "+e);return r[b]?r(t):r.length>1?(n=[e,e,"",t],o.setFilters.hasOwnProperty(e.toLowerCase())?lt(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=F.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:lt(function(e){var t=[],n=[],r=l(e.replace(z,"$1"));return r[b]?lt(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:lt(function(e){return function(t){return at(e,t).length>0}}),contains:lt(function(e){return function(t){return(t.textContent||t.innerText||a(t)).indexOf(e)>-1}}),lang:lt(function(e){return G.test(e||"")||at.error("unsupported lang: "+e),e=e.replace(rt,it).toLowerCase(),function(t){var n;do if(n=h?t.lang:t.getAttribute("xml:lang")||t.getAttribute("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===d},focus:function(e){return e===f.activeElement&&(!f.hasFocus||f.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!o.pseudos.empty(e)},header:function(e){return tt.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"))||t.toLowerCase()===e.type)},first:ht(function(){return[0]}),last:ht(function(e,t){return[t-1]}),eq:ht(function(e,t,n){return[0>n?n+t:n]}),even:ht(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:ht(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:ht(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:ht(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}},o.pseudos.nth=o.pseudos.eq;for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})o.pseudos[n]=ft(n);for(n in{submit:!0,reset:!0})o.pseudos[n]=dt(n);function gt(){}gt.prototype=o.filters=o.pseudos,o.setFilters=new gt;function mt(e,t){var n,r,i,a,s,l,u,c=k[e+" "];if(c)return t?0:c.slice(0);s=e,l=[],u=o.preFilter;while(s){(!n||(r=X.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),l.push(i=[])),n=!1,(r=U.exec(s))&&(n=r.shift(),i.push({value:n,type:r[0].replace(z," ")}),s=s.slice(n.length));for(a in o.filter)!(r=Q[a].exec(s))||u[a]&&!(r=u[a](r))||(n=r.shift(),i.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?at.error(e):k(e,l).slice(0)}function yt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function vt(e,t,n){var r=t.dir,o=n&&"parentNode"===r,a=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||o)return e(t,n,i)}:function(t,n,s){var l,u,c,p=T+" "+a;if(s){while(t=t[r])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[r])if(1===t.nodeType||o)if(c=t[b]||(t[b]={}),(u=c[r])&&u[0]===p){if((l=u[1])===!0||l===i)return l===!0}else if(u=c[r]=[p],u[1]=e(t,n,s)||i,u[1]===!0)return!0}}function bt(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 xt(e,t,n,r,i){var o,a=[],s=0,l=e.length,u=null!=t;for(;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function wt(e,t,n,r,i,o){return r&&!r[b]&&(r=wt(r)),i&&!i[b]&&(i=wt(i,o)),lt(function(o,a,s,l){var u,c,p,f=[],d=[],h=a.length,g=o||Nt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:xt(g,f,e,s,l),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,l),r){u=xt(y,d),r(u,[],s,l),c=u.length;while(c--)(p=u[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){u=[],c=y.length;while(c--)(p=y[c])&&u.push(m[c]=p);i(null,y=[],u,l)}c=y.length;while(c--)(p=y[c])&&(u=i?F.call(o,p):f[c])>-1&&(o[u]=!(a[u]=p))}}else y=xt(y===a?y.splice(h,y.length):y),i?i(null,a,y,l):M.apply(a,y)})}function Tt(e){var t,n,r,i=e.length,a=o.relative[e[0].type],s=a||o.relative[" "],l=a?1:0,c=vt(function(e){return e===t},s,!0),p=vt(function(e){return F.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==u)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;i>l;l++)if(n=o.relative[e[l].type])f=[vt(bt(f),n)];else{if(n=o.filter[e[l].type].apply(null,e[l].matches),n[b]){for(r=++l;i>r;r++)if(o.relative[e[r].type])break;return wt(l>1&&bt(f),l>1&&yt(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace(z,"$1"),n,r>l&&Tt(e.slice(l,r)),i>r&&Tt(e=e.slice(r)),i>r&&yt(e))}f.push(n)}return bt(f)}function Ct(e,t){var n=0,r=t.length>0,a=e.length>0,s=function(s,l,c,p,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,C=u,N=s||a&&o.find.TAG("*",d&&l.parentNode||l),k=T+=null==C?1:Math.random()||.1;for(w&&(u=l!==f&&l,i=n);null!=(h=N[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,l,c)){p.push(h);break}w&&(T=k,i=++n)}r&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,r&&b!==v){g=0;while(m=t[g++])m(x,y,l,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=q.call(p));y=xt(y)}M.apply(p,y),w&&!s&&y.length>0&&v+t.length>1&&at.uniqueSort(p)}return w&&(T=k,u=C),x};return r?lt(s):s}l=at.compile=function(e,t){var n,r=[],i=[],o=E[e+" "];if(!o){t||(t=mt(e)),n=t.length;while(n--)o=Tt(t[n]),o[b]?r.push(o):i.push(o);o=E(e,Ct(i,r))}return o};function Nt(e,t,n){var r=0,i=t.length;for(;i>r;r++)at(e,t[r],n);return n}function kt(e,t,n,i){var a,s,u,c,p,f=mt(e);if(!i&&1===f.length){if(s=f[0]=f[0].slice(0),s.length>2&&"ID"===(u=s[0]).type&&r.getById&&9===t.nodeType&&h&&o.relative[s[1].type]){if(t=(o.find.ID(u.matches[0].replace(rt,it),t)||[])[0],!t)return n;e=e.slice(s.shift().value.length)}a=Q.needsContext.test(e)?0:s.length;while(a--){if(u=s[a],o.relative[c=u.type])break;if((p=o.find[c])&&(i=p(u.matches[0].replace(rt,it),V.test(s[0].type)&&t.parentNode||t))){if(s.splice(a,1),e=i.length&&yt(s),!e)return M.apply(n,i),n;break}}}return l(e,f)(i,t,!h,n,V.test(e)),n}r.sortStable=b.split("").sort(A).join("")===b,r.detectDuplicates=S,p(),r.sortDetached=ut(function(e){return 1&e.compareDocumentPosition(f.createElement("div"))}),ut(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||ct("type|href|height|width",function(e,n,r){return r?t:e.getAttribute(n,"type"===n.toLowerCase()?1:2)}),r.attributes&&ut(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||ct("value",function(e,n,r){return r||"input"!==e.nodeName.toLowerCase()?t:e.defaultValue}),ut(function(e){return null==e.getAttribute("disabled")})||ct(B,function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&i.specified?i.value:e[n]===!0?n.toLowerCase():null}),x.find=at,x.expr=at.selectors,x.expr[":"]=x.expr.pseudos,x.unique=at.uniqueSort,x.text=at.getText,x.isXMLDoc=at.isXML,x.contains=at.contains}(e);var O={};function F(e){var t=O[e]={};return x.each(e.match(T)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?O[e]||F(e):x.extend({},e);var n,r,i,o,a,s,l=[],u=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=l.length,n=!0;l&&o>a;a++)if(l[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,l&&(u?u.length&&c(u.shift()):r?l=[]:p.disable())},p={add:function(){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this},remove:function(){return l&&x.each(arguments,function(e,t){var r;while((r=x.inArray(t,l,r))>-1)l.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?x.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],o=0,this},disable:function(){return l=u=r=t,this},disabled:function(){return!l},lock:function(){return u=t,r||p.disable(),this},locked:function(){return!u},fireWith:function(e,t){return!l||i&&!u||(t=t||[],t=[e,t.slice?t.slice():t],n?u.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var a=o[0],s=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&x.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?x.extend(e,r):r}},i={};return r.pipe=r.then,x.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=g.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?g.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,l,u;if(r>1)for(s=Array(r),l=Array(r),u=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(a(t,u,n)).fail(o.reject).progress(a(t,l,s)):--i;return i||o.resolveWith(u,n),o.promise()}}),x.support=function(t){var n,r,o,s,l,u,c,p,f,d=a.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],!r||!r.style||!n.length)return t;s=a.createElement("select"),u=s.appendChild(a.createElement("option")),o=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t.getSetAttribute="t"!==d.className,t.leadingWhitespace=3===d.firstChild.nodeType,t.tbody=!d.getElementsByTagName("tbody").length,t.htmlSerialize=!!d.getElementsByTagName("link").length,t.style=/top/.test(r.getAttribute("style")),t.hrefNormalized="/a"===r.getAttribute("href"),t.opacity=/^0.5/.test(r.style.opacity),t.cssFloat=!!r.style.cssFloat,t.checkOn=!!o.value,t.optSelected=u.selected,t.enctype=!!a.createElement("form").enctype,t.html5Clone="<:nav></:nav>"!==a.createElement("nav").cloneNode(!0).outerHTML,t.inlineBlockNeedsLayout=!1,t.shrinkWrapBlocks=!1,t.pixelPosition=!1,t.deleteExpando=!0,t.noCloneEvent=!0,t.reliableMarginRight=!0,t.boxSizingReliable=!0,o.checked=!0,t.noCloneChecked=o.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!u.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}o=a.createElement("input"),o.setAttribute("value",""),t.input=""===o.getAttribute("value"),o.value="t",o.setAttribute("type","radio"),t.radioValue="t"===o.value,o.setAttribute("checked","t"),o.setAttribute("name","t"),l=a.createDocumentFragment(),l.appendChild(o),t.appendChecked=o.checked,t.checkClone=l.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;d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip;for(f in x(t))break;return t.ownLast="0"!==f,x(function(){var n,r,o,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",l=a.getElementsByTagName("body")[0];l&&(n=a.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",l.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",o=d.getElementsByTagName("td"),o[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===o[0].offsetHeight,o[0].style.display="",o[1].style.display="none",t.reliableHiddenOffsets=p&&0===o[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%;",x.swap(l,null!=l.style.zoom?{zoom:1}:{},function(){t.boxSizing=4===d.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(a.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&&(l.style.zoom=1)),l.removeChild(n),n=d=o=r=null)}),n=s=l=u=r=o=null,t
}({});var B=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;function R(e,n,r,i){if(x.acceptData(e)){var o,a,s=x.expando,l=e.nodeType,u=l?x.cache:e,c=l?e[s]:e[s]&&s;if(c&&u[c]&&(i||u[c].data)||r!==t||"string"!=typeof n)return c||(c=l?e[s]=p.pop()||x.guid++:s),u[c]||(u[c]=l?{}:{toJSON:x.noop}),("object"==typeof n||"function"==typeof n)&&(i?u[c]=x.extend(u[c],n):u[c].data=x.extend(u[c].data,n)),a=u[c],i||(a.data||(a.data={}),a=a.data),r!==t&&(a[x.camelCase(n)]=r),"string"==typeof n?(o=a[n],null==o&&(o=a[x.camelCase(n)])):o=a,o}}function W(e,t,n){if(x.acceptData(e)){var r,i,o=e.nodeType,a=o?x.cache:e,s=o?e[x.expando]:x.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){x.isArray(t)?t=t.concat(x.map(t,x.camelCase)):t in r?t=[t]:(t=x.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;while(i--)delete r[t[i]];if(n?!I(r):!x.isEmptyObject(r))return}(n||(delete a[s].data,I(a[s])))&&(o?x.cleanData([e],!0):x.support.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}x.extend({cache:{},noData:{applet:!0,embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?x.cache[e[x.expando]]:e[x.expando],!!e&&!I(e)},data:function(e,t,n){return R(e,t,n)},removeData:function(e,t){return W(e,t)},_data:function(e,t,n){return R(e,t,n,!0)},_removeData:function(e,t){return W(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&x.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),x.fn.extend({data:function(e,n){var r,i,o=null,a=0,s=this[0];if(e===t){if(this.length&&(o=x.data(s),1===s.nodeType&&!x._data(s,"parsedAttrs"))){for(r=s.attributes;r.length>a;a++)i=r[a].name,0===i.indexOf("data-")&&(i=x.camelCase(i.slice(5)),$(s,i,o[i]));x._data(s,"parsedAttrs",!0)}return o}return"object"==typeof e?this.each(function(){x.data(this,e)}):arguments.length>1?this.each(function(){x.data(this,e,n)}):s?$(s,e,x.data(s,e)):null},removeData:function(e){return this.each(function(){x.removeData(this,e)})}});function $(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(P,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:B.test(r)?x.parseJSON(r):r}catch(o){}x.data(e,n,r)}else r=t}return r}function I(e){var t;for(t in e)if(("data"!==t||!x.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}x.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=x._data(e,n),r&&(!i||x.isArray(r)?i=x._data(e,n,x.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=x.queue(e,t),r=n.length,i=n.shift(),o=x._queueHooks(e,t),a=function(){x.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),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 x._data(e,n)||x._data(e,n,{empty:x.Callbacks("once memory").add(function(){x._removeData(e,t+"queue"),x._removeData(e,n)})})}}),x.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?x.queue(this[0],e):n===t?this:this.each(function(){var t=x.queue(this,e,n);x._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.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=x.Deferred(),a=this,s=this.length,l=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=x._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(l));return l(),o.promise(n)}});var z,X,U=/[\t\r\n\f]/g,V=/\r/g,Y=/^(?:input|select|textarea|button|object)$/i,J=/^(?:a|area)$/i,G=/^(?:checked|selected)$/i,Q=x.support.getSetAttribute,K=x.support.input;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return e=x.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,l="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,l=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var t,r=0,o=x(this),a=e.match(T)||[];while(t=a[r++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else(n===i||"boolean"===n)&&(this.className&&x._data(this,"__className__",this.className),this.className=this.className||e===!1?"":x._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(U," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=x.isFunction(e),this.each(function(n){var o;1===this.nodeType&&(o=i?e.call(this,n,x(this).val()):e,null==o?o="":"number"==typeof o?o+="":x.isArray(o)&&(o=x.map(o,function(e){return null==e?"":e+""})),r=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=x.valHooks[o.type]||x.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(V,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=x.find.attr(e,"value");return null!=t?t: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,l=0>i?s:o?i:0;for(;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),a=i.length;while(a--)r=i[a],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,n,r){var o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===i?x.prop(e,n,r):(1===s&&x.isXMLDoc(e)||(n=n.toLowerCase(),o=x.attrHooks[n]||(x.expr.match.bool.test(n)?X:z)),r===t?o&&"get"in o&&null!==(a=o.get(e,n))?a:(a=x.find.attr(e,n),null==a?t:a):null!==r?o&&"set"in o&&(a=o.set(e,r,n))!==t?a:(e.setAttribute(n,r+""),r):(x.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(T);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.bool.test(n)?K&&Q||!G.test(n)?e[r]=!1:e[x.camelCase("default-"+n)]=e[r]=!1:x.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!x.isXMLDoc(e),a&&(n=x.propFix[n]||n,o=x.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 t=x.find.attr(e,"tabindex");return t?parseInt(t,10):Y.test(e.nodeName)||J.test(e.nodeName)&&e.href?0:-1}}}}),X={set:function(e,t,n){return t===!1?x.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&x.propFix[n]||n,n):e[x.camelCase("default-"+n)]=e[n]=!0,n}},x.each(x.expr.match.bool.source.match(/\w+/g),function(e,n){var r=x.expr.attrHandle[n]||x.find.attr;x.expr.attrHandle[n]=K&&Q||!G.test(n)?function(e,n,i){var o=x.expr.attrHandle[n],a=i?t:(x.expr.attrHandle[n]=t)!=r(e,n,i)?n.toLowerCase():null;return x.expr.attrHandle[n]=o,a}:function(e,n,r){return r?t:e[x.camelCase("default-"+n)]?n.toLowerCase():null}}),K&&Q||(x.attrHooks.value={set:function(e,n,r){return x.nodeName(e,"input")?(e.defaultValue=n,t):z&&z.set(e,n,r)}}),Q||(z={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}},x.expr.attrHandle.id=x.expr.attrHandle.name=x.expr.attrHandle.coords=function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&""!==i.value?i.value:null},x.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&r.specified?r.value:t},set:z.set},x.attrHooks.contenteditable={set:function(e,t,n){z.set(e,""===t?!1:t,n)}},x.each(["width","height"],function(e,n){x.attrHooks[n]={set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}}})),x.support.hrefNormalized||x.each(["href","src"],function(e,t){x.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),x.support.style||(x.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),x.support.optSelected||(x.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),x.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){x.propFix[this.toLowerCase()]=this}),x.support.enctype||(x.propFix.enctype="encoding"),x.each(["radio","checkbox"],function(){x.valHooks[this]={set:function(e,n){return x.isArray(n)?e.checked=x.inArray(x(e).val(),n)>=0:t}},x.support.checkOn||(x.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}function at(){try{return a.activeElement}catch(e){}}x.event={global:{},add:function(e,n,r,o,a){var s,l,u,c,p,f,d,h,g,m,y,v=x._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=x.guid++),(l=v.events)||(l=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof x===i||e&&x.event.triggered===e.type?t:x.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(T)||[""],u=n.length;while(u--)s=rt.exec(n[u])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),g&&(p=x.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=x.event.special[g]||{},d=x.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&x.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=l[g])||(h=l[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),x.event.global[g]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,p,f,d,h,g,m=x.hasData(e)&&x._data(e);if(m&&(c=m.events)){t=(t||"").match(T)||[""],u=t.length;while(u--)if(s=rt.exec(t[u])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=x.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=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));l&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||x.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)x.event.remove(e,d+t[u],n,r,!0);x.isEmptyObject(c)&&(delete m.handle,x._removeData(e,"events"))}},trigger:function(n,r,i,o){var s,l,u,c,p,f,d,h=[i||a],g=v.call(n,"type")?n.type:n,m=v.call(n,"namespace")?n.namespace.split("."):[];if(u=f=i=i||a,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+x.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),l=0>g.indexOf(":")&&"on"+g,n=n[x.expando]?n:new x.Event(g,"object"==typeof n&&n),n.isTrigger=o?2:3,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]:x.makeArray(r,[n]),p=x.event.special[g]||{},o||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!o&&!p.noBubble&&!x.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(u=u.parentNode);u;u=u.parentNode)h.push(u),f=u;f===(i.ownerDocument||a)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((u=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(x._data(u,"events")||{})[n.type]&&x._data(u,"handle"),s&&s.apply(u,r),s=l&&u[l],s&&x.acceptData(u)&&s.apply&&s.apply(u,r)===!1&&n.preventDefault();if(n.type=g,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(h.pop(),r)===!1)&&x.acceptData(i)&&l&&i[g]&&!x.isWindow(i)){f=i[l],f&&(i[l]=null),x.event.triggered=g;try{i[g]()}catch(y){}x.event.triggered=t,f&&(i[l]=f)}return n.result}},dispatch:function(e){e=x.event.fix(e);var n,r,i,o,a,s=[],l=g.call(arguments),u=(x._data(this,"events")||{})[e.type]||[],c=x.event.special[e.type]||{};if(l[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=x.event.handlers.call(this,e,u),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=((x.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,l),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=[],l=n.delegateCount,u=e.target;if(l&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!=this;u=u.parentNode||this)if(1===u.nodeType&&(u.disabled!==!0||"click"!==e.type)){for(o=[],a=0;l>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?x(r,this).index(u)>=0:x.find(r,this,null,[u]).length),o[r]&&o.push(i);o.length&&s.push({elem:u,handlers:o})}return n.length>l&&s.push({elem:this,handlers:n.slice(l)}),s},fix:function(e){if(e[x.expando])return e;var t,n,r,i=e.type,o=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 x.Event(o),t=r.length;while(t--)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||a),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,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){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,o,s=n.button,l=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||a,o=i.documentElement,r=i.body,e.pageX=n.clientX+(o&&o.scrollLeft||r&&r.scrollLeft||0)-(o&&o.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(o&&o.scrollTop||r&&r.scrollTop||0)-(o&&o.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&l&&(e.relatedTarget=l===e.target?n.toElement:l),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==at()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===at()&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},click:{trigger:function(){return x.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t},_default:function(e){return x.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=x.extend(new x.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?x.event.trigger(i,null,t):x.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},x.removeEvent=a.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))},x.Event=function(e,n){return this instanceof x.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&&x.extend(this,n),this.timeStamp=e&&e.timeStamp||x.now(),this[x.expando]=!0,t):new x.Event(e,n)},x.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()}},x.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){x.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!x.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),x.support.submitBubbles||(x.event.special.submit={setup:function(){return x.nodeName(this,"form")?!1:(x.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=x.nodeName(n,"input")||x.nodeName(n,"button")?n.form:t;r&&!x._data(r,"submitBubbles")&&(x.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),x._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&x.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return x.nodeName(this,"form")?!1:(x.event.remove(this,"._submit"),t)}}),x.support.changeBubbles||(x.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(x.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),x.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),x.event.simulate("change",this,e,!0)})),!1):(x.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!x._data(t,"changeBubbles")&&(x.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||x.event.simulate("change",this.parentNode,e,!0)}),x._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 x.event.remove(this,"._change"),!Z.test(this.nodeName)}}),x.support.focusinBubbles||x.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){x.event.simulate(t,e.target,x.event.fix(e),!0)};x.event.special[t]={setup:function(){0===n++&&a.addEventListener(e,r,!0)},teardown:function(){0===--n&&a.removeEventListener(e,r,!0)}}}),x.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 x().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=x.guid++)),this.each(function(){x.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,x(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(){x.event.remove(this,e,r,n)})},trigger:function(e,t){return this.each(function(){x.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?x.event.trigger(e,n,r,!0):t}});var st=/^.[^:#\[\.,]*$/,lt=/^(?:parents|prev(?:Until|All))/,ut=x.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};x.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(x(e).filter(function(){for(t=0;i>t;t++)if(x.contains(r[t],this))return!0}));for(t=0;i>t;t++)x.find(e,r[t],n);return n=this.pushStack(i>1?x.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},has:function(e){var t,n=x(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(x.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e||[],!0))},filter:function(e){return this.pushStack(ft(this,e||[],!1))},is:function(e){return!!ft(this,"string"==typeof e&&ut.test(e)?x(e):e||[],!1).length},closest:function(e,t){var n,r=0,i=this.length,o=[],a=ut.test(e)||"string"!=typeof e?x(e,t||this.context):0;for(;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(11>n.nodeType&&(a?a.index(n)>-1:1===n.nodeType&&x.find.matchesSelector(n,e))){n=o.push(n);break}return this.pushStack(o.length>1?x.unique(o):o)},index:function(e){return e?"string"==typeof e?x.inArray(this[0],x(e)):x.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?x(e,t):x.makeArray(e&&e.nodeType?[e]:e),r=x.merge(this.get(),n);return this.pushStack(x.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}x.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return x.dir(e,"parentNode")},parentsUntil:function(e,t,n){return x.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return x.dir(e,"nextSibling")},prevAll:function(e){return x.dir(e,"previousSibling")},nextUntil:function(e,t,n){return x.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return x.dir(e,"previousSibling",n)},siblings:function(e){return x.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return x.sibling(e.firstChild)},contents:function(e){return x.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:x.merge([],e.childNodes)}},function(e,t){x.fn[e]=function(n,r){var i=x.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=x.filter(r,i)),this.length>1&&(ct[e]||(i=x.unique(i)),lt.test(e)&&(i=i.reverse())),this.pushStack(i)}}),x.extend({filter:function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?x.find.matchesSelector(r,e)?[r]:[]:x.find.matches(e,x.grep(t,function(e){return 1===e.nodeType}))},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!x(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(x.isFunction(t))return x.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return x.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(st.test(t))return x.filter(t,e,n);t=x.filter(t,e)}return x.grep(e,function(e){return x.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,Ct=/^(?:checkbox|radio)$/i,Nt=/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:x.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(a),Dt=jt.appendChild(a.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,x.fn.extend({text:function(e){return x.access(this,function(e){return e===t?x.text(this):this.empty().append((this[0]&&this[0].ownerDocument||a).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=Lt(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=Lt(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){var n,r=e?x.filter(e,this):this,i=0;for(;null!=(n=r[i]);i++)t||1!==n.nodeType||x.cleanData(Ft(n)),n.parentNode&&(t&&x.contains(n.ownerDocument,n)&&_t(Ft(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&x.cleanData(Ft(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&x.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 x.clone(this,e,t)})},html:function(e){return x.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)||!x.support.htmlSerialize&&mt.test(e)||!x.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&&(x.cleanData(Ft(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=x.map(this,function(e){return[e.nextSibling,e.parentNode]}),t=0;return this.domManip(arguments,function(n){var r=e[t++],i=e[t++];i&&(r&&r.parentNode!==i&&(r=this.nextSibling),x(this).remove(),i.insertBefore(n,r))},!0),t?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t,n){e=d.apply([],e);var r,i,o,a,s,l,u=0,c=this.length,p=this,f=c-1,h=e[0],g=x.isFunction(h);if(g||!(1>=c||"string"!=typeof h||x.support.checkClone)&&Nt.test(h))return this.each(function(r){var i=p.eq(r);g&&(e[0]=h.call(this,r,i.html())),i.domManip(e,t,n)});if(c&&(l=x.buildFragment(e,this[0].ownerDocument,!1,!n&&this),r=l.firstChild,1===l.childNodes.length&&(l=r),r)){for(a=x.map(Ft(l,"script"),Ht),o=a.length;c>u;u++)i=l,u!==f&&(i=x.clone(i,!0,!0),o&&x.merge(a,Ft(i,"script"))),t.call(this[u],i,u);if(o)for(s=a[a.length-1].ownerDocument,x.map(a,qt),u=0;o>u;u++)i=a[u],kt.test(i.type||"")&&!x._data(i,"globalEval")&&x.contains(s,i)&&(i.src?x._evalUrl(i.src):x.globalEval((i.text||i.textContent||i.innerHTML||"").replace(St,"")));l=r=null}return this}});function Lt(e,t){return x.nodeName(e,"table")&&x.nodeName(1===t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function Ht(e){return e.type=(null!==x.find.attr(e,"type"))+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function _t(e,t){var n,r=0;for(;null!=(n=e[r]);r++)x._data(n,"globalEval",!t||x._data(t[r],"globalEval"))}function Mt(e,t){if(1===t.nodeType&&x.hasData(e)){var n,r,i,o=x._data(e),a=x._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++)x.event.add(t,n,s[n][r])}a.data&&(a.data=x.extend({},a.data))}}function Ot(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!x.support.noCloneEvent&&t[x.expando]){i=x._data(t);for(r in i.events)x.removeEvent(t,r,i.handle);t.removeAttribute(x.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),x.support.html5Clone&&e.innerHTML&&!x.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Ct.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)}}x.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){x.fn[e]=function(e){var n,r=0,i=[],o=x(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),x(o[r])[t](n),h.apply(i,n.get());return this.pushStack(i)}});function Ft(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||x.nodeName(o,n)?s.push(o):x.merge(s,Ft(o,n));return n===t||n&&x.nodeName(e,n)?x.merge([e],s):s}function Bt(e){Ct.test(e.type)&&(e.defaultChecked=e.checked)}x.extend({clone:function(e,t,n){var r,i,o,a,s,l=x.contains(e.ownerDocument,e);if(x.support.html5Clone||x.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(x.support.noCloneEvent&&x.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||x.isXMLDoc(e)))for(r=Ft(o),s=Ft(e),a=0;null!=(i=s[a]);++a)r[a]&&Ot(i,r[a]);if(t)if(n)for(s=s||Ft(e),r=r||Ft(o),a=0;null!=(i=s[a]);a++)Mt(i,r[a]);else Mt(e,o);return r=Ft(o,"script"),r.length>0&&_t(r,!l&&Ft(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,l,u,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===x.type(o))x.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),l=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[l]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!x.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!x.support.tbody){o="table"!==l||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)x.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u)}x.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),x.support.appendChecked||x.grep(Ft(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===x.inArray(o,r))&&(a=x.contains(o.ownerDocument,o),s=Ft(f.appendChild(o),"script"),a&&_t(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,l=x.expando,u=x.cache,c=x.support.deleteExpando,f=x.event.special;for(;null!=(n=e[s]);s++)if((t||x.acceptData(n))&&(o=n[l],a=o&&u[o])){if(a.events)for(r in a.events)f[r]?x.event.remove(n,r):x.removeEvent(n,r,a.handle);
u[o]&&(delete u[o],c?delete n[l]:typeof n.removeAttribute!==i?n.removeAttribute(l):n[l]=null,p.push(o))}},_evalUrl:function(e){return x.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})}}),x.fn.extend({wrapAll:function(e){if(x.isFunction(e))return this.each(function(t){x(this).wrapAll(e.call(this,t))});if(this[0]){var t=x(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 x.isFunction(e)?this.each(function(t){x(this).wrapInner(e.call(this,t))}):this.each(function(){var t=x(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=x.isFunction(e);return this.each(function(n){x(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){x.nodeName(this,"body")||x(this).replaceWith(this.childNodes)}).end()}});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("^("+w+")(.*)$","i"),Yt=RegExp("^("+w+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+w+")","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"===x.css(e,"display")||!x.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]=x._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=x._data(r,"olddisplay",ln(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&x._data(r,"olddisplay",i?n:x.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}x.fn.extend({css:function(e,n){return x.access(this,function(e,n,r){var i,o,a={},s=0;if(x.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=x.css(e,n[s],!1,o);return a}return r!==t?x.style(e,n,r):x.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){nn(this)?x(this).show():x(this).hide()})}}),x.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,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":x.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,l=x.camelCase(n),u=e.style;if(n=x.cssProps[l]||(x.cssProps[l]=tn(u,l)),s=x.cssHooks[n]||x.cssHooks[l],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:u[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(x.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||x.cssNumber[l]||(r+="px"),x.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(u[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{u[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,l=x.camelCase(n);return n=x.cssProps[l]||(x.cssProps[l]=tn(e.style,l)),s=x.cssHooks[n]||x.cssHooks[l],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||x.isNumeric(o)?o||0:a):a}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s.getPropertyValue(n)||s[n]:t,u=e.style;return s&&(""!==l||x.contains(e.ownerDocument,e)||(l=x.style(e,n)),Yt.test(l)&&Ut.test(n)&&(i=u.width,o=u.minWidth,a=u.maxWidth,u.minWidth=u.maxWidth=u.width=l,l=s.width,u.width=i,u.minWidth=o,u.maxWidth=a)),l}):a.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s[n]:t,u=e.style;return null==l&&u&&u[n]&&(l=u[n]),Yt.test(l)&&!zt.test(n)&&(i=u.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),u.left="fontSize"===n?"1em":l,l=u.pixelLeft+"px",u.left=i,a&&(o.left=a)),""===l?"auto":l});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+=x.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=x.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=x.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=x.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=x.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=x.support.boxSizing&&"border-box"===x.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&&(x.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function ln(e){var t=a,n=Gt[e];return n||(n=un(e,t),"none"!==n&&n||(Pt=(Pt||x("<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=un(e,t),Pt.detach()),Gt[e]=n),n}function un(e,t){var n=x(t.createElement(e)).appendTo(t.body),r=x.css(n[0],"display");return n.remove(),r}x.each(["height","width"],function(e,n){x.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(x.css(e,"display"))?x.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,x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,i),i):0)}}}),x.support.opacity||(x.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=x.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===x.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),x(function(){x.support.reliableMarginRight||(x.cssHooks.marginRight={get:function(e,n){return n?x.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!x.support.pixelPosition&&x.fn.position&&x.each(["top","left"],function(e,n){x.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?x(e).position()[n]+"px":r):t}}})}),x.expr&&x.expr.filters&&(x.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!x.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||x.css(e,"display"))},x.expr.filters.visible=function(e){return!x.expr.filters.hidden(e)}),x.each({margin:"",padding:"",border:"Width"},function(e,t){x.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)||(x.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;x.fn.extend({serialize:function(){return x.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=x.prop(this,"elements");return e?x.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!x(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Ct.test(e))}).map(function(e,t){var n=x(this).val();return null==n?null:x.isArray(n)?x.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),x.param=function(e,n){var r,i=[],o=function(e,t){t=x.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=x.ajaxSettings&&x.ajaxSettings.traditional),x.isArray(e)||e.jquery&&!x.isPlainObject(e))x.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(x.isArray(t))x.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"!==x.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}x.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){x.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),x.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},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)}});var mn,yn,vn=x.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Cn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Nn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=x.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=o.href}catch(Ln){yn=a.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(T)||[];if(x.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(l){var u;return o[l]=!0,x.each(e[l]||[],function(e,l){var c=l(n,r,i);return"string"!=typeof c||a||o[c]?a?!(u=c):t:(n.dataTypes.unshift(c),s(c),!1)}),u}return s(n.dataTypes[0])||!o["*"]&&s("*")}function _n(e,n){var r,i,o=x.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&x.extend(!0,e,r),e}x.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,l=e.indexOf(" ");return l>=0&&(i=e.slice(l,e.length),e=e.slice(0,l)),x.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&x.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?x("<div>").append(x.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},x.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){x.fn[t]=function(e){return this.on(t,e)}}),x.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Cn.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",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":x.parseJSON,"text xml":x.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?_n(_n(e,x.ajaxSettings),t):_n(x.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,l,u,c,p=x.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?x(f):x.event,h=x.Deferred(),g=x.Callbacks("once memory"),m=p.statusCode||{},y={},v={},b=0,w="canceled",C={readyState:0,getResponseHeader:function(e){var t;if(2===b){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===b?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return b||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return b||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)m[t]=[m[t],e[t]];else C.always(e[C.status]);return this},abort:function(e){var t=e||w;return u&&u.abort(t),k(0,t),this}};if(h.promise(C).complete=g.add,C.success=C.done,C.error=C.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=x.trim(p.dataType||"*").toLowerCase().match(T)||[""],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=x.param(p.data,p.traditional)),qn(An,p,n,C),2===b)return C;l=p.global,l&&0===x.active++&&x.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Nn.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&&(x.lastModified[o]&&C.setRequestHeader("If-Modified-Since",x.lastModified[o]),x.etag[o]&&C.setRequestHeader("If-None-Match",x.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&C.setRequestHeader("Content-Type",p.contentType),C.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)C.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,C,p)===!1||2===b))return C.abort();w="abort";for(i in{success:1,error:1,complete:1})C[i](p[i]);if(u=qn(jn,p,n,C)){C.readyState=1,l&&d.trigger("ajaxSend",[C,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){C.abort("timeout")},p.timeout));try{b=1,u.send(y,k)}catch(N){if(!(2>b))throw N;k(-1,N)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,N=n;2!==b&&(b=2,s&&clearTimeout(s),u=t,a=i||"",C.readyState=e>0?4:0,c=e>=200&&300>e||304===e,r&&(w=Mn(p,C,r)),w=On(p,w,C,c),c?(p.ifModified&&(T=C.getResponseHeader("Last-Modified"),T&&(x.lastModified[o]=T),T=C.getResponseHeader("etag"),T&&(x.etag[o]=T)),204===e||"HEAD"===p.type?N="nocontent":304===e?N="notmodified":(N=w.state,y=w.data,v=w.error,c=!v)):(v=N,(e||!N)&&(N="error",0>e&&(e=0))),C.status=e,C.statusText=(n||N)+"",c?h.resolveWith(f,[y,N,C]):h.rejectWith(f,[C,N,v]),C.statusCode(m),m=t,l&&d.trigger(c?"ajaxSuccess":"ajaxError",[C,p,c?y:v]),g.fireWith(f,[C,N]),l&&(d.trigger("ajaxComplete",[C,p]),--x.active||x.event.trigger("ajaxStop")))}return C},getJSON:function(e,t,n){return x.get(e,t,n,"json")},getScript:function(e,n){return x.get(e,t,n,"script")}}),x.each(["get","post"],function(e,n){x[n]=function(e,r,i,o){return x.isFunction(r)&&(o=o||i,i=r,r=t),x.ajax({url:e,type:n,dataType:o,data:r,success:i})}});function Mn(e,n,r){var i,o,a,s,l=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in l)if(l[s]&&l[s].test(o)){u.unshift(s);break}if(u[0]in r)a=u[0];else{for(s in r){if(!u[0]||e.converters[s+" "+u[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==u[0]&&u.unshift(a),r[a]):t}function On(e,t,n,r){var i,o,a,s,l,u={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)u[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=o,o=c.shift())if("*"===o)o=l;else if("*"!==l&&l!==o){if(a=u[l+" "+o]||u["* "+o],!a)for(i in u)if(s=i.split(" "),s[1]===o&&(a=u[l+" "+s[0]]||u["* "+s[0]])){a===!0?a=u[i]:u[i]!==!0&&(o=s[0],c.unshift(s[1]));break}if(a!==!0)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(p){return{state:"parsererror",error:a?p:"No conversion from "+l+" to "+o}}}return{state:"success",data:t}}x.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return x.globalEval(e),e}}}),x.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),x.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=a.head||x("head")[0]||a.documentElement;return{send:function(t,i){n=a.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 Fn=[],Bn=/(=)\?(?=&|$)|\?\?/;x.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Fn.pop()||x.expando+"_"+vn++;return this[e]=!0,e}}),x.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,l=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 l||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=x.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,l?n[l]=n[l].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||x.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,Fn.push(o)),s&&x.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){}}x.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=x.ajaxSettings.xhr(),x.support.cors=!!Rn&&"withCredentials"in Rn,Rn=x.support.ajax=!!Rn,Rn&&x.ajaxTransport(function(n){if(!n.crossDomain||x.support.cors){var r;return{send:function(i,o){var a,s,l=n.xhr();if(n.username?l.open(n.type,n.url,n.async,n.username,n.password):l.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)l[s]=n.xhrFields[s];n.mimeType&&l.overrideMimeType&&l.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)l.setRequestHeader(s,i[s])}catch(u){}l.send(n.hasContent&&n.data||null),r=function(e,i){var s,u,c,p;try{if(r&&(i||4===l.readyState))if(r=t,a&&(l.onreadystatechange=x.noop,$n&&delete Pn[a]),i)4!==l.readyState&&l.abort();else{p={},s=l.status,u=l.getAllResponseHeaders(),"string"==typeof l.responseText&&(p.text=l.responseText);try{c=l.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,u)},n.async?4===l.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},x(e).unload($n)),Pn[a]=r),l.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+w+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=Yn.exec(t),o=i&&i[3]||(x.cssNumber[e]?"":"px"),a=(x.cssNumber[e]||"px"!==o&&+r)&&Yn.exec(x.css(n.elem,e)),s=1,l=20;if(a&&a[3]!==o){o=o||a[3],i=i||[],a=+r||1;do s=s||".5",a/=s,x.style(n.elem,e,a+o);while(s!==(s=n.cur()/r)&&1!==s&&--l)}return i&&(a=n.start=+a||+r||0,n.unit=o,n.end=i[1]?a+(i[1]+1)*i[2]:+i[2]),n}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=x.now()}function Zn(e,t,n){var r,i=(Qn[t]||[]).concat(Qn["*"]),o=0,a=i.length;for(;a>o;o++)if(r=i[o].call(n,t,e))return r}function er(e,t,n){var r,i,o=0,a=Gn.length,s=x.Deferred().always(function(){delete l.elem}),l=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,u.startTime+u.duration-t),r=n/u.duration||0,o=1-r,a=0,l=u.tweens.length;for(;l>a;a++)u.tweens[a].run(o);return s.notifyWith(e,[u,o,n]),1>o&&l?n:(s.resolveWith(e,[u]),!1)},u=s.promise({elem:e,props:x.extend({},t),opts:x.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=x.Tween(e,u.opts,t,n,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(r),r},stop:function(t){var n=0,r=t?u.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)u.tweens[n].run(1);return t?s.resolveWith(e,[u,t]):s.rejectWith(e,[u,t]),this}}),c=u.props;for(tr(c,u.opts.specialEasing);a>o;o++)if(r=Gn[o].call(u,e,c,u.opts))return r;return x.map(c,Zn,u),x.isFunction(u.opts.start)&&u.opts.start.call(e,u),x.fx.timer(x.extend(l,{elem:e,anim:u,queue:u.opts.queue})),u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function tr(e,t){var n,r,i,o,a;for(n in e)if(r=x.camelCase(n),i=t[r],o=e[n],x.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=x.cssHooks[r],a&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}x.Animation=x.extend(er,{tweener:function(e,t){x.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,l,u=this,c={},p=e.style,f=e.nodeType&&nn(e),d=x._data(e,"fxshow");n.queue||(s=x._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,l=s.empty.fire,s.empty.fire=function(){s.unqueued||l()}),s.unqueued++,u.always(function(){u.always(function(){s.unqueued--,x.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],"inline"===x.css(e,"display")&&"none"===x.css(e,"float")&&(x.support.inlineBlockNeedsLayout&&"inline"!==ln(e.nodeName)?p.zoom=1:p.display="inline-block")),n.overflow&&(p.overflow="hidden",x.support.shrinkWrapBlocks||u.always(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],Vn.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(f?"hide":"show"))continue;c[r]=d&&d[r]||x.style(e,r)}if(!x.isEmptyObject(c)){d?"hidden"in d&&(f=d.hidden):d=x._data(e,"fxshow",{}),o&&(d.hidden=!f),f?x(e).show():u.done(function(){x(e).hide()}),u.done(function(){var t;x._removeData(e,"fxshow");for(t in c)x.style(e,t,c[t])});for(r in c)a=Zn(f?d[r]:0,r,u),r in d||(d[r]=a.start,f&&(a.end=a.start,a.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}x.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||(x.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?x.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=x.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){x.fx.step[e.prop]?x.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[x.cssProps[e.prop]]||x.cssHooks[e.prop])?x.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)}},x.each(["toggle","show","hide"],function(e,t){var n=x.fn[t];x.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),x.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=x.isEmptyObject(e),o=x.speed(t,n,r),a=function(){var t=er(this,x.extend({},e),o);(i||x._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=x.timers,a=x._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)&&x.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=x._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=x.timers,a=r?r.length:0;for(n.finish=!0,x.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),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}x.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){x.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),x.speed=function(e,t,n){var r=e&&"object"==typeof e?x.extend({},e):{complete:n||!n&&t||x.isFunction(e)&&e,duration:e,easing:n&&t||t&&!x.isFunction(t)&&t};return r.duration=x.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in x.fx.speeds?x.fx.speeds[r.duration]:x.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){x.isFunction(r.old)&&r.old.call(this),r.queue&&x.dequeue(this,r.queue)},r},x.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},x.timers=[],x.fx=rr.prototype.init,x.fx.tick=function(){var e,n=x.timers,r=0;for(Xn=x.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||x.fx.stop(),Xn=t},x.fx.timer=function(e){e()&&x.timers.push(e)&&x.fx.start()},x.fx.interval=13,x.fx.start=function(){Un||(Un=setInterval(x.fx.tick,x.fx.interval))},x.fx.stop=function(){clearInterval(Un),Un=null},x.fx.speeds={slow:600,fast:200,_default:400},x.fx.step={},x.expr&&x.expr.filters&&(x.expr.filters.animated=function(e){return x.grep(x.timers,function(t){return e===t.elem}).length}),x.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){x.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,x.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},x.offset={setOffset:function(e,t,n){var r=x.css(e,"position");"static"===r&&(e.style.position="relative");var i=x(e),o=i.offset(),a=x.css(e,"top"),s=x.css(e,"left"),l=("absolute"===r||"fixed"===r)&&x.inArray("auto",[a,s])>-1,u={},c={},p,f;l?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),x.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(u.top=t.top-o.top+p),null!=t.left&&(u.left=t.left-o.left+f),"using"in t?t.using.call(e,u):i.css(u)}},x.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===x.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),x.nodeName(e[0],"html")||(n=e.offset()),n.top+=x.css(e[0],"borderTopWidth",!0),n.left+=x.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-x.css(r,"marginTop",!0),left:t.left-n.left-x.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||s;while(e&&!x.nodeName(e,"html")&&"static"===x.css(e,"position"))e=e.offsetParent;return e||s})}}),x.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);x.fn[e]=function(i){return x.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?x(a).scrollLeft():o,r?o:x(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return x.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}x.each({Height:"height",Width:"width"},function(e,n){x.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){x.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return x.access(this,function(n,r,i){var o;return x.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?x.css(n,r,s):x.style(n,r,i,s)},n,a?i:t,a,null)}})}),x.fn.size=function(){return this.length},x.fn.andSelf=x.fn.addBack,"object"==typeof module&&module&&"object"==typeof module.exports?module.exports=x:(e.jQuery=e.$=x,"function"==typeof define&&define.amd&&define("jquery",[],function(){return x}))})(window);
|
examples/node_modules/react-native/node_modules/react-tools/src/browser/ui/dom/components/__tests__/LocalEventTrapMixin-test.js
|
yhyuan/react-native-swiper
|
/**
* 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';
describe('LocalEventTrapMixin', function() {
var EventConstants;
var LocalEventTrapMixin;
var React;
var ReactTestUtils;
beforeEach(function() {
EventConstants = require('EventConstants');
LocalEventTrapMixin = require('LocalEventTrapMixin');
React = require('React');
ReactTestUtils = require('ReactTestUtils');
});
it('throws when trapping bubbled state on null', function() {
var BadImage = React.createClass({
mixins: [LocalEventTrapMixin],
render: function() {
return null;
},
componentDidMount: function() {
this.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load');
}
});
expect(function() {
ReactTestUtils.renderIntoDocument(<BadImage />);
}).toThrow(
'Invariant Violation: ' +
'LocalEventTrapMixin.trapBubbledEvent(...): ' +
'Requires node to be rendered.'
);
});
});
|
app/components/Legend/__tests__/index-test.js
|
nelsonomuto/budgeting-sample-app-webpack2
|
import React from 'react';
import renderer from 'react-test-renderer';
import Legend from '../';
// mock nested components
jest.mock('../LegendItem', () => 'div');
it('renders correctly', () => {
const mockData = [{ key: 1 }, { key: 2 }];
const tree = renderer
.create(<Legend data={mockData} dataValue="test" dataLabel="test" dataKey="key" color={() => {}} />)
.toJSON();
expect(tree).toMatchSnapshot();
});
|
front-end/src/component/skills/babel_icon.js
|
axelmichael11/website
|
import React from 'react'
export default React.createClass({
render(){
return(
<svg viewBox="0 0 128 128" className="skills-icons">
<path className="cls-1" d="M90.18,50.5v.15l.31,0a1.18,1.18,0,0,1,.09-.43l0-.27c-.13,0-.26.21-.38.58Zm-2.94-7.08,0-.27-.44,0,0,.27.44,0Zm-8.54,16a14.07,14.07,0,0,0-2.35-3c0-.32.5-.79,1.59-1.42L81,52.34A7.79,7.79,0,0,0,82.28,48l0-.46c-.12-1.38-1.12-2.49-3-3.34q-1.68-1.13-6-1.25a35.58,35.58,0,0,0-9.41,2.58,38.64,38.64,0,0,1-3.63,2.29l0,.23a.87.87,0,0,0,.36-.16.21.21,0,0,1,.26.21L61,48h.11v.1a12.79,12.79,0,0,1-2.52,2l.13.24h-.11l-.28-.1c0,.08-.11.14-.34.16v.1l.27.34a1,1,0,0,1-.39-.09,1.88,1.88,0,0,0-1.16.63l.16-.69a56.27,56.27,0,0,0,1.16-6.5L58,44A4.73,4.73,0,0,1,56.91,43a3.71,3.71,0,0,0,0-.49l0-.1-.11,0q-1.85,2.77-7.11,9.45-4,4.75-4.14,5.28c-1.09,1.13-1.61,1.81-1.56,2-.29.19-.41.37-.36.58a.12.12,0,0,1-.16-.09,3.17,3.17,0,0,1-2.08,1.45l-1,.22a.23.23,0,0,0-.19.28l0,.12.36-.08,0,.1-.82.32-1.45.34-.76,0c-.11.11.61,0,.33.06l-1,.22c-.58.13-.89.08-1-.15l-.11,0a.54.54,0,0,1,0,.24l-.06-.23-.76.18Q35,62.29,32,59c0-.43.67-1.05,2.12-1.86l4.08-3.59q1.37-1.76,1.63-5.65l-.06-.61c-.16-1.83-1.48-3.3-4-4.44-1.47-1-4.12-1.53-7.94-1.61a47.82,47.82,0,0,0-12.39,3.36,47.39,47.39,0,0,1-4.78,3l0,.32a1.25,1.25,0,0,0,.48-.19.27.27,0,0,1,.34.26l.32-.18H12V48a18.64,18.64,0,0,1-3.34,2.6l.18.28H8.7l-.34-.12c0,.09-.15.16-.48.19l0,.17.37.41a1.36,1.36,0,0,1-.5-.1A3.17,3.17,0,0,0,5.63,53l.18.28a4.47,4.47,0,0,1,1.06-.85l0,.46a1.53,1.53,0,0,0-.48.19l.38.58a12.63,12.63,0,0,1,2.43-2c.44.11.67.25.68.4l.34,0a26,26,0,0,1,7.14-3.86l0,.32q-.66,1-.89,1a1,1,0,0,0,.23.59q.06.6-3.21,8.1Q6.17,75.5,1.13,83.84a1.08,1.08,0,0,0,.2.45,4.17,4.17,0,0,0,1.57-.6l.18,0,0,.32.31,0,.32-.18c0,.09.11.14.33.12l0,.32a2.83,2.83,0,0,1-.52,1.42A7.37,7.37,0,0,0,2.48,88v.15l.31,0a19.55,19.55,0,0,0,3.06-4.41,48.85,48.85,0,0,0,9-3.38,8.39,8.39,0,0,0,4.74-1.63l0-.17-.78.23-.18,0,0-.17a7.07,7.07,0,0,0,3.17-1q4.46-3.44,6.74-4.87,4.68-3.44,6.08-6.7l.52-.12a6.81,6.81,0,0,0,.75,0c0-.08,0-.13.1-.15.7-.07.36,0,.81-.06l1.17-.27.2,0-.09.06a1.14,1.14,0,0,0,.43,0l.08.34-5.34,8.49L32,75.71l-.58,1.94.11,0,.58-.24-.19.75.06.22.16.2c-.07,0-.1.07-.08.15l0,.12.24-.06q.53-.46.45-.84a2.21,2.21,0,0,0,.76.06l0,.12c-.23.06-.35.24-.37.56l0,.12.13,0c1.94-2.12,6.69-9.35,10.5-14.27q-.18-.8,6-2.22l.13,0q.22,1-1,4.67a12.58,12.58,0,0,0-.71,2.44,18.69,18.69,0,0,0-.92,3.22L45.9,77.34A43.46,43.46,0,0,0,43.74,85a1,1,0,0,1,.4,0l.21-.18a.12.12,0,0,0,.16.09l-.08-.34.63,0c.19,0,.34-.28.48-.71,0-.64.1-1,.39-1.06a10.29,10.29,0,0,1,.72-2.32,10.29,10.29,0,0,1,.81-2.6c.55-2,1-3,1.21-3.06l.06.24-.4,1a50.68,50.68,0,0,1-2.12,7.35l.21.89.13,0q2.6-5.59,7.48-22.14A2.89,2.89,0,0,1,55.4,60l-.19-.2,0-.1a1.27,1.27,0,0,0,.78-.44c0-.08-.34-.21-1-.37l1.62-7a2.41,2.41,0,0,1,.62-.48l0,.35a.87.87,0,0,0-.36.16l.31.44A10,10,0,0,1,59,50.83c.34.09.5.21.52.32l.24,0a19.75,19.75,0,0,1,5.43-2.91l0,.23q-.49.74-.67.75a1,1,0,0,0,.15.45,42.49,42.49,0,0,1-2.41,6.16,167.41,167.41,0,0,1-9.44,19.55.87.87,0,0,0,.17.34,3,3,0,0,0,1.18-.46h.11l0,.23.26,0,.23-.12q0,.1.25.08l0,.25a2.12,2.12,0,0,1-.4,1.06,5.31,5.31,0,0,0-.85,1.82v.12l.24,0a14.72,14.72,0,0,0,2.32-3.35,37.55,37.55,0,0,0,6.8-2.56,6.39,6.39,0,0,0,3.62-1.24v-.12l-.61.18h-.13v-.12a5.36,5.36,0,0,0,2.4-.77c2.25-1.73,4-3,5.12-3.7,3.6-2.62,5.27-5.13,5.07-7.55Zm-.62.16.08.94c-.11.23-.23.35-.34.36l-.14-1.6c.26.09.39.19.4.3ZM7.52,52H7.36l0-.29L8,51.66v.15a1.24,1.24,0,0,0-.47.19ZM4.38,83.4a2,2,0,0,0-1-.21l0-.46c0-.18.08-.3.31-.34s.33.13.34.43a6.78,6.78,0,0,1,.89-1l.34.14c-.11.93-.4,1.41-.86,1.44ZM37.93,48.3c-.16,0-.48-.48-.93-1.45l0-.29c.3,0,.61.46.93,1.45l0,.29Zm-.45-3.48-.13.31-4.56-1.9q4.56.15,4.69,1.59ZM18.25,61.35l-.64.06,0-.29.64-.06,0,.29Zm-.52-9.92h.16l0,.46c-.15,0-.34.23-.59.66l0-.32c.29-.34.44-.61.42-.79Zm-1.35,3.19.06.61h-.16l-.06-.61Zm-.71,1.14.31,0c0,.5-.17.77-.42.79h-.16a1.46,1.46,0,0,0,.27-.77Zm-.53,1.58.18,0v.15l-.29.48-.31,0v-.15a.4.4,0,0,0,.42-.49Zm-.52,1.43-.09.76h-.16l-.07-.75.32,0ZM9.38,73.62c-.21,1-.43,1.57-.66,1.59v-.15a1.67,1.67,0,0,1,.67-1.44Zm-1,2.08v.15a.27.27,0,0,1-.28.34V76q0-.27.28-.34ZM8.15,80l.48,0,0,.17a1.25,1.25,0,0,0-.48.19l-.31,0c0-.16.08-.28.28-.34Zm13.79-4.26a25.56,25.56,0,0,0-4.8,2.73Q12.72,80,12.76,80.39a48,48,0,0,0-5.17,2.27,1.86,1.86,0,0,1-.85-.22,1.37,1.37,0,0,1,.71-1.3,2.75,2.75,0,0,1,1.31.21,12.78,12.78,0,0,1,2.53-.83l0-.32-1,.08A13.17,13.17,0,0,1,13.1,79l.48,0v.15c-.83.07-1.29.32-1.39.75,0,.2.13.28.34.26.62-.39.93-.62.92-.69q1.77-.34,9.81-5.13l0,.29c0,.14-.45.53-1.37,1.2Zm-8.22,2.7a3.17,3.17,0,0,0,2-.93c.22,0,.34.07.35.26a7.17,7.17,0,0,0-2.19,1h-.16l0-.31ZM27,68.27l-4.11,3.26a40.68,40.68,0,0,1-4.94,3q-7.3,4-9.07,4.17l-.18,0q.22-.82,6.5-13.31a35.47,35.47,0,0,0,8.71-2.58l1-.08a5.59,5.59,0,0,1,4.49,1.15l.06.61c-.74,2.13-1.56,3.38-2.44,3.75Zm-8-4.52.66-.06v.15L19,63.9v-.15Zm9.29-1.57.48,0c.45.21.68.4.7.57v.15a1.36,1.36,0,0,1-1.19-.67Zm1.31-7.48A19,19,0,0,1,26,57.31c-.63.06-3,1-7.07,2.76A1.29,1.29,0,0,0,18.3,60l0-.29a3.81,3.81,0,0,1,.79-2.22c.32-1.68.66-2.64,1-2.87l3.4-7.65q-.06-.71,2.18-1.09l.48,0,0,.44c1.46-.22,2.38-.35,2.73-.38,2.7-.23,4.11.32,4.22,1.63l.31,0-.07-.77.34,0A2.12,2.12,0,0,1,35,48.25a2.48,2.48,0,0,1-.69,1.59c-.21,0-.33-.13-.34-.43l-.34,0-.07.93q-2.05,3.07-3,3.16c-.56.77-.9,1.16-1,1.16Zm2.09,5.36a1.2,1.2,0,0,0-.67-.26l0-.46.31,0,.68.4a.27.27,0,0,1-.28.34Zm2.16,2.56c.3.12.48.25.51.37l-.15,0h0l-.09,0-.22.18-.06-.62ZM34,63.9l0-.12.39-.09,0,.12L34,63.9ZM34.94,65c.4-.07.6-.09,1.34-.26l0,.12-1.42.33a1.87,1.87,0,0,0,0-.19Zm1.38.59a6.06,6.06,0,0,0-1.42.2l0-.12,1.19-.38.57-.13.06.22c-.26.06-.07.06-.37.21Zm1.26-.3a.26.26,0,0,1-.32-.19l.36-.08a.22.22,0,0,1,.3.19l-.34.08ZM41,61.57l0-.12.59-.14.06.22-.62,0Zm3.64,22.34a.92.92,0,0,0,0-.37l.13,0a.21.21,0,0,1,.29.17l0,.12-.48.11Zm2.55-21.38-.26,0a7.38,7.38,0,0,1-1.06.35l-.24.06a.24.24,0,0,1-.31-.17L47,62.34l.56-.26.19.21a1.25,1.25,0,0,0-.58.24Zm1.31-.42,0-.12a.71.71,0,0,0,.32-.21L50,61.51l0,.12a9.36,9.36,0,0,0-1.53.48Zm.19-2.45a1,1,0,0,0-.34.21c0-.08-.19-.08-.5,0-.06-.23.84-.56,2.69-1l.26-.06.06.22c-1.3.38-2,.6-2.17.62Zm3.26-3.52c-.13,1.48-.65,2.32-1.57,2.53l0-.12-.82.32-.36.08a.91.91,0,0,1-.5,0l-.07-.33a49.32,49.32,0,0,1,3.56-4.91l.28,0a5.09,5.09,0,0,1-.48,2.39Zm5.77-4.94H57.6l0-.23.48,0v.12a1.57,1.57,0,0,0-.36.15ZM55.34,75.06a1.49,1.49,0,0,0-.75-.17l0-.35q0-.18.22-.25c.16,0,.25.09.27.34a4.09,4.09,0,0,1,.67-.77L56,74c-.09.71-.31,1.08-.64,1.11ZM80.81,48.42c-.12,0-.35-.36-.72-1.12l0-.23c.23,0,.48.34.72,1.09l0,.26Zm-.34-2.66-.11.24-3.45-1.44c2.3.07,3.49.48,3.56,1.2ZM65.86,58.3l-.48,0,0-.23.48,0,0,.23Zm-.4-7.54h.13l0,.35q-.18,0-.45.5l0-.23a1.08,1.08,0,0,0,.31-.62Zm-1,2.42,0,.46h-.13l0-.46Zm-.55.87.24,0q0,.59-.31.61H63.7a1.26,1.26,0,0,0,.2-.61Zm-.39,1.19h.11v.12l-.21.37-.24,0v-.12c.25,0,.36-.15.34-.38Zm-.39,1.08-.08.6h-.11l0-.59.24,0Zm-4,11.3q-.24,1.17-.5,1.2v-.1a1.33,1.33,0,0,1,.51-1.1ZM58.4,69.2v.1a.21.21,0,0,1-.22.27v-.12q0-.18.22-.25Zm-.21,3.28.37,0v.12a1.07,1.07,0,0,0-.36.14l-.24,0q0-.2.22-.25Zm10.46-3.23A21.75,21.75,0,0,0,65,71.31c-2.24.78-3.34,1.27-3.33,1.46a35.33,35.33,0,0,0-3.9,1.72,1.45,1.45,0,0,1-.64-.18,1,1,0,0,1,.54-1,2.1,2.1,0,0,1,1,.15,10.83,10.83,0,0,1,1.93-.62l0-.23-.75.07a10,10,0,0,1,2.14-1l.37,0v.1c-.63.06-1,.24-1.06.58a.21.21,0,0,0,.26.21c.47-.31.69-.48.69-.54q1.34-.24,7.44-3.9l0,.23c0,.09-.34.39-1,.9Zm-6.24,2A2.5,2.5,0,0,0,64,70.6c.16,0,.25.06.26.21a5.92,5.92,0,0,0-1.66.71h-.13l0-.22Zm10.08-7.74-3.1,2.5a30.16,30.16,0,0,1-3.77,2.3q-5.53,3-6.89,3.16H58.6q.17-.63,4.95-10.1a27.26,27.26,0,0,0,6.61-2l.75-.07a4.2,4.2,0,0,1,3.4.89l0,.46c-.57,1.6-1.18,2.54-1.85,2.83ZM66.4,60.13l.48,0v.12l-.48,0v-.12Zm7.05-1.2.37,0c.34.17.52.32.53.44v.1a1,1,0,0,1-.91-.51Zm1-5.67a14.26,14.26,0,0,1-2.66,2,35.66,35.66,0,0,0-5.37,2.08,1.23,1.23,0,0,0-.49-.07l0-.23a2.92,2.92,0,0,1,.59-1.69c.24-1.29.51-2,.79-2.17l2.6-5.81c0-.34.52-.62,1.64-.84l.37,0,0,.35q1.65-.27,2.07-.31c2-.18,3.12.23,3.21,1.24l.24,0,0-.56.24,0a1.55,1.55,0,0,1,1,1.18,1.93,1.93,0,0,1-.49,1.22c-.16,0-.25-.09-.27-.34l-.24,0-.07.7c-1,1.57-1.79,2.39-2.26,2.42-.42.57-.68.86-.8.87Zm1.09,3.88,0-.35.24,0,.52.32a.22.22,0,0,1-.22.25,1,1,0,0,0-.51-.2ZM32.15,79.76l-.24.06L31.7,80a.21.21,0,0,0,.29.17c.16,0,.22-.13.19-.28l0-.12Zm-.92-1.84,0,.12c.16,0,.22-.13.19-.28l0-.12a.22.22,0,0,0-.19.28Zm6.6-12.39.18-.11-.09,0a.11.11,0,0,0-.08.13Zm0-3.21.28-.07L38,62l-.28.07.06.24Zm65.85,9.41-.63-.07-.11.24V72l3.77-.32,0-.23-3,.26Zm3.45-.29,0,.23h0l0-.23Zm15.83-2.07,0,.23.41.07,0-.23-.41-.07Zm-.58,0a15.72,15.72,0,0,1-3.78.57l0,.23.26,0H119l0,0,.31-.12c2.8-.31,3.13-.2,3.1-.51v-.11Zm-17-4.12-.25-.08a4.2,4.2,0,0,0-.3,1v.1c.2,0,.37-.34.54-1Zm-3.41-1.84v-.12h-.13l-.23.15.13.22c.18,0,.26-.1.24-.26Zm7.41,7.66,0-.23h-.07l0,.23Zm15.37-3.47.18,0c.1,0,.15-.09.14-.24l-.1-.22a3,3,0,0,0-1.46.37v-.12l-.77.07c0-.23-.08-.35-.19-.34l-.4,0c-.47,0-.69,0-.92.2,0-.08,0-.12-.08-.12l-.45,0-.26.15c0-.08,0-.12-.08-.12l-.16.14v-.12l-.62,0h-.15l0,.23.32.08.3,0a.54.54,0,0,0,.34.07l.26-.13v.1a19.08,19.08,0,0,1-2.46.47.43.43,0,0,0-.25-.1l0,0a.2.2,0,0,1-.19-.21l.52-.07a3.19,3.19,0,0,0,.35.09c.42-.21.44-.29.66-.31l0-.23a15.19,15.19,0,0,1-2.66.25h-.08l0-.23c2.31-.28,1.54-.12,2.33-.34,0,.08,0,.12.08.12a.54.54,0,0,1,.32-.16h.16A8.46,8.46,0,0,0,122,66.6v.1l.26-.13.24,0c0-.23.34-.27.46-.28l0-.25c-2.81.57-3.55.41-4.33.63v-.1a3.41,3.41,0,0,1-1,.08.49.49,0,0,0-.23.15c0-.08,0-.12-.09-.12h0l-2.39.39c0-.07,0-.1-.09-.09a12.17,12.17,0,0,1-2.56.46.78.78,0,0,0-.31.13c0-.07,0-.1-.13-.09l-1,.08-.68.17c0-.07,0-.1-.13-.09a5.41,5.41,0,0,1-1,.19h0c-.17,0,.08,0,0-.1l-.21.12c-.3,0-.14,0-1.16,0-1.8.22-1.6.25-1.8.26l-.67,0a.09.09,0,0,1-.1.11c-.76-.1-1.16-.22-1.16-.36q.15-1.09.53-1.12h.13l-.11.24h.13c.24-.13.35-.25.34-.36l0-.25-.24,0,0-.23a.84.84,0,0,1,.07-.47l.55-.89,0,.23.26,0,0-.23-.15-.21a1,1,0,0,1,.47-.27v-.12l-.35,0,0-.35a10,10,0,0,0,1-2.57l.25.1c.16,0,.23-.1.22-.27l-.24,0v-.1a.89.89,0,0,1,.09-.49,1.56,1.56,0,0,0,.52-1.22c.07,0,.11,0,.12.11.33-.19.58-.68.76-1.5a46.87,46.87,0,0,0,2.47-6.25c2.05-5.52,2-6.1,2.25-7.41l-.24,0a.84.84,0,0,1-.09.48,1,1,0,0,0-.39-.09v-.1a2.83,2.83,0,0,1,.61-1.71h.11l.21.8.24,0a7.3,7.3,0,0,1,.19-1c0-.12-.1-.2-.29-.21l-.23.15c0-.17,0-.61,0-1.3h-.12a.91.91,0,0,1-.32-.51l-1.33.13a1.22,1.22,0,0,0-.15-.41c0-.12.29-.24.9-.36l.27.1.25-.15c0,.08.06.12.15.11l.25-.15c0,.08.06.12.15.11h.12l0-.27c-.19,0-.68,0-1.46,0l-.25.17v-.15q-9.38.77-10.65.89c-.11,0-.55,0-1.32,0,0,.1-.08.16-.27.18l-.27-.12L98,41a6.06,6.06,0,0,1-1.08,0,.93.93,0,0,1-.51.2L99.06,41a1.22,1.22,0,0,1-.65.21.9.9,0,0,1-.53-.09,15.15,15.15,0,0,1-2,.47l-.27-.1-4.36.67a1.09,1.09,0,0,0-.59-.09,7.24,7.24,0,0,0-1.16.25l-2.11.88.16.26a1.17,1.17,0,0,0,.43-.17l.75.07-.09.7a1.88,1.88,0,0,0-1.2,1.34c-1,.46-1.55.78-1.55,1v.12h.16l.28-.15.33.39,0,.54q0,.25-5.21,11c-3,6.9-4.6,10.67-4.75,11.35-1,.29-1.63.71-1.81,1.27,0,.18.33.3.92.34l0,.27-.27.45,0,.54q0,.42,2.26.64c0-.09,0-.15.14-.16a8.16,8.16,0,0,1-.28,2H78a3.47,3.47,0,0,0,.88-1.73H79c.15,0,.31.16.49.52q-.28.11-2,4.45l.16.26h.16q2.05-5.2,2.58-5.75,2.7-.24,9.33-1l.28-.17a.13.13,0,0,0,.17.13l.29,0,.28-.17a.13.13,0,0,0,.17.13l3.35-.29c.89-.07,1.3-.34,1.27-.8,0-.12.51-.26,1.57-.41a1.28,1.28,0,0,1,.46.08c0-.08.52-.17,1.58-.26,0-.56.2-.86.52-.89l0-.27a4.63,4.63,0,0,0-1,.23,6.26,6.26,0,0,1-1.33-.16,1.23,1.23,0,0,1-.43.17L94.51,69l-.28.15q0-.13-.17-.11h-.13l-.3.15c0-.08-.25-.15-.74-.21l-.3.18-.58,0v-.15q4.5-.49,4.44-1.22a.26.26,0,0,1,.32.27l.88-.22,0-.27-7.18.2c0,.09,0,.15-.14.16l-.88-.07a1.06,1.06,0,0,0-.56.2L88.54,68a10,10,0,0,0-2,.33,12.73,12.73,0,0,0-2,0l-1.61.14-.75-.08c0-.48.89-2.81,2.79-7a6.11,6.11,0,0,1,1.54-2.64,1.08,1.08,0,0,1,.46.11L88,58.47l.59.09a13.45,13.45,0,0,0,3.45-.85,1.62,1.62,0,0,1,.75.07l.88-.21,2.61-.22a17.3,17.3,0,0,0,3.62-.74l0-.27c-.48,0-.74,0-.75-.23,0-.36-.38-.51-1.06-.46l0-.27.72-.21,1.88-.16,0-.27c-.07,0-.46,0-1.16,0l0-.29.73-.07c.2,0,.28-.11.26-.3-1,0-1.47,0-1.48-.15q-10.23.5-10.26.19a1.17,1.17,0,0,0-.43.19L88.06,54q2.71-5.76,3.18-5.8a1.69,1.69,0,0,1-.22.72V49l.29,0c.72-1.71,1.32-2.6,1.83-2.64,2.14-.19-.3-.33,4.29-1a.89.89,0,0,0,.41.11q2.7-.55,7.52-1.14l0-.27-1.71.16,0-.27a.93.93,0,0,0,.51-.2v.15a1,1,0,0,0,.39-.19,1.23,1.23,0,0,1,.68.08,9.92,9.92,0,0,1,1.44-.29l1.07-.1c.26-.17.38-.32.37-.46v-.12a3.38,3.38,0,0,1-.94-.06.27.27,0,0,1,.24-.3l2-.19.91-.23c0,.1.06.14.13.14a1,1,0,0,0,.39-.19l.15,0a7.45,7.45,0,0,0-.4,1.09l-.26,0a1.14,1.14,0,0,0-.15-.48H110c-2.42,6.75-3.5,9.89-5.74,15.07-.41,1.32-.75,2.06-1.05,2.22a.21.21,0,0,0,.26.21,3.25,3.25,0,0,1-.46,1.93c-1,3-1.72,4.61-2.08,4.91l.23,1.41a.22.22,0,0,1-.22.25l-.24,0c0-.39-.18-.58-.43-.55h-.13a5.54,5.54,0,0,0-.72,1.72l.24,0a.81.81,0,0,0,.45-.75l.48,0,.28.1a1.49,1.49,0,0,0-.31.85l.13.22-.32.75v.12a1.51,1.51,0,0,1,.91.26A1.63,1.63,0,0,0,102,71c.28,0,1.32,0,3.12,0l.9-.31a20.9,20.9,0,0,0,2.23-.07l.39,0,.21-.14v.12a6.11,6.11,0,0,1,1.84.07v.12l-.55,0,0,.23a.79.79,0,0,0,.44-.17c.14,0,.22.07.23.23a3.28,3.28,0,0,0-.75.17l-.24-.08c-.38.1-.3.13-.56.15l-.38-.07a.09.09,0,0,1-.09.11.2.2,0,0,0,.23.21l.39,0,2-.18.77-.17c0,.07,0,.1.1.09l.37-.14.7-.06c.54,0,.53-.08,1.71-.27,0-.07,0-.1.07-.11v.1a17.2,17.2,0,0,0,2.34-.45l0,.06c.48-.11.21-.08.34-.18,0,.08,0,.12.08.12l.34,0,0-.25h-.68v0l-.07,0h-.09v0a3.59,3.59,0,0,1-.76.06l-1.71.09v-.12l1-.13.34,0,.2-.14V70c1.34-.11,1.82.22,8-1.1.34,0,.31-.31.52-.89a.58.58,0,0,1-.33-.07,9.7,9.7,0,0,1-1.77.26c-.08,0-.15-.07-.18-.21v-.1l1,0a2.4,2.4,0,0,0,1-.34c0,.08-.2.13-.08.12Zm-45.88.74-.44,0a8.26,8.26,0,0,1,.7-2l.29,0a7.62,7.62,0,0,1-.55,2Zm.53-2.12v-.12c0-.15.08-.25.29-.3V66c0,.18-.08.28-.29.3Zm5.82,4.5v.12l-.73.07v-.12l.73-.07Zm-.88-.07c0,.15-.21.32-.7.48l-.89-.07-.29,0,0-.27,1.91-.18Zm5.89-27.11-.44,0v-.15c0-.15.07-.25.26-.3h.16l.3.12a.26.26,0,0,1-.27.3Zm6.66-1.3H97l0,.27-.4,0a.27.27,0,0,1,.24-.3Zm-1.68.59-.66-.07v-.12a7.15,7.15,0,0,0,1.69-.32c0,.1.1.14.27.12l0,.27-.26,0a.9.9,0,0,1-.53-.09,1.14,1.14,0,0,1-.51.19ZM96,45.29v-.12l1.07-.1v.12l-1.07.1Zm1.15-.93V44.2l.52,0v.15l-.52,0Zm.12-1.83h-.14l.12-.29,1.19-.11v.15a7.2,7.2,0,0,0-1.18.24Zm.61,2.57,0-.27.52,0q.27,0,.28.25l-.78.07Zm3.16-4.3-.67.19h-.12A6.85,6.85,0,0,1,99,41c.87-.06,1.7-.12,2-.17Zm-.72,3v.12L99.4,44v-.12l.92-.08Zm1.51.72c0-.11-.19-.19-.55-.22l-.92.26-.71,0c-.16-.11-.24-.19-.25-.24l.82,0,1.84-.3.94,0v.15a5.28,5.28,0,0,0-1.18.24ZM111.32,42h.21a3.57,3.57,0,0,1,1.11-.75,6.55,6.55,0,0,1-1.57,3.27l-.52-.32a17,17,0,0,0,.77-2.22Zm-1.6,2.75h.13c-.18.34-.34.51-.47.52l0-.35a.79.79,0,0,0,.36-.16Zm-1,2.47a3.5,3.5,0,0,1,.72-1.72v.12c-.13.93-.34,1.43-.61,1.46l0,.59a1.32,1.32,0,0,0-.32.75h-.13l-.07-.81c.15,0,.27-.15.35-.39Zm-.4,1.34a3.41,3.41,0,0,1-.27,1h-.13l0-.35c.18-.41.33-.62.43-.62Zm-7.52,21.82v-.1l.24,0,0,.35c-.13,0-.22-.07-.26-.23Zm10.74.28c0-.08,0-.12-.13-.11l-.61.06v-.12h.06l1.43-.12v.12a1.26,1.26,0,0,0-.75.18Zm-.72-.3c.06,0,0,.06,0,.07s-.07,0,0-.07Zm.07-1.68-.8.07v-.12l.73-.07.63-.16c0,.07,0,.1.13.09.75-.13.68-.17,1-.2.12,0,.2.07.21.21l-1.93.17Zm2.8-.24a3.19,3.19,0,0,0-.79-.06v-.1l.72-.07v.1c-.07,0,.2,0,.07.12Zm.06-.13v-.1l.39,0v.1l-.39,0Zm.87-.07v-.1a.68.68,0,0,0,.28-.15.28.28,0,0,1,.32.26Zm1.11-.14V68l.48,0v.12l-.48,0Zm.66-.06c0-.14,0-.22.17-.24l.16.21a.09.09,0,0,1,.07-.11l.12.22-.52-.07ZM125.53,67h0v0Zm.17-.12c.07,0,.11-.09-.07-.12s.09.12-.09.13V67l.1-.07-.1.08h0l-.2.25.39-.14h0l0-.23Zm.68.53h-.07l0,.23.55,0c0-.15-.37-.2-.49-.2Z"></path>
</svg>
)
}
})
|
ajax/libs/vega/2.0.1/vega.js
|
froala/cdnjs
|
(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.vg = 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){
module.exports = {
version: '2.0.1',
dataflow: require('vega-dataflow'),
parse: require('./src/parse/'),
scene: {
Bounder: require('./src/scene/Bounder'),
Builder: require('./src/scene/Builder'),
Encoder: require('./src/scene/Encoder'),
GroupBuilder: require('./src/scene/GroupBuilder'),
},
transforms: require('./src/transforms'),
schema: require('./src/core/schema'),
config: require('./src/core/config'),
util: require('datalib/src/util'),
debug: require('vega-logging').debug
};
},{"./src/core/config":82,"./src/core/schema":83,"./src/parse/":89,"./src/scene/Bounder":101,"./src/scene/Builder":102,"./src/scene/Encoder":103,"./src/scene/GroupBuilder":104,"./src/transforms":130,"datalib/src/util":20,"vega-dataflow":35,"vega-logging":41}],2:[function(require,module,exports){
},{}],3:[function(require,module,exports){
var util = require('../util'),
Measures = require('./measures'),
Collector = require('./collector');
function Aggregator() {
this._cells = {};
this._aggr = [];
this._stream = false;
}
var Flags = Aggregator.Flags = {
ADD_CELL: 1,
MOD_CELL: 2
};
var proto = Aggregator.prototype;
// Parameters
proto.stream = function(v) {
if (v == null) return this._stream;
this._stream = !!v;
this._aggr = [];
return this;
};
// key accessor to use for streaming removes
proto.key = function(key) {
if (key == null) return this._key;
this._key = util.$(key);
return this;
};
// Input: array of objects of the form
// {name: string, get: function}
proto.groupby = function(dims) {
this._dims = util.array(dims).map(function(d, i) {
d = util.isString(d) ? {name: d, get: util.$(d)}
: util.isFunction(d) ? {name: util.name(d) || d.name || ('_' + i), get: d}
: (d.name && util.isFunction(d.get)) ? d : null;
if (d == null) throw 'Invalid groupby argument: ' + d;
return d;
});
return this.clear();
};
// Input: array of objects of the form
// {name: string, ops: [string, ...]}
proto.summarize = function(fields) {
fields = summarize_args(fields);
this._count = true;
var aggr = (this._aggr = []),
m, f, i, j, op, as, get;
for (i=0; i<fields.length; ++i) {
for (j=0, m=[], f=fields[i]; j<f.ops.length; ++j) {
op = f.ops[j];
if (op !== 'count') this._count = false;
as = (f.as && f.as[j]) || (op + (f.name==='*' ? '' : '_'+f.name));
m.push(Measures[op](as));
}
get = f.get && util.$(f.get) ||
(f.name === '*' ? util.identity : util.$(f.name));
aggr.push({
name: f.name,
measures: Measures.create(
m,
this._stream, // streaming remove flag
get, // input tuple getter
this._assign) // output tuple setter
});
}
return this.clear();
};
// Convenience method to summarize by count
proto.count = function() {
return this.summarize({'*':'count'});
};
// Override to perform custom tuple value assignment
proto._assign = function(object, name, value) {
object[name] = value;
};
function summarize_args(fields) {
if (util.isArray(fields)) { return fields; }
if (fields == null) { return []; }
var a = [], name, ops;
for (name in fields) {
ops = util.array(fields[name]);
a.push({name: name, ops: ops});
}
return a;
}
// Cell Management
proto.clear = function() {
return (this._cells = {}, this);
};
proto._cellkey = function(x) {
var d = this._dims,
n = d.length, i,
k = String(d[0].get(x));
for (i=1; i<n; ++i) {
k += '|' + d[i].get(x);
}
return k;
};
proto._cell = function(x) {
var key = this._dims.length ? this._cellkey(x) : '';
return this._cells[key] || (this._cells[key] = this._newcell(x));
};
proto._newcell = function(x) {
var cell = {
num: 0,
tuple: this._newtuple(x),
flag: Flags.ADD_CELL,
aggs: {}
};
var aggr = this._aggr, i;
for (i=0; i<aggr.length; ++i) {
cell.aggs[aggr[i].name] = new aggr[i].measures(cell, cell.tuple);
}
if (cell.collect) {
cell.data = new Collector(this._key);
}
return cell;
};
proto._newtuple = function(x) {
var dims = this._dims,
t = {}, i, n;
for (i=0, n=dims.length; i<n; ++i) {
t[dims[i].name] = dims[i].get(x);
}
return this._ingest(t);
};
// Override to perform custom tuple ingestion
proto._ingest = util.identity;
// Process Tuples
proto._add = function(x) {
var cell = this._cell(x),
aggr = this._aggr, i;
cell.num += 1;
if (!this._count) { // skip if count-only
if (cell.collect) cell.data.add(x);
for (i=0; i<aggr.length; ++i) {
cell.aggs[aggr[i].name].add(x);
}
}
cell.flag |= Flags.MOD_CELL;
};
proto._rem = function(x) {
var cell = this._cell(x),
aggr = this._aggr, i;
cell.num -= 1;
if (!this._count) { // skip if count-only
if (cell.collect) cell.data.rem(x);
for (i=0; i<aggr.length; ++i) {
cell.aggs[aggr[i].name].rem(x);
}
}
cell.flag |= Flags.MOD_CELL;
};
proto._mod = function(curr, prev) {
var cell0 = this._cell(prev),
cell1 = this._cell(curr),
aggr = this._aggr, i;
if (cell0 !== cell1) {
cell0.num -= 1;
cell1.num += 1;
if (cell0.collect) cell0.data.rem(prev);
if (cell1.collect) cell1.data.add(curr);
} else if (cell0.collect && !util.isObject(curr)) {
cell0.data.rem(prev);
cell0.data.add(curr);
}
for (i=0; i<aggr.length; ++i) {
cell0.aggs[aggr[i].name].rem(prev);
cell1.aggs[aggr[i].name].add(curr);
}
cell0.flag |= Flags.MOD_CELL;
cell1.flag |= Flags.MOD_CELL;
};
proto.result = function() {
var result = [],
aggr = this._aggr,
cell, i, k;
for (k in this._cells) {
cell = this._cells[k];
if (cell.num > 0) {
// consolidate collector values
if (cell.collect) {
cell.data.values();
}
// update tuple properties
for (i=0; i<aggr.length; ++i) {
cell.aggs[aggr[i].name].set();
}
// add output tuple
result.push(cell.tuple);
} else {
delete this._cells[k];
}
cell.flag = 0;
}
this._rems = false;
return result;
};
proto.changes = function() {
var changes = {add:[], rem:[], mod:[]},
aggr = this._aggr,
cell, flag, i, k;
for (k in this._cells) {
cell = this._cells[k];
flag = cell.flag;
// consolidate collector values
if (cell.collect) {
cell.data.values();
}
// update tuple properties
for (i=0; i<aggr.length; ++i) {
cell.aggs[aggr[i].name].set();
}
// organize output tuples
if (cell.num <= 0) {
changes.rem.push(cell.tuple);
delete this._cells[k];
} else if (flag & Flags.ADD_CELL) {
changes.add.push(cell.tuple);
} else if (flag & Flags.MOD_CELL) {
changes.mod.push(cell.tuple);
}
cell.flag = 0;
}
this._rems = false;
return changes;
};
proto.execute = function(input) {
return this.clear().insert(input).result();
};
proto.insert = function(input) {
this._consolidate();
for (var i=0; i<input.length; ++i) {
this._add(input[i]);
}
return this;
};
proto.remove = function(input) {
if (!this._stream) {
throw 'Aggregator not configured for streaming removes.' +
' Call stream(true) prior to calling summarize.';
}
for (var i=0; i<input.length; ++i) {
this._rem(input[i]);
}
this._rems = true;
return this;
};
// consolidate removals
proto._consolidate = function() {
if (!this._rems) return;
for (var k in this._cells) {
if (this._cells[k].collect) {
this._cells[k].data.values();
}
}
this._rems = false;
};
module.exports = Aggregator;
},{"../util":20,"./collector":4,"./measures":5}],4:[function(require,module,exports){
var util = require('../util');
var stats = require('../stats');
var REM = '__dl_rem__';
function Collector(key) {
this._add = [];
this._rem = [];
this._key = key || null;
this._last = null;
}
var proto = Collector.prototype;
proto.add = function(v) {
this._add.push(v);
};
proto.rem = function(v) {
this._rem.push(v);
};
proto.values = function() {
this._get = null;
if (this._rem.length === 0) return this._add;
var a = this._add,
r = this._rem,
k = this._key,
x = Array(a.length - r.length),
i, j, n, m;
if (!util.isObject(r[0])) {
// processing raw values
m = stats.count.map(r);
for (i=0, j=0, n=a.length; i<n; ++i) {
if (m[a[i]] > 0) {
m[a[i]] -= 1;
} else {
x[j++] = a[i];
}
}
} else if (k) {
// has unique key field, so use that
m = util.toMap(r, k);
for (i=0, j=0, n=a.length; i<n; ++i) {
if (!m.hasOwnProperty(k(a[i]))) { x[j++] = a[i]; }
}
} else {
// no unique key, mark tuples directly
for (i=0, n=r.length; i<n; ++i) {
r[i][REM] = 1;
}
for (i=0, j=0, n=a.length; i<n; ++i) {
if (!a[i][REM]) { x[j++] = a[i]; }
}
for (i=0, n=r.length; i<n; ++i) {
delete r[i][REM];
}
}
this._rem = [];
return (this._add = x);
};
// memoizing statistics methods
proto.extent = function(get) {
if (this._get !== get || !this._ext) {
var v = this.values(),
i = stats.extent.index(v, get);
this._ext = [v[i[0]], v[i[1]]];
this._get = get;
}
return this._ext;
};
proto.argmin = function(get) {
return this.extent(get)[0];
};
proto.argmax = function(get) {
return this.extent(get)[1];
};
proto.min = function(get) {
var m = this.extent(get)[0];
return m ? get(m) : +Infinity;
};
proto.max = function(get) {
var m = this.extent(get)[1];
return m ? get(m) : -Infinity;
};
proto.quartile = function(get) {
if (this._get !== get || !this._q) {
this._q = stats.quartile(this.values(), get);
this._get = get;
}
return this._q;
};
proto.q1 = function(get) {
return this.quartile(get)[0];
};
proto.q2 = function(get) {
return this.quartile(get)[1];
};
proto.q3 = function(get) {
return this.quartile(get)[2];
};
module.exports = Collector;
},{"../stats":17,"../util":20}],5:[function(require,module,exports){
var util = require('../util');
var types = {
'values': measure({
name: 'values',
init: 'cell.collect = true;',
set: 'cell.data.values()', idx: -1
}),
'count': measure({
name: 'count',
set: 'cell.num'
}),
'missing': measure({
name: 'missing',
set: 'this.missing'
}),
'valid': measure({
name: 'valid',
set: 'this.valid'
}),
'sum': measure({
name: 'sum',
init: 'this.sum = 0;',
add: 'this.sum += v;',
rem: 'this.sum -= v;',
set: 'this.sum'
}),
'mean': measure({
name: 'mean',
init: 'this.mean = 0;',
add: 'var d = v - this.mean; this.mean += d / this.valid;',
rem: 'var d = v - this.mean; this.mean -= this.valid ? d / this.valid : this.mean;',
set: 'this.mean'
}),
'average': measure({
name: 'average',
set: 'this.mean',
req: ['mean'], idx: 1
}),
'variance': measure({
name: 'variance',
init: 'this.dev = 0;',
add: 'this.dev += d * (v - this.mean);',
rem: 'this.dev -= d * (v - this.mean);',
set: 'this.valid > 1 ? this.dev / (this.valid-1) : 0',
req: ['mean'], idx: 1
}),
'variancep': measure({
name: 'variancep',
set: 'this.valid > 1 ? this.dev / this.valid : 0',
req: ['variance'], idx: 2
}),
'stdev': measure({
name: 'stdev',
set: 'this.valid > 1 ? Math.sqrt(this.dev / (this.valid-1)) : 0',
req: ['variance'], idx: 2
}),
'stdevp': measure({
name: 'stdevp',
set: 'this.valid > 1 ? Math.sqrt(this.dev / this.valid) : 0',
req: ['variance'], idx: 2
}),
'median': measure({
name: 'median',
set: 'cell.data.q2(this.get)',
req: ['values'], idx: 3
}),
'q1': measure({
name: 'q1',
set: 'cell.data.q1(this.get)',
req: ['values'], idx: 3
}),
'q3': measure({
name: 'q3',
set: 'cell.data.q3(this.get)',
req: ['values'], idx: 3
}),
'distinct': measure({
name: 'distinct',
set: 'this.distinct(cell.data.values(), this.get)',
req: ['values'], idx: 3
}),
'argmin': measure({
name: 'argmin',
add: 'if (v < this.min) this.argmin = t;',
rem: 'if (v <= this.min) this.argmin = null;',
set: 'this.argmin = this.argmin || cell.data.argmin(this.get)',
req: ['min'], str: ['values'], idx: 3
}),
'argmax': measure({
name: 'argmax',
add: 'if (v > this.max) this.argmax = t;',
rem: 'if (v >= this.max) this.argmax = null;',
set: 'this.argmax = this.argmax || cell.data.argmax(this.get)',
req: ['max'], str: ['values'], idx: 3
}),
'min': measure({
name: 'min',
init: 'this.min = +Infinity;',
add: 'if (v < this.min) this.min = v;',
rem: 'if (v <= this.min) this.min = NaN;',
set: 'this.min = (isNaN(this.min) ? cell.data.min(this.get) : this.min)',
str: ['values'], idx: 4
}),
'max': measure({
name: 'max',
init: 'this.max = -Infinity;',
add: 'if (v > this.max) this.max = v;',
rem: 'if (v >= this.max) this.max = NaN;',
set: 'this.max = (isNaN(this.max) ? cell.data.max(this.get) : this.max)',
str: ['values'], idx: 4
}),
'modeskew': measure({
name: 'modeskew',
set: 'this.dev===0 ? 0 : (this.mean - cell.data.q2(this.get)) / Math.sqrt(this.dev/(this.valid-1))',
req: ['mean', 'stdev', 'median'], idx: 5
})
};
function measure(base) {
return function(out) {
var m = util.extend({init:'', add:'', rem:'', idx:0}, base);
m.out = out || base.name;
return m;
};
}
function resolve(agg, stream) {
function collect(m, a) {
function helper(r) { if (!m[r]) collect(m, m[r] = types[r]()); }
if (a.req) a.req.forEach(helper);
if (stream && a.str) a.str.forEach(helper);
return m;
}
var map = agg.reduce(
collect,
agg.reduce(function(m, a) { return (m[a.name] = a, m); }, {})
);
return util.vals(map).sort(function(a, b) { return a.idx - b.idx; });
}
function create(agg, stream, accessor, mutator) {
var all = resolve(agg, stream),
ctr = 'this.cell = cell; this.tuple = t; this.valid = 0; this.missing = 0;',
add = 'if (v==null) this.missing++; if (!this.isValid(v)) return; ++this.valid;',
rem = 'if (v==null) this.missing--; if (!this.isValid(v)) return; --this.valid;',
set = 'var t = this.tuple; var cell = this.cell;';
all.forEach(function(a) {
if (a.idx < 0) {
ctr = a.init + ctr;
add = a.add + add;
rem = a.rem + rem;
} else {
ctr += a.init;
add += a.add;
rem += a.rem;
}
});
agg.slice()
.sort(function(a, b) { return a.idx - b.idx; })
.forEach(function(a) {
set += 'this.assign(t,\''+a.out+'\','+a.set+');';
});
set += 'return t;';
/* jshint evil: true */
ctr = Function('cell', 't', ctr);
ctr.prototype.assign = mutator;
ctr.prototype.add = Function('t', 'var v = this.get(t);' + add);
ctr.prototype.rem = Function('t', 'var v = this.get(t);' + rem);
ctr.prototype.set = Function(set);
ctr.prototype.get = accessor;
ctr.prototype.distinct = require('../stats').count.distinct;
ctr.prototype.isValid = util.isValid;
return ctr;
}
types.create = create;
module.exports = types;
},{"../stats":17,"../util":20}],6:[function(require,module,exports){
var util = require('../util');
var units = require('../time-units');
var EPSILON = 1e-15;
function bins(opt) {
if (!opt) { throw Error("Missing binning options."); }
// determine range
var maxb = opt.maxbins || 15,
base = opt.base || 10,
logb = Math.log(base),
div = opt.div || [5, 2],
min = opt.min,
max = opt.max,
span = max - min,
step, level, minstep, precision, v, i, eps;
if (opt.step) {
// if step size is explicitly given, use that
step = opt.step;
} else if (opt.steps) {
// if provided, limit choice to acceptable step sizes
step = opt.steps[Math.min(
opt.steps.length - 1,
bisect(opt.steps, span/maxb, 0, opt.steps.length)
)];
} else {
// else use span to determine step size
level = Math.ceil(Math.log(maxb) / logb);
minstep = opt.minstep || 0;
step = Math.max(
minstep,
Math.pow(base, Math.round(Math.log(span) / logb) - level)
);
// increase step size if too many bins
do { step *= base; } while (Math.ceil(span/step) > maxb);
// decrease step size if allowed
for (i=0; i<div.length; ++i) {
v = step / div[i];
if (v >= minstep && span / v <= maxb) step = v;
}
}
// update precision, min and max
v = Math.log(step);
precision = v >= 0 ? 0 : ~~(-v / logb) + 1;
eps = Math.pow(base, -precision - 1);
min = Math.min(min, Math.floor(min / step + eps) * step);
max = Math.ceil(max / step) * step;
return {
start: min,
stop: max,
step: step,
unit: {precision: precision},
value: value,
index: index
};
}
function bisect(a, x, lo, hi) {
while (lo < hi) {
var mid = lo + hi >>> 1;
if (util.cmp(a[mid], x) < 0) { lo = mid + 1; }
else { hi = mid; }
}
return lo;
}
function value(v) {
return this.step * Math.floor(v / this.step + EPSILON);
}
function index(v) {
return Math.floor((v - this.start) / this.step + EPSILON);
}
function date_value(v) {
return this.unit.date(value.call(this, v));
}
function date_index(v) {
return index.call(this, this.unit.unit(v));
}
bins.date = function(opt) {
if (!opt) { throw Error("Missing date binning options."); }
// find time step, then bin
var dmin = opt.min,
dmax = opt.max,
maxb = opt.maxbins || 20,
minb = opt.minbins || 4,
span = (+dmax) - (+dmin),
unit = opt.unit ? units[opt.unit] : units.find(span, minb, maxb),
spec = bins({
min: unit.min != null ? unit.min : unit.unit(dmin),
max: unit.max != null ? unit.max : unit.unit(dmax),
maxbins: maxb,
minstep: unit.minstep,
steps: unit.step
});
spec.unit = unit;
spec.index = date_index;
if (!opt.raw) spec.value = date_value;
return spec;
};
module.exports = bins;
},{"../time-units":19,"../util":20}],7:[function(require,module,exports){
var gen = module.exports = {};
gen.repeat = function(val, n) {
var a = Array(n), i;
for (i=0; i<n; ++i) a[i] = val;
return a;
};
gen.zeros = function(n) {
return gen.repeat(0, n);
};
gen.range = function(start, stop, step) {
if (arguments.length < 3) {
step = 1;
if (arguments.length < 2) {
stop = start;
start = 0;
}
}
if ((stop - start) / step == Infinity) throw new Error('Infinite range');
var range = [], i = -1, j;
if (step < 0) while ((j = start + step * ++i) > stop) range.push(j);
else while ((j = start + step * ++i) < stop) range.push(j);
return range;
};
gen.random = {};
gen.random.uniform = function(min, max) {
if (max === undefined) {
max = min === undefined ? 1 : min;
min = 0;
}
var d = max - min;
var f = function() {
return min + d * Math.random();
};
f.samples = function(n) { return gen.zeros(n).map(f); };
return f;
};
gen.random.integer = function(a, b) {
if (b === undefined) {
b = a;
a = 0;
}
var d = b - a;
var f = function() {
return a + Math.floor(d * Math.random());
};
f.samples = function(n) { return gen.zeros(n).map(f); };
return f;
};
gen.random.normal = function(mean, stdev) {
mean = mean || 0;
stdev = stdev || 1;
var next;
var f = function() {
var x = 0, y = 0, rds, c;
if (next !== undefined) {
x = next;
next = undefined;
return x;
}
do {
x = Math.random()*2-1;
y = Math.random()*2-1;
rds = x*x + y*y;
} while (rds === 0 || rds > 1);
c = Math.sqrt(-2*Math.log(rds)/rds); // Box-Muller transform
next = mean + y*c*stdev;
return mean + x*c*stdev;
};
f.samples = function(n) { return gen.zeros(n).map(f); };
return f;
};
},{}],8:[function(require,module,exports){
(function (global){
var util = require('../../util');
var d3 = (typeof window !== "undefined" ? window.d3 : typeof global !== "undefined" ? global.d3 : null);
function dsv(data, format) {
if (data) {
var h = format.header;
data = (h ? h.join(format.delimiter) + '\n' : '') + data;
}
return d3.dsv(format.delimiter).parse(data);
}
dsv.delimiter = function(delim) {
var fmt = {delimiter: delim};
return function(data, format) {
return dsv(data, format ? util.extend(format, fmt) : fmt);
};
};
module.exports = dsv;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9kYXRhbGliL3NyYy9pbXBvcnQvZm9ybWF0cy9kc3YuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwiZmlsZSI6ImdlbmVyYXRlZC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgdXRpbCA9IHJlcXVpcmUoJy4uLy4uL3V0aWwnKTtcbnZhciBkMyA9ICh0eXBlb2Ygd2luZG93ICE9PSBcInVuZGVmaW5lZFwiID8gd2luZG93LmQzIDogdHlwZW9mIGdsb2JhbCAhPT0gXCJ1bmRlZmluZWRcIiA/IGdsb2JhbC5kMyA6IG51bGwpO1xuXG5mdW5jdGlvbiBkc3YoZGF0YSwgZm9ybWF0KSB7XG4gIGlmIChkYXRhKSB7XG4gICAgdmFyIGggPSBmb3JtYXQuaGVhZGVyO1xuICAgIGRhdGEgPSAoaCA/IGguam9pbihmb3JtYXQuZGVsaW1pdGVyKSArICdcXG4nIDogJycpICsgZGF0YTtcbiAgfVxuICByZXR1cm4gZDMuZHN2KGZvcm1hdC5kZWxpbWl0ZXIpLnBhcnNlKGRhdGEpO1xufVxuXG5kc3YuZGVsaW1pdGVyID0gZnVuY3Rpb24oZGVsaW0pIHtcbiAgdmFyIGZtdCA9IHtkZWxpbWl0ZXI6IGRlbGltfTtcbiAgcmV0dXJuIGZ1bmN0aW9uKGRhdGEsIGZvcm1hdCkge1xuICAgIHJldHVybiBkc3YoZGF0YSwgZm9ybWF0ID8gdXRpbC5leHRlbmQoZm9ybWF0LCBmbXQpIDogZm10KTtcbiAgfTtcbn07XG5cbm1vZHVsZS5leHBvcnRzID0gZHN2OyJdfQ==
},{"../../util":20}],9:[function(require,module,exports){
var dsv = require('./dsv');
module.exports = {
json: require('./json'),
topojson: require('./topojson'),
treejson: require('./treejson'),
dsv: dsv,
csv: dsv.delimiter(','),
tsv: dsv.delimiter('\t')
};
},{"./dsv":8,"./json":10,"./topojson":11,"./treejson":12}],10:[function(require,module,exports){
var util = require('../../util');
module.exports = function(data, format) {
var d = util.isObject(data) && !util.isBuffer(data) ?
data : JSON.parse(data);
if (format && format.property) {
d = util.accessor(format.property)(d);
}
return d;
};
},{"../../util":20}],11:[function(require,module,exports){
(function (global){
var json = require('./json');
var reader = function(data, format) {
var topojson = reader.topojson;
if (topojson == null) { throw Error('TopoJSON library not loaded.'); }
var t = json(data, format), obj;
if (format && format.feature) {
if ((obj = t.objects[format.feature])) {
return topojson.feature(t, obj).features;
} else {
throw Error('Invalid TopoJSON object: ' + format.feature);
}
} else if (format && format.mesh) {
if ((obj = t.objects[format.mesh])) {
return [topojson.mesh(t, t.objects[format.mesh])];
} else {
throw Error('Invalid TopoJSON object: ' + format.mesh);
}
} else {
throw Error('Missing TopoJSON feature or mesh parameter.');
}
};
reader.topojson = (typeof window !== "undefined" ? window.topojson : typeof global !== "undefined" ? global.topojson : null);
module.exports = reader;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9kYXRhbGliL3NyYy9pbXBvcnQvZm9ybWF0cy90b3BvanNvbi5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwiZmlsZSI6ImdlbmVyYXRlZC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIganNvbiA9IHJlcXVpcmUoJy4vanNvbicpO1xuXG52YXIgcmVhZGVyID0gZnVuY3Rpb24oZGF0YSwgZm9ybWF0KSB7XG4gIHZhciB0b3BvanNvbiA9IHJlYWRlci50b3BvanNvbjtcbiAgaWYgKHRvcG9qc29uID09IG51bGwpIHsgdGhyb3cgRXJyb3IoJ1RvcG9KU09OIGxpYnJhcnkgbm90IGxvYWRlZC4nKTsgfVxuXG4gIHZhciB0ID0ganNvbihkYXRhLCBmb3JtYXQpLCBvYmo7XG5cbiAgaWYgKGZvcm1hdCAmJiBmb3JtYXQuZmVhdHVyZSkge1xuICAgIGlmICgob2JqID0gdC5vYmplY3RzW2Zvcm1hdC5mZWF0dXJlXSkpIHtcbiAgICAgIHJldHVybiB0b3BvanNvbi5mZWF0dXJlKHQsIG9iaikuZmVhdHVyZXM7XG4gICAgfSBlbHNlIHtcbiAgICAgIHRocm93IEVycm9yKCdJbnZhbGlkIFRvcG9KU09OIG9iamVjdDogJyArIGZvcm1hdC5mZWF0dXJlKTtcbiAgICB9XG4gIH0gZWxzZSBpZiAoZm9ybWF0ICYmIGZvcm1hdC5tZXNoKSB7XG4gICAgaWYgKChvYmogPSB0Lm9iamVjdHNbZm9ybWF0Lm1lc2hdKSkge1xuICAgICAgcmV0dXJuIFt0b3BvanNvbi5tZXNoKHQsIHQub2JqZWN0c1tmb3JtYXQubWVzaF0pXTtcbiAgICB9IGVsc2Uge1xuICAgICAgdGhyb3cgRXJyb3IoJ0ludmFsaWQgVG9wb0pTT04gb2JqZWN0OiAnICsgZm9ybWF0Lm1lc2gpO1xuICAgIH1cbiAgfSBlbHNlIHtcbiAgICB0aHJvdyBFcnJvcignTWlzc2luZyBUb3BvSlNPTiBmZWF0dXJlIG9yIG1lc2ggcGFyYW1ldGVyLicpO1xuICB9XG59O1xuXG5yZWFkZXIudG9wb2pzb24gPSAodHlwZW9mIHdpbmRvdyAhPT0gXCJ1bmRlZmluZWRcIiA/IHdpbmRvdy50b3BvanNvbiA6IHR5cGVvZiBnbG9iYWwgIT09IFwidW5kZWZpbmVkXCIgPyBnbG9iYWwudG9wb2pzb24gOiBudWxsKTtcbm1vZHVsZS5leHBvcnRzID0gcmVhZGVyOyJdfQ==
},{"./json":10}],12:[function(require,module,exports){
var json = require('./json');
module.exports = function(data, format) {
data = json(data, format);
return toTable(data, (format && format.children));
};
function toTable(root, childrenField) {
childrenField = childrenField || 'children';
var table = [];
function visit(node) {
table.push(node);
var children = node[childrenField];
if (children) {
for (var i=0; i<children.length; ++i) {
visit(children[i], node);
}
}
}
visit(root, null);
return (table.root = root, table);
}
},{"./json":10}],13:[function(require,module,exports){
// Matches absolute URLs with optional protocol
// https://... file://... //...
var protocol_re = /^([A-Za-z]+:)?\/\//;
// Special treatment in node.js for the file: protocol
var fileProtocol = 'file://';
// Validate and cleanup URL to ensure that it is allowed to be accessed
// Returns cleaned up URL, or false if access is not allowed
function sanitizeUrl(opt) {
var url = opt.url;
if (!url && opt.file) { return fileProtocol + opt.file; }
// In case this is a relative url (has no host), prepend opt.baseURL
if (opt.baseURL && !protocol_re.test(url)) {
if (!startsWith(url, '/') && opt.baseURL[opt.baseURL.length-1] !== '/') {
url = '/' + url; // Ensure that there is a slash between the baseURL (e.g. hostname) and url
}
url = opt.baseURL + url;
}
// relative protocol, starts with '//'
if (!load.useXHR && startsWith(url, '//')) {
url = (opt.defaultProtocol || 'http') + ':' + url;
}
// If opt.domainWhiteList is set, only allows url, whose hostname
// * Is the same as the origin (window.location.hostname)
// * Equals one of the values in the whitelist
// * Is a proper subdomain of one of the values in the whitelist
if (opt.domainWhiteList) {
var domain, origin;
if (load.useXHR) {
var a = document.createElement('a');
a.href = url;
// From http://stackoverflow.com/questions/736513/how-do-i-parse-a-url-into-hostname-and-path-in-javascript
// IE doesn't populate all link properties when setting .href with a relative URL,
// however .href will return an absolute URL which then can be used on itself
// to populate these additional fields.
if (a.host === '') {
a.href = a.href;
}
domain = a.hostname.toLowerCase();
origin = window.location.hostname;
} else {
// relative protocol is broken: https://github.com/defunctzombie/node-url/issues/5
var parts = require('url').parse(url);
domain = parts.hostname;
origin = null;
}
if (origin !== domain) {
var whiteListed = opt.domainWhiteList.some(function(d) {
var idx = domain.length - d.length;
return d === domain ||
(idx > 1 && domain[idx-1] === '.' && domain.lastIndexOf(d) === idx);
});
if (!whiteListed) {
throw 'URL is not whitelisted: ' + url;
}
}
}
return url;
}
function load(opt, callback) {
var error = callback || function(e) { throw e; }, url;
try {
url = load.sanitizeUrl(opt); // enable override
} catch (err) {
error(err);
return;
}
if (!url) {
error('Invalid URL: ' + opt.url);
} else if (load.useXHR) {
// on client, use xhr
return xhr(url, callback);
} else if (startsWith(url, fileProtocol)) {
// on server, if url starts with 'file://', strip it and load from file
return file(url.slice(fileProtocol.length), callback);
} else if (url.indexOf('://') < 0) { // TODO better protocol check?
// on server, if no protocol assume file
return file(url, callback);
} else {
// for regular URLs on server
return http(url, callback);
}
}
function xhrHasResponse(request) {
var type = request.responseType;
return type && type !== 'text' ?
request.response : // null on error
request.responseText; // '' on error
}
function xhr(url, callback) {
var async = !!callback;
var request = new XMLHttpRequest();
// If IE does not support CORS, use XDomainRequest (copied from d3.xhr)
if (this.XDomainRequest &&
!('withCredentials' in request) &&
/^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest();
function respond() {
var status = request.status;
if (!status && xhrHasResponse(request) || status >= 200 && status < 300 || status === 304) {
callback(null, request.responseText);
} else {
callback(request, null);
}
}
if (async) {
if ('onload' in request) {
request.onload = request.onerror = respond;
} else {
request.onreadystatechange = function() {
if (request.readyState > 3) respond();
};
}
}
request.open('GET', url, async);
request.send();
if (!async && xhrHasResponse(request)) {
return request.responseText;
}
}
function file(filename, callback) {
var fs = require('fs');
if (!callback) {
return fs.readFileSync(filename, 'utf8');
}
fs.readFile(filename, callback);
}
function http(url, callback) {
if (!callback) {
return require('sync-request')('GET', url).getBody();
}
require('request')(url, function(error, response, body) {
if (!error && response.statusCode === 200) {
callback(null, body);
} else {
error = error ||
'Load failed with response code ' + response.statusCode + '.';
callback(error, null);
}
});
}
function startsWith(string, searchString) {
return string == null ? false : string.lastIndexOf(searchString, 0) === 0;
}
load.sanitizeUrl = sanitizeUrl;
load.useXHR = (typeof XMLHttpRequest !== 'undefined');
module.exports = load;
},{"fs":2,"request":2,"sync-request":2,"url":2}],14:[function(require,module,exports){
var util = require('../util');
var type = require('./type');
var formats = require('./formats');
function read(data, format) {
var type = (format && format.type) || 'json';
data = formats[type](data, format);
if (format && format.parse) parse(data, format.parse);
return data;
}
function parse(data, types) {
var cols, parsers, d, i, j, clen, len = data.length;
types = (types==='auto') ? type.inferAll(data) : util.duplicate(types);
cols = util.keys(types);
parsers = cols.map(function(c) { return type.parsers[types[c]]; });
for (i=0, clen=cols.length; i<len; ++i) {
d = data[i];
for (j=0; j<clen; ++j) {
d[cols[j]] = parsers[j](d[cols[j]]);
}
}
type.annotation(data, types);
}
read.formats = formats;
module.exports = read;
},{"../util":20,"./formats":9,"./type":16}],15:[function(require,module,exports){
var util = require('../util');
var load = require('./load');
var read = require('./read');
module.exports = util
.keys(read.formats)
.reduce(function(out, type) {
out[type] = function(opt, format, callback) {
// process arguments
if (util.isString(opt)) { opt = {url: opt}; }
if (arguments.length === 2 && util.isFunction(format)) {
callback = format;
format = undefined;
}
// set up read format
format = util.extend({parse: 'auto'}, format);
format.type = type;
// load data
var data = load(opt, callback ? function(error, data) {
if (error) { callback(error, null); return; }
try {
// data loaded, now parse it (async)
data = read(data, format);
callback(null, data);
} catch (e) {
callback(e, null);
}
} : undefined);
// data loaded, now parse it (sync)
if (!callback) return read(data, format);
};
return out;
}, {});
},{"../util":20,"./load":13,"./read":14}],16:[function(require,module,exports){
var util = require('../util');
var TYPES = '__types__';
var PARSERS = {
boolean: util.boolean,
integer: util.number,
number: util.number,
date: util.date,
string: function(x) { return x==='' ? null : x; }
};
var TESTS = {
boolean: function(x) { return x==='true' || x==='false' || util.isBoolean(x); },
integer: function(x) { return TESTS.number(x) && (x=+x) === ~~x; },
number: function(x) { return !isNaN(+x) && !util.isDate(x); },
date: function(x) { return !isNaN(Date.parse(x)); }
};
function annotation(data, types) {
if (!types) return data && data[TYPES] || null;
data[TYPES] = types;
}
function type(values, f) {
f = util.$(f);
var v, i, n;
// if data array has type annotations, use them
if (values[TYPES]) {
v = f(values[TYPES]);
if (util.isString(v)) return v;
}
for (i=0, n=values.length; !util.isValid(v) && i<n; ++i) {
v = f ? f(values[i]) : values[i];
}
return util.isDate(v) ? 'date' :
util.isNumber(v) ? 'number' :
util.isBoolean(v) ? 'boolean' :
util.isString(v) ? 'string' : null;
}
function typeAll(data, fields) {
if (!data.length) return;
fields = fields || util.keys(data[0]);
return fields.reduce(function(types, f) {
return (types[f] = type(data, f), types);
}, {});
}
function infer(values, f) {
f = util.$(f);
var i, j, v;
// types to test for, in precedence order
var types = ['boolean', 'integer', 'number', 'date'];
for (i=0; i<values.length; ++i) {
// get next value to test
v = f ? f(values[i]) : values[i];
// test value against remaining types
for (j=0; j<types.length; ++j) {
if (util.isValid(v) && !TESTS[types[j]](v)) {
types.splice(j, 1);
j -= 1;
}
}
// if no types left, return 'string'
if (types.length === 0) return 'string';
}
return types[0];
}
function inferAll(data, fields) {
fields = fields || util.keys(data[0]);
return fields.reduce(function(types, f) {
types[f] = infer(data, f);
return types;
}, {});
}
type.annotation = annotation;
type.all = typeAll;
type.infer = infer;
type.inferAll = inferAll;
type.parsers = PARSERS;
module.exports = type;
},{"../util":20}],17:[function(require,module,exports){
var util = require('./util');
var type = require('./import/type');
var gen = require('./generate');
var stats = {};
// Collect unique values.
// Output: an array of unique values, in first-observed order
stats.unique = function(values, f, results) {
f = util.$(f);
results = results || [];
var u = {}, v, i, n;
for (i=0, n=values.length; i<n; ++i) {
v = f ? f(values[i]) : values[i];
if (v in u) continue;
u[v] = 1;
results.push(v);
}
return results;
};
// Return the length of the input array.
stats.count = function(values) {
return values && values.length || 0;
};
// Count the number of non-null, non-undefined, non-NaN values.
stats.count.valid = function(values, f) {
f = util.$(f);
var v, i, n, valid = 0;
for (i=0, n=values.length; i<n; ++i) {
v = f ? f(values[i]) : values[i];
if (util.isValid(v)) valid += 1;
}
return valid;
};
// Count the number of null or undefined values.
stats.count.missing = function(values, f) {
f = util.$(f);
var v, i, n, count = 0;
for (i=0, n=values.length; i<n; ++i) {
v = f ? f(values[i]) : values[i];
if (v == null) count += 1;
}
return count;
};
// Count the number of distinct values.
// Null, undefined and NaN are each considered distinct values.
stats.count.distinct = function(values, f) {
f = util.$(f);
var u = {}, v, i, n, count = 0;
for (i=0, n=values.length; i<n; ++i) {
v = f ? f(values[i]) : values[i];
if (v in u) continue;
u[v] = 1;
count += 1;
}
return count;
};
// Construct a map from distinct values to occurrence counts.
stats.count.map = function(values, f) {
f = util.$(f);
var map = {}, v, i, n;
for (i=0, n=values.length; i<n; ++i) {
v = f ? f(values[i]) : values[i];
map[v] = (v in map) ? map[v] + 1 : 1;
}
return map;
};
// Compute the median of an array of numbers.
stats.median = function(values, f) {
if (f) values = values.map(util.$(f));
values = values.filter(util.isValid).sort(util.cmp);
return stats.quantile(values, 0.5);
};
// Computes the quartile boundaries of an array of numbers.
stats.quartile = function(values, f) {
if (f) values = values.map(util.$(f));
values = values.filter(util.isValid).sort(util.cmp);
var q = stats.quantile;
return [q(values, 0.25), q(values, 0.50), q(values, 0.75)];
};
// Compute the quantile of a sorted array of numbers.
// Adapted from the D3.js implementation.
stats.quantile = function(values, f, p) {
if (p === undefined) { p = f; f = util.identity; }
f = util.$(f);
var H = (values.length - 1) * p + 1,
h = Math.floor(H),
v = +f(values[h - 1]),
e = H - h;
return e ? v + e * (f(values[h]) - v) : v;
};
// Compute the sum of an array of numbers.
stats.sum = function(values, f) {
f = util.$(f);
for (var sum=0, i=0, n=values.length, v; i<n; ++i) {
v = f ? f(values[i]) : values[i];
if (util.isValid(v)) sum += v;
}
return sum;
};
// Compute the mean (average) of an array of numbers.
stats.mean = function(values, f) {
f = util.$(f);
var mean = 0, delta, i, n, c, v;
for (i=0, c=0, n=values.length; i<n; ++i) {
v = f ? f(values[i]) : values[i];
if (util.isValid(v)) {
delta = v - mean;
mean = mean + delta / (++c);
}
}
return mean;
};
// Compute the sample variance of an array of numbers.
stats.variance = function(values, f) {
f = util.$(f);
if (!util.isArray(values) || values.length < 2) return 0;
var mean = 0, M2 = 0, delta, i, c, v;
for (i=0, c=0; i<values.length; ++i) {
v = f ? f(values[i]) : values[i];
if (util.isValid(v)) {
delta = v - mean;
mean = mean + delta / (++c);
M2 = M2 + delta * (v - mean);
}
}
M2 = M2 / (c - 1);
return M2;
};
// Compute the sample standard deviation of an array of numbers.
stats.stdev = function(values, f) {
return Math.sqrt(stats.variance(values, f));
};
// Compute the Pearson mode skewness ((median-mean)/stdev) of an array of numbers.
stats.modeskew = function(values, f) {
var avg = stats.mean(values, f),
med = stats.median(values, f),
std = stats.stdev(values, f);
return std === 0 ? 0 : (avg - med) / std;
};
// Find the minimum value in an array.
stats.min = function(values, f) {
return stats.extent(values, f)[0];
};
// Find the maximum value in an array.
stats.max = function(values, f) {
return stats.extent(values, f)[1];
};
// Find the minimum and maximum of an array of values.
stats.extent = function(values, f) {
f = util.$(f);
var a, b, v, i, n = values.length;
for (i=0; i<n; ++i) {
v = f ? f(values[i]) : values[i];
if (util.isValid(v)) { a = b = v; break; }
}
for (; i<n; ++i) {
v = f ? f(values[i]) : values[i];
if (util.isValid(v)) {
if (v < a) a = v;
if (v > b) b = v;
}
}
return [a, b];
};
// Find the integer indices of the minimum and maximum values.
stats.extent.index = function(values, f) {
f = util.$(f);
var x = -1, y = -1, a, b, v, i, n = values.length;
for (i=0; i<n; ++i) {
v = f ? f(values[i]) : values[i];
if (util.isValid(v)) { a = b = v; x = y = i; break; }
}
for (; i<n; ++i) {
v = f ? f(values[i]) : values[i];
if (util.isValid(v)) {
if (v < a) { a = v; x = i; }
if (v > b) { b = v; y = i; }
}
}
return [x, y];
};
// Compute the dot product of two arrays of numbers.
stats.dot = function(values, a, b) {
var sum = 0, i, v;
if (!b) {
if (values.length !== a.length) {
throw Error('Array lengths must match.');
}
for (i=0; i<values.length; ++i) {
v = values[i] * a[i];
if (v === v) sum += v;
}
} else {
a = util.$(a);
b = util.$(b);
for (i=0; i<values.length; ++i) {
v = a(values[i]) * b(values[i]);
if (v === v) sum += v;
}
}
return sum;
};
// Compute ascending rank scores for an array of values.
// Ties are assigned their collective mean rank.
stats.rank = function(values, f) {
f = util.$(f) || util.identity;
var a = values.map(function(v, i) {
return {idx: i, val: f(v)};
})
.sort(util.comparator('val'));
var n = values.length,
r = Array(n),
tie = -1, p = {}, i, v, mu;
for (i=0; i<n; ++i) {
v = a[i].val;
if (tie < 0 && p === v) {
tie = i - 1;
} else if (tie > -1 && p !== v) {
mu = 1 + (i-1 + tie) / 2;
for (; tie<i; ++tie) r[a[tie].idx] = mu;
tie = -1;
}
r[a[i].idx] = i + 1;
p = v;
}
if (tie > -1) {
mu = 1 + (n-1 + tie) / 2;
for (; tie<n; ++tie) r[a[tie].idx] = mu;
}
return r;
};
// Compute the sample Pearson product-moment correlation of two arrays of numbers.
stats.cor = function(values, a, b) {
var fn = b;
b = fn ? values.map(util.$(b)) : a;
a = fn ? values.map(util.$(a)) : values;
var dot = stats.dot(a, b),
mua = stats.mean(a),
mub = stats.mean(b),
sda = stats.stdev(a),
sdb = stats.stdev(b),
n = values.length;
return (dot - n*mua*mub) / ((n-1) * sda * sdb);
};
// Compute the Spearman rank correlation of two arrays of values.
stats.cor.rank = function(values, a, b) {
var ra = b ? stats.rank(values, util.$(a)) : stats.rank(values),
rb = b ? stats.rank(values, util.$(b)) : stats.rank(a),
n = values.length, i, s, d;
for (i=0, s=0; i<n; ++i) {
d = ra[i] - rb[i];
s += d * d;
}
return 1 - 6*s / (n * (n*n-1));
};
// Compute the distance correlation of two arrays of numbers.
// http://en.wikipedia.org/wiki/Distance_correlation
stats.cor.dist = function(values, a, b) {
var X = b ? values.map(util.$(a)) : values,
Y = b ? values.map(util.$(b)) : a;
var A = stats.dist.mat(X),
B = stats.dist.mat(Y),
n = A.length,
i, aa, bb, ab;
for (i=0, aa=0, bb=0, ab=0; i<n; ++i) {
aa += A[i]*A[i];
bb += B[i]*B[i];
ab += A[i]*B[i];
}
return Math.sqrt(ab / Math.sqrt(aa*bb));
};
// Compute the vector distance between two arrays of numbers.
// Default is Euclidean (exp=2) distance, configurable via exp argument.
stats.dist = function(values, a, b, exp) {
var f = util.isFunction(b) || util.isString(b),
X = values,
Y = f ? values : a,
e = f ? exp : b,
L2 = e === 2 || e == null,
n = values.length, s = 0, d, i;
if (f) {
a = util.$(a);
b = util.$(b);
}
for (i=0; i<n; ++i) {
d = f ? (a(X[i])-b(Y[i])) : (X[i]-Y[i]);
s += L2 ? d*d : Math.pow(Math.abs(d), e);
}
return L2 ? Math.sqrt(s) : Math.pow(s, 1/e);
};
// Construct a mean-centered distance matrix for an array of numbers.
stats.dist.mat = function(X) {
var n = X.length,
m = n*n,
A = Array(m),
R = gen.zeros(n),
M = 0, v, i, j;
for (i=0; i<n; ++i) {
A[i*n+i] = 0;
for (j=i+1; j<n; ++j) {
A[i*n+j] = (v = Math.abs(X[i] - X[j]));
A[j*n+i] = v;
R[i] += v;
R[j] += v;
}
}
for (i=0; i<n; ++i) {
M += R[i];
R[i] /= n;
}
M /= m;
for (i=0; i<n; ++i) {
for (j=i; j<n; ++j) {
A[i*n+j] += M - R[i] - R[j];
A[j*n+i] = A[i*n+j];
}
}
return A;
};
// Compute the Shannon entropy (log base 2) of an array of counts.
stats.entropy = function(counts, f) {
f = util.$(f);
var i, p, s = 0, H = 0, n = counts.length;
for (i=0; i<n; ++i) {
s += (f ? f(counts[i]) : counts[i]);
}
if (s === 0) return 0;
for (i=0; i<n; ++i) {
p = (f ? f(counts[i]) : counts[i]) / s;
if (p) H += p * Math.log(p);
}
return -H / Math.LN2;
};
// Compute the mutual information between two discrete variables.
// Returns an array of the form [MI, MI_distance]
// MI_distance is defined as 1 - I(a,b) / H(a,b).
// http://en.wikipedia.org/wiki/Mutual_information
stats.mutual = function(values, a, b, counts) {
var x = counts ? values.map(util.$(a)) : values,
y = counts ? values.map(util.$(b)) : a,
z = counts ? values.map(util.$(counts)) : b;
var px = {},
py = {},
n = z.length,
s = 0, I = 0, H = 0, p, t, i;
for (i=0; i<n; ++i) {
px[x[i]] = 0;
py[y[i]] = 0;
}
for (i=0; i<n; ++i) {
px[x[i]] += z[i];
py[y[i]] += z[i];
s += z[i];
}
t = 1 / (s * Math.LN2);
for (i=0; i<n; ++i) {
if (z[i] === 0) continue;
p = (s * z[i]) / (px[x[i]] * py[y[i]]);
I += z[i] * t * Math.log(p);
H += z[i] * t * Math.log(z[i]/s);
}
return [I, 1 + I/H];
};
// Compute the mutual information between two discrete variables.
stats.mutual.info = function(values, a, b, counts) {
return stats.mutual(values, a, b, counts)[0];
};
// Compute the mutual information distance between two discrete variables.
// MI_distance is defined as 1 - I(a,b) / H(a,b).
stats.mutual.dist = function(values, a, b, counts) {
return stats.mutual(values, a, b, counts)[1];
};
// Compute a profile of summary statistics for a variable.
stats.profile = function(values, f) {
var mean = 0,
valid = 0,
missing = 0,
distinct = 0,
min = null,
max = null,
M2 = 0,
vals = [],
u = {}, delta, sd, i, v, x;
// compute summary stats
for (i=0; i<values.length; ++i) {
v = f ? f(values[i]) : values[i];
// update unique values
u[v] = (v in u) ? u[v] + 1 : (distinct += 1, 1);
if (v == null) {
++missing;
} else if (util.isValid(v)) {
// update stats
x = (typeof v === 'string') ? v.length : v;
if (min===null || x < min) min = x;
if (max===null || x > max) max = x;
delta = x - mean;
mean = mean + delta / (++valid);
M2 = M2 + delta * (x - mean);
vals.push(x);
}
}
M2 = M2 / (valid - 1);
sd = Math.sqrt(M2);
// sort values for median and iqr
vals.sort(util.cmp);
return {
type: type(values, f),
unique: u,
count: values.length,
valid: valid,
missing: missing,
distinct: distinct,
min: min,
max: max,
mean: mean,
stdev: sd,
median: (v = stats.quantile(vals, 0.5)),
q1: stats.quantile(vals, 0.25),
q3: stats.quantile(vals, 0.75),
modeskew: sd === 0 ? 0 : (mean - v) / sd
};
};
// Compute profiles for all variables in a data set.
stats.summary = function(data, fields) {
fields = fields || util.keys(data[0]);
var s = fields.map(function(f) {
var p = stats.profile(data, util.$(f));
return (p.field = f, p);
});
return (s.__summary__ = true, s);
};
module.exports = stats;
},{"./generate":7,"./import/type":16,"./util":20}],18:[function(require,module,exports){
(function (global){
var util = require('./util');
var d3 = (typeof window !== "undefined" ? window.d3 : typeof global !== "undefined" ? global.d3 : null);
var context = {
formats: [],
format_map: {},
truncate: util.truncate,
pad: util.pad
};
function template(text) {
var src = source(text, 'd');
src = 'var __t; return ' + src + ';';
/* jshint evil: true */
return (new Function('d', src)).bind(context);
}
template.source = source;
template.context = context;
module.exports = template;
// Clear cache of format objects.
// This can *break* prior template functions, so invoke with care!
template.clearFormatCache = function() {
context.formats = [];
context.format_map = {};
};
// Generate property access code for use within template source.
// object: the name of the object (variable) containing template data
// property: the property access string, verbatim from template tag
template.property = function(object, property) {
var src = util.field(property).map(util.str).join('][');
return object + '[' + src + ']';
};
// Generate source code for a template function.
// text: the template text
// variable: the name of the data object variable ('obj' by default)
// properties: optional hash for collecting all accessed properties
function source(text, variable, properties) {
variable = variable || 'obj';
var index = 0;
var src = '\'';
var regex = template_re;
// Compile the template source, escaping string literals appropriately.
text.replace(regex, function(match, interpolate, offset) {
src += text
.slice(index, offset)
.replace(template_escaper, template_escapeChar);
index = offset + match.length;
if (interpolate) {
src += '\'\n+((__t=(' +
template_var(interpolate, variable, properties) +
'))==null?\'\':__t)+\n\'';
}
// Adobe VMs need the match returned to produce the correct offest.
return match;
});
return src + '\'';
}
function template_var(text, variable, properties) {
var filters = text.split('|');
var prop = filters.shift().trim();
var stringCast = true;
function strcall(fn) {
fn = fn || '';
if (stringCast) {
stringCast = false;
src = 'String(' + src + ')' + fn;
} else {
src += fn;
}
return src;
}
function date() {
return '(typeof ' + src + '==="number"?new Date('+src+'):'+src+')';
}
if (properties) properties[prop] = 1;
var src = template.property(variable, prop);
for (var i=0; i<filters.length; ++i) {
var f = filters[i], args = null, pidx, a, b;
if ((pidx=f.indexOf(':')) > 0) {
f = f.slice(0, pidx);
args = filters[i].slice(pidx+1).split(',')
.map(function(s) { return s.trim(); });
}
f = f.trim();
switch (f) {
case 'length':
strcall('.length');
break;
case 'lower':
strcall('.toLowerCase()');
break;
case 'upper':
strcall('.toUpperCase()');
break;
case 'lower-locale':
strcall('.toLocaleLowerCase()');
break;
case 'upper-locale':
strcall('.toLocaleUpperCase()');
break;
case 'trim':
strcall('.trim()');
break;
case 'left':
a = util.number(args[0]);
strcall('.slice(0,' + a + ')');
break;
case 'right':
a = util.number(args[0]);
strcall('.slice(-' + a +')');
break;
case 'mid':
a = util.number(args[0]);
b = a + util.number(args[1]);
strcall('.slice(+'+a+','+b+')');
break;
case 'slice':
a = util.number(args[0]);
strcall('.slice('+ a +
(args.length > 1 ? ',' + util.number(args[1]) : '') +
')');
break;
case 'truncate':
a = util.number(args[0]);
b = args[1];
b = (b!=='left' && b!=='middle' && b!=='center') ? 'right' : b;
src = 'this.truncate(' + strcall() + ',' + a + ',\'' + b + '\')';
break;
case 'pad':
a = util.number(args[0]);
b = args[1];
b = (b!=='left' && b!=='middle' && b!=='center') ? 'right' : b;
src = 'this.pad(' + strcall() + ',' + a + ',\'' + b + '\')';
break;
case 'number':
a = template_format(args[0], d3.format);
stringCast = false;
src = 'this.formats['+a+']('+src+')';
break;
case 'time':
a = template_format(args[0], d3.time.format);
stringCast = false;
src = 'this.formats['+a+']('+date()+')';
break;
default:
throw Error('Unrecognized template filter: ' + f);
}
}
return src;
}
var template_re = /\{\{(.+?)\}\}|$/g;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var template_escapes = {
'\'': '\'',
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var template_escaper = /\\|'|\r|\n|\u2028|\u2029/g;
function template_escapeChar(match) {
return '\\' + template_escapes[match];
}
function template_format(pattern, fmt) {
if ((pattern[0] === '\'' && pattern[pattern.length-1] === '\'') ||
(pattern[0] === '"' && pattern[pattern.length-1] === '"')) {
pattern = pattern.slice(1, -1);
} else {
throw Error('Format pattern must be quoted: ' + pattern);
}
if (!context.format_map[pattern]) {
var f = fmt(pattern);
var i = context.formats.length;
context.formats.push(f);
context.format_map[pattern] = i;
}
return context.format_map[pattern];
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9kYXRhbGliL3NyYy90ZW1wbGF0ZS5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EiLCJmaWxlIjoiZ2VuZXJhdGVkLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXNDb250ZW50IjpbInZhciB1dGlsID0gcmVxdWlyZSgnLi91dGlsJyk7XG52YXIgZDMgPSAodHlwZW9mIHdpbmRvdyAhPT0gXCJ1bmRlZmluZWRcIiA/IHdpbmRvdy5kMyA6IHR5cGVvZiBnbG9iYWwgIT09IFwidW5kZWZpbmVkXCIgPyBnbG9iYWwuZDMgOiBudWxsKTtcblxudmFyIGNvbnRleHQgPSB7XG4gIGZvcm1hdHM6ICAgIFtdLFxuICBmb3JtYXRfbWFwOiB7fSxcbiAgdHJ1bmNhdGU6ICAgdXRpbC50cnVuY2F0ZSxcbiAgcGFkOiAgICAgICAgdXRpbC5wYWRcbn07XG5cbmZ1bmN0aW9uIHRlbXBsYXRlKHRleHQpIHtcbiAgdmFyIHNyYyA9IHNvdXJjZSh0ZXh0LCAnZCcpO1xuICBzcmMgPSAndmFyIF9fdDsgcmV0dXJuICcgKyBzcmMgKyAnOyc7XG5cbiAgLyoganNoaW50IGV2aWw6IHRydWUgKi9cbiAgcmV0dXJuIChuZXcgRnVuY3Rpb24oJ2QnLCBzcmMpKS5iaW5kKGNvbnRleHQpO1xufVxuXG50ZW1wbGF0ZS5zb3VyY2UgPSBzb3VyY2U7XG50ZW1wbGF0ZS5jb250ZXh0ID0gY29udGV4dDtcbm1vZHVsZS5leHBvcnRzID0gdGVtcGxhdGU7XG5cbi8vIENsZWFyIGNhY2hlIG9mIGZvcm1hdCBvYmplY3RzLlxuLy8gVGhpcyBjYW4gKmJyZWFrKiBwcmlvciB0ZW1wbGF0ZSBmdW5jdGlvbnMsIHNvIGludm9rZSB3aXRoIGNhcmUhXG50ZW1wbGF0ZS5jbGVhckZvcm1hdENhY2hlID0gZnVuY3Rpb24oKSB7XG4gIGNvbnRleHQuZm9ybWF0cyA9IFtdO1xuICBjb250ZXh0LmZvcm1hdF9tYXAgPSB7fTtcbn07XG5cbi8vIEdlbmVyYXRlIHByb3BlcnR5IGFjY2VzcyBjb2RlIGZvciB1c2Ugd2l0aGluIHRlbXBsYXRlIHNvdXJjZS5cbi8vIG9iamVjdDogdGhlIG5hbWUgb2YgdGhlIG9iamVjdCAodmFyaWFibGUpIGNvbnRhaW5pbmcgdGVtcGxhdGUgZGF0YVxuLy8gcHJvcGVydHk6IHRoZSBwcm9wZXJ0eSBhY2Nlc3Mgc3RyaW5nLCB2ZXJiYXRpbSBmcm9tIHRlbXBsYXRlIHRhZ1xudGVtcGxhdGUucHJvcGVydHkgPSBmdW5jdGlvbihvYmplY3QsIHByb3BlcnR5KSB7XG4gIHZhciBzcmMgPSB1dGlsLmZpZWxkKHByb3BlcnR5KS5tYXAodXRpbC5zdHIpLmpvaW4oJ11bJyk7XG4gIHJldHVybiBvYmplY3QgKyAnWycgKyBzcmMgKyAnXSc7XG59O1xuXG4vLyBHZW5lcmF0ZSBzb3VyY2UgY29kZSBmb3IgYSB0ZW1wbGF0ZSBmdW5jdGlvbi5cbi8vIHRleHQ6IHRoZSB0ZW1wbGF0ZSB0ZXh0XG4vLyB2YXJpYWJsZTogdGhlIG5hbWUgb2YgdGhlIGRhdGEgb2JqZWN0IHZhcmlhYmxlICgnb2JqJyBieSBkZWZhdWx0KVxuLy8gcHJvcGVydGllczogb3B0aW9uYWwgaGFzaCBmb3IgY29sbGVjdGluZyBhbGwgYWNjZXNzZWQgcHJvcGVydGllc1xuZnVuY3Rpb24gc291cmNlKHRleHQsIHZhcmlhYmxlLCBwcm9wZXJ0aWVzKSB7XG4gIHZhcmlhYmxlID0gdmFyaWFibGUgfHwgJ29iaic7XG4gIHZhciBpbmRleCA9IDA7XG4gIHZhciBzcmMgPSAnXFwnJztcbiAgdmFyIHJlZ2V4ID0gdGVtcGxhdGVfcmU7XG5cbiAgLy8gQ29tcGlsZSB0aGUgdGVtcGxhdGUgc291cmNlLCBlc2NhcGluZyBzdHJpbmcgbGl0ZXJhbHMgYXBwcm9wcmlhdGVseS5cbiAgdGV4dC5yZXBsYWNlKHJlZ2V4LCBmdW5jdGlvbihtYXRjaCwgaW50ZXJwb2xhdGUsIG9mZnNldCkge1xuICAgIHNyYyArPSB0ZXh0XG4gICAgICAuc2xpY2UoaW5kZXgsIG9mZnNldClcbiAgICAgIC5yZXBsYWNlKHRlbXBsYXRlX2VzY2FwZXIsIHRlbXBsYXRlX2VzY2FwZUNoYXIpO1xuICAgIGluZGV4ID0gb2Zmc2V0ICsgbWF0Y2gubGVuZ3RoO1xuXG4gICAgaWYgKGludGVycG9sYXRlKSB7XG4gICAgICBzcmMgKz0gJ1xcJ1xcbisoKF9fdD0oJyArXG4gICAgICAgIHRlbXBsYXRlX3ZhcihpbnRlcnBvbGF0ZSwgdmFyaWFibGUsIHByb3BlcnRpZXMpICtcbiAgICAgICAgJykpPT1udWxsP1xcJ1xcJzpfX3QpK1xcblxcJyc7XG4gICAgfVxuXG4gICAgLy8gQWRvYmUgVk1zIG5lZWQgdGhlIG1hdGNoIHJldHVybmVkIHRvIHByb2R1Y2UgdGhlIGNvcnJlY3Qgb2ZmZXN0LlxuICAgIHJldHVybiBtYXRjaDtcbiAgfSk7XG4gIHJldHVybiBzcmMgKyAnXFwnJztcbn1cblxuZnVuY3Rpb24gdGVtcGxhdGVfdmFyKHRleHQsIHZhcmlhYmxlLCBwcm9wZXJ0aWVzKSB7XG4gIHZhciBmaWx0ZXJzID0gdGV4dC5zcGxpdCgnfCcpO1xuICB2YXIgcHJvcCA9IGZpbHRlcnMuc2hpZnQoKS50cmltKCk7XG4gIHZhciBzdHJpbmdDYXN0ID0gdHJ1ZTtcblxuICBmdW5jdGlvbiBzdHJjYWxsKGZuKSB7XG4gICAgZm4gPSBmbiB8fCAnJztcbiAgICBpZiAoc3RyaW5nQ2FzdCkge1xuICAgICAgc3RyaW5nQ2FzdCA9IGZhbHNlO1xuICAgICAgc3JjID0gJ1N0cmluZygnICsgc3JjICsgJyknICsgZm47XG4gICAgfSBlbHNlIHtcbiAgICAgIHNyYyArPSBmbjtcbiAgICB9XG4gICAgcmV0dXJuIHNyYztcbiAgfVxuXG4gIGZ1bmN0aW9uIGRhdGUoKSB7XG4gICAgcmV0dXJuICcodHlwZW9mICcgKyBzcmMgKyAnPT09XCJudW1iZXJcIj9uZXcgRGF0ZSgnK3NyYysnKTonK3NyYysnKSc7XG4gIH1cblxuICBpZiAocHJvcGVydGllcykgcHJvcGVydGllc1twcm9wXSA9IDE7XG4gIHZhciBzcmMgPSB0ZW1wbGF0ZS5wcm9wZXJ0eSh2YXJpYWJsZSwgcHJvcCk7XG5cbiAgZm9yICh2YXIgaT0wOyBpPGZpbHRlcnMubGVuZ3RoOyArK2kpIHtcbiAgICB2YXIgZiA9IGZpbHRlcnNbaV0sIGFyZ3MgPSBudWxsLCBwaWR4LCBhLCBiO1xuXG4gICAgaWYgKChwaWR4PWYuaW5kZXhPZignOicpKSA+IDApIHtcbiAgICAgIGYgPSBmLnNsaWNlKDAsIHBpZHgpO1xuICAgICAgYXJncyA9IGZpbHRlcnNbaV0uc2xpY2UocGlkeCsxKS5zcGxpdCgnLCcpXG4gICAgICAgIC5tYXAoZnVuY3Rpb24ocykgeyByZXR1cm4gcy50cmltKCk7IH0pO1xuICAgIH1cbiAgICBmID0gZi50cmltKCk7XG5cbiAgICBzd2l0Y2ggKGYpIHtcbiAgICAgIGNhc2UgJ2xlbmd0aCc6XG4gICAgICAgIHN0cmNhbGwoJy5sZW5ndGgnKTtcbiAgICAgICAgYnJlYWs7XG4gICAgICBjYXNlICdsb3dlcic6XG4gICAgICAgIHN0cmNhbGwoJy50b0xvd2VyQ2FzZSgpJyk7XG4gICAgICAgIGJyZWFrO1xuICAgICAgY2FzZSAndXBwZXInOlxuICAgICAgICBzdHJjYWxsKCcudG9VcHBlckNhc2UoKScpO1xuICAgICAgICBicmVhaztcbiAgICAgIGNhc2UgJ2xvd2VyLWxvY2FsZSc6XG4gICAgICAgIHN0cmNhbGwoJy50b0xvY2FsZUxvd2VyQ2FzZSgpJyk7XG4gICAgICAgIGJyZWFrO1xuICAgICAgY2FzZSAndXBwZXItbG9jYWxlJzpcbiAgICAgICAgc3RyY2FsbCgnLnRvTG9jYWxlVXBwZXJDYXNlKCknKTtcbiAgICAgICAgYnJlYWs7XG4gICAgICBjYXNlICd0cmltJzpcbiAgICAgICAgc3RyY2FsbCgnLnRyaW0oKScpO1xuICAgICAgICBicmVhaztcbiAgICAgIGNhc2UgJ2xlZnQnOlxuICAgICAgICBhID0gdXRpbC5udW1iZXIoYXJnc1swXSk7XG4gICAgICAgIHN0cmNhbGwoJy5zbGljZSgwLCcgKyBhICsgJyknKTtcbiAgICAgICAgYnJlYWs7XG4gICAgICBjYXNlICdyaWdodCc6XG4gICAgICAgIGEgPSB1dGlsLm51bWJlcihhcmdzWzBdKTtcbiAgICAgICAgc3RyY2FsbCgnLnNsaWNlKC0nICsgYSArJyknKTtcbiAgICAgICAgYnJlYWs7XG4gICAgICBjYXNlICdtaWQnOlxuICAgICAgICBhID0gdXRpbC5udW1iZXIoYXJnc1swXSk7XG4gICAgICAgIGIgPSBhICsgdXRpbC5udW1iZXIoYXJnc1sxXSk7XG4gICAgICAgIHN0cmNhbGwoJy5zbGljZSgrJythKycsJytiKycpJyk7XG4gICAgICAgIGJyZWFrO1xuICAgICAgY2FzZSAnc2xpY2UnOlxuICAgICAgICBhID0gdXRpbC5udW1iZXIoYXJnc1swXSk7XG4gICAgICAgIHN0cmNhbGwoJy5zbGljZSgnKyBhICtcbiAgICAgICAgICAoYXJncy5sZW5ndGggPiAxID8gJywnICsgdXRpbC5udW1iZXIoYXJnc1sxXSkgOiAnJykgK1xuICAgICAgICAgICcpJyk7XG4gICAgICAgIGJyZWFrO1xuICAgICAgY2FzZSAndHJ1bmNhdGUnOlxuICAgICAgICBhID0gdXRpbC5udW1iZXIoYXJnc1swXSk7XG4gICAgICAgIGIgPSBhcmdzWzFdO1xuICAgICAgICBiID0gKGIhPT0nbGVmdCcgJiYgYiE9PSdtaWRkbGUnICYmIGIhPT0nY2VudGVyJykgPyAncmlnaHQnIDogYjtcbiAgICAgICAgc3JjID0gJ3RoaXMudHJ1bmNhdGUoJyArIHN0cmNhbGwoKSArICcsJyArIGEgKyAnLFxcJycgKyBiICsgJ1xcJyknO1xuICAgICAgICBicmVhaztcbiAgICAgIGNhc2UgJ3BhZCc6XG4gICAgICAgIGEgPSB1dGlsLm51bWJlcihhcmdzWzBdKTtcbiAgICAgICAgYiA9IGFyZ3NbMV07XG4gICAgICAgIGIgPSAoYiE9PSdsZWZ0JyAmJiBiIT09J21pZGRsZScgJiYgYiE9PSdjZW50ZXInKSA/ICdyaWdodCcgOiBiO1xuICAgICAgICBzcmMgPSAndGhpcy5wYWQoJyArIHN0cmNhbGwoKSArICcsJyArIGEgKyAnLFxcJycgKyBiICsgJ1xcJyknO1xuICAgICAgICBicmVhaztcbiAgICAgIGNhc2UgJ251bWJlcic6XG4gICAgICAgIGEgPSB0ZW1wbGF0ZV9mb3JtYXQoYXJnc1swXSwgZDMuZm9ybWF0KTtcbiAgICAgICAgc3RyaW5nQ2FzdCA9IGZhbHNlO1xuICAgICAgICBzcmMgPSAndGhpcy5mb3JtYXRzWycrYSsnXSgnK3NyYysnKSc7XG4gICAgICAgIGJyZWFrO1xuICAgICAgY2FzZSAndGltZSc6XG4gICAgICAgIGEgPSB0ZW1wbGF0ZV9mb3JtYXQoYXJnc1swXSwgZDMudGltZS5mb3JtYXQpO1xuICAgICAgICBzdHJpbmdDYXN0ID0gZmFsc2U7XG4gICAgICAgIHNyYyA9ICd0aGlzLmZvcm1hdHNbJythKyddKCcrZGF0ZSgpKycpJztcbiAgICAgICAgYnJlYWs7XG4gICAgICBkZWZhdWx0OlxuICAgICAgICB0aHJvdyBFcnJvcignVW5yZWNvZ25pemVkIHRlbXBsYXRlIGZpbHRlcjogJyArIGYpO1xuICAgIH1cbiAgfVxuXG4gIHJldHVybiBzcmM7XG59XG5cbnZhciB0ZW1wbGF0ZV9yZSA9IC9cXHtcXHsoLis/KVxcfVxcfXwkL2c7XG5cbi8vIENlcnRhaW4gY2hhcmFjdGVycyBuZWVkIHRvIGJlIGVzY2FwZWQgc28gdGhhdCB0aGV5IGNhbiBiZSBwdXQgaW50byBhXG4vLyBzdHJpbmcgbGl0ZXJhbC5cbnZhciB0ZW1wbGF0ZV9lc2NhcGVzID0ge1xuICAnXFwnJzogICAgICdcXCcnLFxuICAnXFxcXCc6ICAgICAnXFxcXCcsXG4gICdcXHInOiAgICAgJ3InLFxuICAnXFxuJzogICAgICduJyxcbiAgJ1xcdTIwMjgnOiAndTIwMjgnLFxuICAnXFx1MjAyOSc6ICd1MjAyOSdcbn07XG5cbnZhciB0ZW1wbGF0ZV9lc2NhcGVyID0gL1xcXFx8J3xcXHJ8XFxufFxcdTIwMjh8XFx1MjAyOS9nO1xuXG5mdW5jdGlvbiB0ZW1wbGF0ZV9lc2NhcGVDaGFyKG1hdGNoKSB7XG4gIHJldHVybiAnXFxcXCcgKyB0ZW1wbGF0ZV9lc2NhcGVzW21hdGNoXTtcbn1cblxuZnVuY3Rpb24gdGVtcGxhdGVfZm9ybWF0KHBhdHRlcm4sIGZtdCkge1xuICBpZiAoKHBhdHRlcm5bMF0gPT09ICdcXCcnICYmIHBhdHRlcm5bcGF0dGVybi5sZW5ndGgtMV0gPT09ICdcXCcnKSB8fFxuICAgICAgKHBhdHRlcm5bMF0gPT09ICdcIicgICYmIHBhdHRlcm5bcGF0dGVybi5sZW5ndGgtMV0gPT09ICdcIicpKSB7XG4gICAgcGF0dGVybiA9IHBhdHRlcm4uc2xpY2UoMSwgLTEpO1xuICB9IGVsc2Uge1xuICAgIHRocm93IEVycm9yKCdGb3JtYXQgcGF0dGVybiBtdXN0IGJlIHF1b3RlZDogJyArIHBhdHRlcm4pO1xuICB9XG4gIGlmICghY29udGV4dC5mb3JtYXRfbWFwW3BhdHRlcm5dKSB7XG4gICAgdmFyIGYgPSBmbXQocGF0dGVybik7XG4gICAgdmFyIGkgPSBjb250ZXh0LmZvcm1hdHMubGVuZ3RoO1xuICAgIGNvbnRleHQuZm9ybWF0cy5wdXNoKGYpO1xuICAgIGNvbnRleHQuZm9ybWF0X21hcFtwYXR0ZXJuXSA9IGk7XG4gIH1cbiAgcmV0dXJuIGNvbnRleHQuZm9ybWF0X21hcFtwYXR0ZXJuXTtcbn1cbiJdfQ==
},{"./util":20}],19:[function(require,module,exports){
var STEPS = [
[31536e6, 5], // 1-year
[7776e6, 4], // 3-month
[2592e6, 4], // 1-month
[12096e5, 3], // 2-week
[6048e5, 3], // 1-week
[1728e5, 3], // 2-day
[864e5, 3], // 1-day
[432e5, 2], // 12-hour
[216e5, 2], // 6-hour
[108e5, 2], // 3-hour
[36e5, 2], // 1-hour
[18e5, 1], // 30-minute
[9e5, 1], // 15-minute
[3e5, 1], // 5-minute
[6e4, 1], // 1-minute
[3e4, 0], // 30-second
[15e3, 0], // 15-second
[5e3, 0], // 5-second
[1e3, 0] // 1-second
];
function isNumber(d) { return typeof d === 'number'; }
var entries = [
{
type: 'second',
minstep: 1,
format: '%Y %b %-d %H:%M:%S.%L',
date: function(d) {
return new Date(d * 1e3);
},
unit: function(d) {
return (+d / 1e3);
}
},
{
type: 'minute',
minstep: 1,
format: '%Y %b %-d %H:%M',
date: function(d) {
return new Date(d * 6e4);
},
unit: function(d) {
return ~~(+d / 6e4);
}
},
{
type: 'hour',
minstep: 1,
format: '%Y %b %-d %H:00',
date: function(d) {
return new Date(d * 36e5);
},
unit: function(d) {
return ~~(+d / 36e5);
}
},
{
type: 'day',
minstep: 1,
step: [1, 7],
format: '%Y %b %-d',
date: function(d) {
return new Date(d * 864e5);
},
unit: function(d) {
return ~~(+d / 864e5);
}
},
{
type: 'month',
minstep: 1,
step: [1, 3, 6],
format: '%b %Y',
date: function(d) {
return new Date(Date.UTC(~~(d / 12), d % 12, 1));
},
unit: function(d) {
if (isNumber(d)) d = new Date(d);
return 12 * d.getUTCFullYear() + d.getUTCMonth();
}
},
{
type: 'year',
minstep: 1,
format: '%Y',
date: function(d) {
return new Date(Date.UTC(d, 0, 1));
},
unit: function(d) {
return (isNumber(d) ? new Date(d) : d).getUTCFullYear();
}
}
];
var minuteOfHour = {
type: 'minuteOfHour',
min: 0,
max: 59,
minstep: 1,
format: '%M',
date: function(d) {
return new Date(Date.UTC(1970, 0, 1, 0, d));
},
unit: function(d) {
return (isNumber(d) ? new Date(d) : d).getUTCMinutes();
}
};
var hourOfDay = {
type: 'hourOfDay',
min: 0,
max: 23,
minstep: 1,
format: '%H',
date: function(d) {
return new Date(Date.UTC(1970, 0, 1, d));
},
unit: function(d) {
return (isNumber(d) ? new Date(d) : d).getUTCHours();
}
};
var dayOfWeek = {
type: 'dayOfWeek',
min: 0,
max: 6,
step: [1],
format: '%a',
date: function(d) {
return new Date(Date.UTC(1970, 0, 4 + d));
},
unit: function(d) {
return (isNumber(d) ? new Date(d) : d).getUTCDay();
}
};
var dayOfMonth = {
type: 'dayOfMonth',
min: 1,
max: 31,
step: [1],
format: '%-d',
date: function(d) {
return new Date(Date.UTC(1970, 0, d));
},
unit: function(d) {
return (isNumber(d) ? new Date(d) : d).getUTCDate();
}
};
var monthOfYear = {
type: 'monthOfYear',
min: 0,
max: 11,
step: [1],
format: '%b',
date: function(d) {
return new Date(Date.UTC(1970, d % 12, 1));
},
unit: function(d) {
return (isNumber(d) ? new Date(d) : d).getUTCMonth();
}
};
var units = {
'second': entries[0],
'minute': entries[1],
'hour': entries[2],
'day': entries[3],
'month': entries[4],
'year': entries[5],
'minuteOfHour': minuteOfHour,
'hourOfDay': hourOfDay,
'dayOfWeek': dayOfWeek,
'dayOfMonth': dayOfMonth,
'monthOfYear': monthOfYear,
'timesteps': entries
};
units.find = function(span, minb, maxb) {
var i, len, bins, step = STEPS[0];
for (i = 1, len = STEPS.length; i < len; ++i) {
step = STEPS[i];
if (span > step[0]) {
bins = span / step[0];
if (bins > maxb) {
return entries[STEPS[i - 1][1]];
}
if (bins >= minb) {
return entries[step[1]];
}
}
}
return entries[STEPS[STEPS.length - 1][1]];
};
module.exports = units;
},{}],20:[function(require,module,exports){
var buffer = require('buffer');
var units = require('./time-units');
var u = module.exports = {};
// utility functions
var FNAME = '__name__';
u.namedfunc = function(name, f) { return (f[FNAME] = name, f); };
u.name = function(f) { return f==null ? null : f[FNAME]; };
u.identity = function(x) { return x; };
u.true = u.namedfunc('true', function() { return true; });
u.false = u.namedfunc('false', function() { return false; });
u.duplicate = function(obj) {
return JSON.parse(JSON.stringify(obj));
};
u.equal = function(a, b) {
return JSON.stringify(a) === JSON.stringify(b);
};
u.extend = function(obj) {
for (var x, name, i=1, len=arguments.length; i<len; ++i) {
x = arguments[i];
for (name in x) { obj[name] = x[name]; }
}
return obj;
};
u.length = function(x) {
return x != null && x.length != null ? x.length : null;
};
u.keys = function(x) {
var keys = [], k;
for (k in x) keys.push(k);
return keys;
};
u.vals = function(x) {
var vals = [], k;
for (k in x) vals.push(x[k]);
return vals;
};
u.toMap = function(list, f) {
return (f = u.$(f)) ?
list.reduce(function(obj, x) { return (obj[f(x)] = 1, obj); }, {}) :
list.reduce(function(obj, x) { return (obj[x] = 1, obj); }, {});
};
u.keystr = function(values) {
// use to ensure consistent key generation across modules
var n = values.length;
if (!n) return '';
for (var s=String(values[0]), i=1; i<n; ++i) {
s += '|' + String(values[i]);
}
return s;
};
// type checking functions
var toString = Object.prototype.toString;
u.isObject = function(obj) {
return obj === Object(obj);
};
u.isFunction = function(obj) {
return toString.call(obj) === '[object Function]';
};
u.isString = function(obj) {
return typeof value === 'string' || toString.call(obj) === '[object String]';
};
u.isArray = Array.isArray || function(obj) {
return toString.call(obj) === '[object Array]';
};
u.isNumber = function(obj) {
return typeof obj === 'number' || toString.call(obj) === '[object Number]';
};
u.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
};
u.isDate = function(obj) {
return toString.call(obj) === '[object Date]';
};
u.isValid = function(obj) {
return obj != null && obj === obj;
};
u.isBuffer = (buffer.Buffer && buffer.Buffer.isBuffer) || u.false;
// type coercion functions
u.number = function(s) {
return s == null || s === '' ? null : +s;
};
u.boolean = function(s) {
return s == null || s === '' ? null : s==='false' ? false : !!s;
};
u.date = function(s) {
return s == null || s === '' ? null : Date.parse(s);
};
u.array = function(x) {
return x != null ? (u.isArray(x) ? x : [x]) : [];
};
u.str = function(x) {
return u.isArray(x) ? '[' + x.map(u.str) + ']'
: u.isObject(x) ? JSON.stringify(x)
: u.isString(x) ? ('\''+util_escape_str(x)+'\'') : x;
};
var escape_str_re = /(^|[^\\])'/g;
function util_escape_str(x) {
return x.replace(escape_str_re, '$1\\\'');
}
// data access functions
u.field = function(f) {
return String(f).split('\\.')
.map(function(d) { return d.split('.'); })
.reduce(function(a, b) {
if (a.length) { a[a.length-1] += '.' + b.shift(); }
a.push.apply(a, b);
return a;
}, []);
};
u.accessor = function(f) {
var s;
return f==null || u.isFunction(f) ? f :
u.namedfunc(f, (s = u.field(f)).length > 1 ?
function(x) { return s.reduce(function(x,f) { return x[f]; }, x); } :
function(x) { return x[f]; }
);
};
u.$ = u.accessor;
u.mutator = function(f) {
var s;
return u.isString(f) && (s=u.field(f)).length > 1 ?
function(x, v) {
for (var i=0; i<s.length-1; ++i) x = x[s[i]];
x[s[i]] = v;
} :
function(x, v) { x[f] = v; };
};
u.$func = function(name, op) {
return function(f) {
f = u.$(f) || u.identity;
var n = name + (u.name(f) ? '_'+u.name(f) : '');
return u.namedfunc(n, function(d) { return op(f(d)); });
};
};
u.$valid = u.$func('valid', u.isValid);
u.$length = u.$func('length', u.length);
u.$year = u.$func('year', units.year.unit);
u.$month = u.$func('month', units.monthOfYear.unit);
u.$date = u.$func('date', units.dayOfMonth.unit);
u.$day = u.$func('day', units.dayOfWeek.unit);
u.$hour = u.$func('hour', units.hourOfDay.unit);
u.$minute = u.$func('minute', units.minuteOfHour.unit);
u.$in = function(f, values) {
f = u.$(f);
var map = u.isArray(values) ? u.toMap(values) : values;
return function(d) { return !!map[f(d)]; };
};
// comparison / sorting functions
u.comparator = function(sort) {
var sign = [];
if (sort === undefined) sort = [];
sort = u.array(sort).map(function(f) {
var s = 1;
if (f[0] === '-') { s = -1; f = f.slice(1); }
else if (f[0] === '+') { s = +1; f = f.slice(1); }
sign.push(s);
return u.accessor(f);
});
return function(a,b) {
var i, n, f, x, y;
for (i=0, n=sort.length; i<n; ++i) {
f = sort[i]; x = f(a); y = f(b);
if (x < y) return -1 * sign[i];
if (x > y) return sign[i];
}
return 0;
};
};
u.cmp = function(a, b) {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else if (a >= b) {
return 0;
} else if (a === null) {
return -1;
} else if (b === null) {
return 1;
}
return NaN;
};
u.numcmp = function(a, b) { return a - b; };
u.stablesort = function(array, sortBy, keyFn) {
var indices = array.reduce(function(idx, v, i) {
return (idx[keyFn(v)] = i, idx);
}, {});
array.sort(function(a, b) {
var sa = sortBy(a),
sb = sortBy(b);
return sa < sb ? -1 : sa > sb ? 1
: (indices[keyFn(a)] - indices[keyFn(b)]);
});
return array;
};
// string functions
u.pad = function(s, length, pos, padchar) {
padchar = padchar || " ";
var d = length - s.length;
if (d <= 0) return s;
switch (pos) {
case 'left':
return strrep(d, padchar) + s;
case 'middle':
case 'center':
return strrep(Math.floor(d/2), padchar) +
s + strrep(Math.ceil(d/2), padchar);
default:
return s + strrep(d, padchar);
}
};
function strrep(n, str) {
var s = "", i;
for (i=0; i<n; ++i) s += str;
return s;
}
u.truncate = function(s, length, pos, word, ellipsis) {
var len = s.length;
if (len <= length) return s;
ellipsis = ellipsis !== undefined ? String(ellipsis) : '\u2026';
var l = Math.max(0, length - ellipsis.length);
switch (pos) {
case 'left':
return ellipsis + (word ? truncateOnWord(s,l,1) : s.slice(len-l));
case 'middle':
case 'center':
var l1 = Math.ceil(l/2), l2 = Math.floor(l/2);
return (word ? truncateOnWord(s,l1) : s.slice(0,l1)) +
ellipsis + (word ? truncateOnWord(s,l2,1) : s.slice(len-l2));
default:
return (word ? truncateOnWord(s,l) : s.slice(0,l)) + ellipsis;
}
};
function truncateOnWord(s, len, rev) {
var cnt = 0, tok = s.split(truncate_word_re);
if (rev) {
s = (tok = tok.reverse())
.filter(function(w) { cnt += w.length; return cnt <= len; })
.reverse();
} else {
s = tok.filter(function(w) { cnt += w.length; return cnt <= len; });
}
return s.length ? s.join('').trim() : tok[0].slice(0, len);
}
var truncate_word_re = /([\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u2028\u2029\u3000\uFEFF])/;
},{"./time-units":19,"buffer":2}],21:[function(require,module,exports){
arguments[4][19][0].apply(exports,arguments)
},{"dup":19}],22:[function(require,module,exports){
arguments[4][20][0].apply(exports,arguments)
},{"./time-units":21,"buffer":2,"dup":20}],23:[function(require,module,exports){
module.exports = require('./lib/heap');
},{"./lib/heap":24}],24:[function(require,module,exports){
// Generated by CoffeeScript 1.8.0
(function() {
var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup;
floor = Math.floor, min = Math.min;
/*
Default comparison function to be used
*/
defaultCmp = function(x, y) {
if (x < y) {
return -1;
}
if (x > y) {
return 1;
}
return 0;
};
/*
Insert item x in list a, and keep it sorted assuming a is sorted.
If x is already in a, insert it to the right of the rightmost x.
Optional args lo (default 0) and hi (default a.length) bound the slice
of a to be searched.
*/
insort = function(a, x, lo, hi, cmp) {
var mid;
if (lo == null) {
lo = 0;
}
if (cmp == null) {
cmp = defaultCmp;
}
if (lo < 0) {
throw new Error('lo must be non-negative');
}
if (hi == null) {
hi = a.length;
}
while (lo < hi) {
mid = floor((lo + hi) / 2);
if (cmp(x, a[mid]) < 0) {
hi = mid;
} else {
lo = mid + 1;
}
}
return ([].splice.apply(a, [lo, lo - lo].concat(x)), x);
};
/*
Push item onto heap, maintaining the heap invariant.
*/
heappush = function(array, item, cmp) {
if (cmp == null) {
cmp = defaultCmp;
}
array.push(item);
return _siftdown(array, 0, array.length - 1, cmp);
};
/*
Pop the smallest item off the heap, maintaining the heap invariant.
*/
heappop = function(array, cmp) {
var lastelt, returnitem;
if (cmp == null) {
cmp = defaultCmp;
}
lastelt = array.pop();
if (array.length) {
returnitem = array[0];
array[0] = lastelt;
_siftup(array, 0, cmp);
} else {
returnitem = lastelt;
}
return returnitem;
};
/*
Pop and return the current smallest value, and add the new item.
This is more efficient than heappop() followed by heappush(), and can be
more appropriate when using a fixed size heap. Note that the value
returned may be larger than item! That constrains reasonable use of
this routine unless written as part of a conditional replacement:
if item > array[0]
item = heapreplace(array, item)
*/
heapreplace = function(array, item, cmp) {
var returnitem;
if (cmp == null) {
cmp = defaultCmp;
}
returnitem = array[0];
array[0] = item;
_siftup(array, 0, cmp);
return returnitem;
};
/*
Fast version of a heappush followed by a heappop.
*/
heappushpop = function(array, item, cmp) {
var _ref;
if (cmp == null) {
cmp = defaultCmp;
}
if (array.length && cmp(array[0], item) < 0) {
_ref = [array[0], item], item = _ref[0], array[0] = _ref[1];
_siftup(array, 0, cmp);
}
return item;
};
/*
Transform list into a heap, in-place, in O(array.length) time.
*/
heapify = function(array, cmp) {
var i, _i, _j, _len, _ref, _ref1, _results, _results1;
if (cmp == null) {
cmp = defaultCmp;
}
_ref1 = (function() {
_results1 = [];
for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--){ _results1.push(_j); }
return _results1;
}).apply(this).reverse();
_results = [];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
i = _ref1[_i];
_results.push(_siftup(array, i, cmp));
}
return _results;
};
/*
Update the position of the given item in the heap.
This function should be called every time the item is being modified.
*/
updateItem = function(array, item, cmp) {
var pos;
if (cmp == null) {
cmp = defaultCmp;
}
pos = array.indexOf(item);
if (pos === -1) {
return;
}
_siftdown(array, 0, pos, cmp);
return _siftup(array, pos, cmp);
};
/*
Find the n largest elements in a dataset.
*/
nlargest = function(array, n, cmp) {
var elem, result, _i, _len, _ref;
if (cmp == null) {
cmp = defaultCmp;
}
result = array.slice(0, n);
if (!result.length) {
return result;
}
heapify(result, cmp);
_ref = array.slice(n);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
elem = _ref[_i];
heappushpop(result, elem, cmp);
}
return result.sort(cmp).reverse();
};
/*
Find the n smallest elements in a dataset.
*/
nsmallest = function(array, n, cmp) {
var elem, i, los, result, _i, _j, _len, _ref, _ref1, _results;
if (cmp == null) {
cmp = defaultCmp;
}
if (n * 10 <= array.length) {
result = array.slice(0, n).sort(cmp);
if (!result.length) {
return result;
}
los = result[result.length - 1];
_ref = array.slice(n);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
elem = _ref[_i];
if (cmp(elem, los) < 0) {
insort(result, elem, 0, null, cmp);
result.pop();
los = result[result.length - 1];
}
}
return result;
}
heapify(array, cmp);
_results = [];
for (i = _j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i = 0 <= _ref1 ? ++_j : --_j) {
_results.push(heappop(array, cmp));
}
return _results;
};
_siftdown = function(array, startpos, pos, cmp) {
var newitem, parent, parentpos;
if (cmp == null) {
cmp = defaultCmp;
}
newitem = array[pos];
while (pos > startpos) {
parentpos = (pos - 1) >> 1;
parent = array[parentpos];
if (cmp(newitem, parent) < 0) {
array[pos] = parent;
pos = parentpos;
continue;
}
break;
}
return array[pos] = newitem;
};
_siftup = function(array, pos, cmp) {
var childpos, endpos, newitem, rightpos, startpos;
if (cmp == null) {
cmp = defaultCmp;
}
endpos = array.length;
startpos = pos;
newitem = array[pos];
childpos = 2 * pos + 1;
while (childpos < endpos) {
rightpos = childpos + 1;
if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) {
childpos = rightpos;
}
array[pos] = array[childpos];
pos = childpos;
childpos = 2 * pos + 1;
}
array[pos] = newitem;
return _siftdown(array, startpos, pos, cmp);
};
Heap = (function() {
Heap.push = heappush;
Heap.pop = heappop;
Heap.replace = heapreplace;
Heap.pushpop = heappushpop;
Heap.heapify = heapify;
Heap.updateItem = updateItem;
Heap.nlargest = nlargest;
Heap.nsmallest = nsmallest;
function Heap(cmp) {
this.cmp = cmp != null ? cmp : defaultCmp;
this.nodes = [];
}
Heap.prototype.push = function(x) {
return heappush(this.nodes, x, this.cmp);
};
Heap.prototype.pop = function() {
return heappop(this.nodes, this.cmp);
};
Heap.prototype.peek = function() {
return this.nodes[0];
};
Heap.prototype.contains = function(x) {
return this.nodes.indexOf(x) !== -1;
};
Heap.prototype.replace = function(x) {
return heapreplace(this.nodes, x, this.cmp);
};
Heap.prototype.pushpop = function(x) {
return heappushpop(this.nodes, x, this.cmp);
};
Heap.prototype.heapify = function() {
return heapify(this.nodes, this.cmp);
};
Heap.prototype.updateItem = function(x) {
return updateItem(this.nodes, x, this.cmp);
};
Heap.prototype.clear = function() {
return this.nodes = [];
};
Heap.prototype.empty = function() {
return this.nodes.length === 0;
};
Heap.prototype.size = function() {
return this.nodes.length;
};
Heap.prototype.clone = function() {
var heap;
heap = new Heap();
heap.nodes = this.nodes.slice(0);
return heap;
};
Heap.prototype.toArray = function() {
return this.nodes.slice(0);
};
Heap.prototype.insert = Heap.prototype.push;
Heap.prototype.top = Heap.prototype.peek;
Heap.prototype.front = Heap.prototype.peek;
Heap.prototype.has = Heap.prototype.contains;
Heap.prototype.copy = Heap.prototype.clone;
return Heap;
})();
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
return define([], factory);
} else if (typeof exports === 'object') {
return module.exports = factory();
} else {
return root.Heap = factory();
}
})(this, function() {
return Heap;
});
}).call(this);
},{}],25:[function(require,module,exports){
var ts = Date.now();
function write(msg) {
msg = '[Vega Log] ' + msg;
console.log(msg);
}
function error(msg) {
msg = '[Vega Err] ' + msg;
console.error(msg);
}
function debug(input, args) {
if (!debug.enable) return;
var log = Function.prototype.bind.call(console.log, console);
var state = {
prevTime: Date.now() - ts,
stamp: input.stamp
};
if (input.add) {
state.add = input.add.length;
state.mod = input.mod.length;
state.rem = input.rem.length;
state.reflow = !!input.reflow;
}
log.apply(console, (args.push(JSON.stringify(state)), args));
ts = Date.now();
}
module.exports = {
log: write,
error: error,
debug: (debug.enable = false, debug)
};
},{}],26:[function(require,module,exports){
var DEPS = require('./Dependencies').ALL;
function create(cs, reflow) {
var out = {};
copy(cs, out);
out.add = [];
out.mod = [];
out.rem = [];
out.reflow = reflow;
return out;
}
function copy(a, b) {
b.stamp = a ? a.stamp : 0;
b.sort = a ? a.sort : null;
b.facet = a ? a.facet : null;
b.trans = a ? a.trans : null;
b.dirty = a ? a.dirty : [];
b.request = a ? a.request : null;
for (var d, i=0, n=DEPS.length; i<n; ++i) {
b[d=DEPS[i]] = a ? a[d] : {};
}
}
module.exports = {
create: create,
copy: copy
};
},{"./Dependencies":29}],27:[function(require,module,exports){
var log = require('vega-logging'),
Tuple = require('./Tuple'),
Base = require('./Node').prototype;
function Collector(graph) {
Base.init.call(this, graph);
this._data = [];
this.router(true).collector(true);
}
var prototype = (Collector.prototype = Object.create(Base));
prototype.constructor = Collector;
prototype.data = function() {
return this._data;
};
prototype.evaluate = function(input) {
log.debug(input, ["collecting"]);
if (input.rem.length) {
this._data = Tuple.idFilter(this._data, input.rem);
}
if (input.add.length) {
this._data = this._data.length ? this._data.concat(input.add) : input.add;
}
if (input.sort) {
this._data.sort(input.sort);
}
if (input.reflow) {
input.mod = input.mod.concat(Tuple.idFilter(this._data,
input.add, input.mod, input.rem));
input.reflow = false;
}
return input;
};
module.exports = Collector;
},{"./Node":31,"./Tuple":34,"vega-logging":25}],28:[function(require,module,exports){
var log = require('vega-logging'),
ChangeSet = require('./ChangeSet'),
Collector = require('./Collector'),
Tuple = require('./Tuple'),
Node = require('./Node'), // jshint ignore:line
SENTINEL = require('./Sentinel');
function DataSource(graph, name, facet) {
this._graph = graph;
this._name = name;
this._data = [];
this._source = null;
this._facet = facet;
this._input = ChangeSet.create();
this._output = null; // Output changeset
this._pipeline = null; // Pipeline of transformations.
this._collector = null; // Collector to materialize output of pipeline
this._revises = false; // Does any pipeline operator need to track prev?
}
var prototype = DataSource.prototype;
prototype.name = function(name) {
if (!arguments.length) return this._name;
return (this._name = name, this);
};
prototype.source = function(src) {
if (!arguments.length) return this._source;
return (this._source = this._graph.data(src));
};
prototype.insert = function(tuples) {
var prev = this._revises ? null : undefined;
var insert = tuples.map(function(d) {
return Tuple.ingest(d, prev);
});
this._input.add = this._input.add.concat(insert);
return this;
};
prototype.remove = function(where) {
var remove = this._data.filter(where);
this._input.rem = this._input.rem.concat(remove);
return this;
};
prototype.update = function(where, field, func) {
var mod = this._input.mod,
ids = Tuple.idMap(mod);
this._input.fields[field] = 1;
this._data.filter(where).forEach(function(x) {
var prev = x[field],
next = func(x);
if (prev !== next) {
Tuple.set(x, field, next);
if (ids[x._id] !== 1) {
mod.push(x);
ids[x._id] = 1;
}
}
});
return this;
};
prototype.values = function(data) {
if (!arguments.length) {
return this._collector ? this._collector.data() : this._data;
}
// Replace backing data
this._input.rem = this._data.slice();
if (data) { this.insert(data); }
return this;
};
function set_prev(d) {
if (d._prev === undefined) d._prev = SENTINEL;
}
prototype.revises = function(p) {
if (!arguments.length) return this._revises;
// If we've not needed prev in the past, but a new dataflow node needs it now
// ensure existing tuples have prev set.
if (!this._revises && p) {
this._data.forEach(set_prev);
// New tuples that haven't yet been merged into _data
this._input.add.forEach(set_prev);
}
this._revises = this._revises || p;
return this;
};
prototype.last = function() {
return this._output;
};
prototype.fire = function(input) {
if (input) this._input = input;
this._graph.propagate(this._input, this._pipeline[0]);
return this;
};
prototype.pipeline = function(pipeline) {
if (!arguments.length) return this._pipeline;
var ds = this;
// Add a collector to materialize the output of pipeline operators.
if (pipeline.length) {
ds._collector = new Collector(this._graph);
pipeline.push(ds._collector);
ds._revises = pipeline.some(function(p) { return p.revises(); });
}
// Input/output nodes masquerade as collector nodes, so they need to
// have a `data` function. dsData is used if a collector isn't available.
function dsData() { return ds._data; }
// Input node applies the datasource's delta, and propagates it to
// the rest of the pipeline. It receives touches to reflow data.
var input = new Node(this._graph)
.router(true)
.collector(true);
input.data = dsData;
input.evaluate = function(input) {
log.debug(input, ['input', ds._name]);
var delta = ds._input,
out = ChangeSet.create(input), f;
// Delta might contain fields updated through API
for (f in delta.fields) {
out.fields[f] = 1;
}
// update data
if (delta.rem.length) {
ds._data = Tuple.idFilter(ds._data, delta.rem);
}
if (delta.add.length) {
ds._data = ds._data.concat(delta.add);
}
// if reflowing, add any other tuples not currently in changeset
if (input.reflow) {
delta.mod = delta.mod.concat(Tuple.idFilter(ds._data,
delta.add, delta.mod, delta.rem));
}
// reset change list
ds._input = ChangeSet.create();
out.add = delta.add;
out.mod = delta.mod;
out.rem = delta.rem;
out.facet = ds._facet;
return out;
};
pipeline.unshift(input);
// Output node captures the last changeset seen by this datasource
// (needed for joins and builds) and materializes any nested data.
// If this datasource is faceted, materializes the values in the facet.
var output = new Node(this._graph)
.router(true)
.reflows(true)
.collector(true);
output.data = ds._collector ?
ds._collector.data.bind(ds._collector) :
dsData;
output.evaluate = function(input) {
log.debug(input, ['output', ds._name]);
var output = ChangeSet.create(input, true);
if (ds._facet) {
ds._facet.values = ds.values();
input.facet = null;
}
ds._output = input;
output.data[ds._name] = 1;
return output;
};
pipeline.push(output);
this._pipeline = pipeline;
this._graph.connect(ds._pipeline);
return this;
};
prototype.finalize = function() {
if (!this._revises) return;
for (var i=0, n=this._data.length; i<n; ++i) {
var x = this._data[i];
x._prev = (x._prev === undefined) ? undefined : SENTINEL;
}
};
prototype.listener = function() {
var l = new Node(this._graph).router(true),
dest = this,
prev = this._revises ? null : undefined;
l.evaluate = function(input) {
dest._srcMap = dest._srcMap || {}; // to propagate tuples correctly
var map = dest._srcMap,
output = ChangeSet.create(input);
output.add = input.add.map(function(t) {
var d = Tuple.derive(t, t._prev !== undefined ? t._prev : prev);
return (map[t._id] = d);
});
output.mod = input.mod.map(function(t) {
var o = map[t._id];
return (o._prev = t._prev, o);
});
output.rem = input.rem.map(function(t) {
var o = map[t._id];
map[t._id] = null;
return (o._prev = t._prev, o);
});
return (dest._input = output);
};
l.addListener(this._pipeline[0]);
return l;
};
prototype.addListener = function(l) {
if (l instanceof DataSource) {
if (this._collector) {
this._collector.addListener(l.listener());
} else {
this._pipeline[0].addListener(l.listener());
}
} else {
this._pipeline[this._pipeline.length-1].addListener(l);
}
return this;
};
prototype.removeListener = function(l) {
this._pipeline[this._pipeline.length-1].removeListener(l);
};
prototype.listeners = function(ds) {
if (ds) {
return this._collector ?
this._collector.listeners() :
this._pipeline[0].listeners();
} else {
return this._pipeline[this._pipeline.length-1].listeners();
}
};
module.exports = DataSource;
},{"./ChangeSet":26,"./Collector":27,"./Node":31,"./Sentinel":32,"./Tuple":34,"vega-logging":25}],29:[function(require,module,exports){
var deps = module.exports = {
ALL: ['data', 'fields', 'scales', 'signals']
};
deps.ALL.forEach(function(k) { deps[k.toUpperCase()] = k; });
},{}],30:[function(require,module,exports){
var Heap = require('heap'),
util = require('datalib/src/util'),
ChangeSet = require('./ChangeSet'),
DataSource = require('./DataSource'),
Collector = require('./Collector'),
Signal = require('./Signal'),
Deps = require('./Dependencies');
function Graph() {
}
var prototype = Graph.prototype;
prototype.init = function() {
this._stamp = 0;
this._rank = 0;
this._data = {};
this._signals = {};
this.doNotPropagate = {};
};
prototype.rank = function() {
return ++this._rank;
};
prototype.data = function(name, pipeline, facet) {
var db = this._data;
if (!arguments.length) {
var all = [], key;
for (key in db) { all.push(db[key]); }
return all;
} else if (arguments.length === 1) {
return db[name];
} else {
return (db[name] = new DataSource(this, name, facet).pipeline(pipeline));
}
};
prototype.dataValues = function(names) {
var data = this._data, k;
if (!arguments.length) {
names = [];
for (k in data) names.push(k);
}
if (Array.isArray(names)) {
return names.reduce(function(db, name) {
return (db[name] = data[name].values(), db);
}, {});
} else {
return data[names].values();
}
};
function signal(names) {
var m = this;
if (Array.isArray(names)) {
return names.map(function(name) {
return m._signals[name];
});
} else {
return this._signals[names];
}
}
prototype.signal = function(name, init) {
if (arguments.length === 1) {
return signal.call(this, name);
} else {
return (this._signals[name] = new Signal(this, name, init));
}
};
// TODO: separate into signalValue and signalValues?
prototype.signalValues = function(names) {
if (!arguments.length) {
names = [];
for (var k in this._signals) names.push(k);
}
if (Array.isArray(names)) {
var values = {};
for (var i=0, n=names.length; i<n; ++i) {
values[names[i]] = this._signals[names[i]].value();
}
return values;
} else {
return this._signals[names].value();
}
};
prototype.signalRef = function(ref) {
if (!Array.isArray(ref)) {
ref = util.field(ref);
}
var value = this.signal(ref[0]).value();
if (ref.length > 1) {
for (var i=1, n=ref.length; i<n; ++i) {
value = value[ref[i]];
}
}
return value;
};
var schedule = function(a, b) {
if (a.rank !== b.rank) {
// Topological sort
return a.rank - b.rank;
} else {
// If queueing multiple pulses to the same node, then there will be
// at most one pulse with a changeset (add/mod/rem), and the remainder
// will be reflows. Combine the changeset and reflows into a single pulse
// and queue that first. Subsequent reflow-only pulses will be pruned.
var pa = a.pulse, pb = b.pulse,
paCS = pa.add.length || pa.mod.length || pa.rem.length,
pbCS = pb.add.length || pb.mod.length || pb.rem.length;
pa.reflow = pb.reflow = pa.reflow || pb.reflow;
if (paCS && pbCS) throw Error('Both pulses have changesets.');
return paCS ? -1 : 1;
}
};
// Stamp should be specified with caution. It is necessary for inline datasources,
// which need to be populated during the same cycle even though propagation has
// passed that part of the dataflow graph.
prototype.propagate = function(pulse, node, stamp) {
var v, l, n, p, r, i, len, reflowed;
// new PQ with each propagation cycle so that we can pulse branches
// of the dataflow graph during a propagation (e.g., when creating
// a new inline datasource).
var pq = new Heap(schedule);
if (pulse.stamp) throw Error('Pulse already has a non-zero stamp.');
pulse.stamp = stamp || ++this._stamp;
pq.push({node: node, pulse: pulse, rank: node.rank()});
while (pq.size() > 0) {
v = pq.pop();
n = v.node;
p = v.pulse;
r = v.rank;
l = n._listeners;
reflowed = p.reflow && n.last() >= p.stamp;
if (reflowed) continue; // Don't needlessly reflow ops.
// A node's rank might change during a propagation (e.g. instantiating
// a group's dataflow branch). Re-queue if it has.
// TODO: use pq.replace or pq.poppush?
if (r !== n.rank()) {
pq.push({node: n, pulse: p, rank: n.rank()});
continue;
}
p = this.evaluate(p, n);
// Even if we didn't run the node, we still want to propagate the pulse.
if (p !== this.doNotPropagate) {
if (!p.reflow && n.reflows()) { // If skipped eval of reflows node
p = ChangeSet.create(p, true);
}
for (i=0, len=l.length; i<len; ++i) {
pq.push({node: l[i], pulse: p, rank: l[i]._rank, src: n});
}
}
}
};
// Connect a branch of dataflow nodes.
// Dependencies are wired to the nearest collector.
function forEachNode(branch, fn) {
var node, collector, router, i, n;
for (i=0, n=branch.length; i<n; ++i) {
node = branch[i];
// Share collectors between batch transforms. We can reuse an
// existing collector unless a router node has come after it,
// in which case, we splice in a new collector.
if (!node.data && node.batch()) { /* TODO: update transforms! */
if (router) {
branch.splice(i, 0, (node = new Collector(this)));
} else {
node.data = collector.data.bind(collector);
}
}
if (node.collector()) collector = node;
router = node.router() && !node.collector();
fn(node, collector, i);
}
}
prototype.connect = function(branch) {
var graph = this;
forEachNode.call(this, branch, function(n, c, i) {
var data = n.dependency(Deps.DATA),
signals = n.dependency(Deps.SIGNALS);
if (data.length > 0) {
data.forEach(function(d) {
graph.data(d)
.revises(n.revises())
.addListener(c);
});
}
if (signals.length > 0) {
signals.forEach(function(s) { graph.signal(s).addListener(c); });
}
if (i > 0) {
branch[i-1].addListener(branch[i]);
}
});
return branch;
};
prototype.disconnect = function(branch) {
var graph = this;
forEachNode.call(this, branch, function(n, c) {
var data = n.dependency(Deps.DATA),
signals = n.dependency(Deps.SIGNALS);
if (data.length > 0) {
data.forEach(function(d) { graph.data(d).removeListener(c); });
}
if (signals.length > 0) {
signals.forEach(function(s) { graph.signal(s).removeListener(c); });
}
n.disconnect();
});
return branch;
};
prototype.reevaluate = function(pulse, node) {
var reflowed = !pulse.reflow || (pulse.reflow && node.last() >= pulse.stamp),
run = !!pulse.add.length || !!pulse.rem.length || node.router();
return run || !reflowed || node.reevaluate(pulse);
};
prototype.evaluate = function(pulse, node) {
if (!this.reevaluate(pulse, node)) return pulse;
pulse = node.evaluate(pulse);
node.last(pulse.stamp);
return pulse;
};
module.exports = Graph;
},{"./ChangeSet":26,"./Collector":27,"./DataSource":28,"./Dependencies":29,"./Signal":33,"datalib/src/util":22,"heap":23}],31:[function(require,module,exports){
var DEPS = require('./Dependencies').ALL,
nodeID = 1;
function Node(graph) {
if (graph) this.init(graph);
}
var Flags = Node.Flags = {
Router: 0x01, // Responsible for propagating tuples, cannot be skipped.
Collector: 0x02, // Holds a materialized dataset, pulse node to reflow.
Revises: 0x04, // Node requires tuple previous values.
Reflows: 0x08, // Node will forward a reflow pulse.
Batch: 0x10 // Node performs batch data processing, needs collector.
};
var prototype = Node.prototype;
prototype.init = function(graph) {
this._id = nodeID++;
this._graph = graph;
this._rank = graph.rank(); // For topologial sort
this._stamp = 0; // Last stamp seen
this._listeners = [];
this._registered = {}; // To prevent duplicate listeners
// Initialize dependencies.
this._deps = {};
for (var i=0, n=DEPS.length; i<n; ++i) {
this._deps[DEPS[i]] = [];
}
// Initialize status flags.
this._flags = 0;
return this;
};
prototype.rank = function() {
return this._rank;
};
prototype.last = function(stamp) {
if (!arguments.length) return this._stamp;
this._stamp = stamp;
return this;
};
// -- status flags ---
prototype._setf = function(v, b) {
if (b) { this._flags |= v; } else { this._flags &= ~v; }
return this;
};
prototype.router = function(state) {
if (!arguments.length) return (this._flags & Flags.Router);
return this._setf(Flags.Router, state);
};
prototype.collector = function(state) {
if (!arguments.length) return (this._flags & Flags.Collector);
return this._setf(Flags.Collector, state);
};
prototype.revises = function(state) {
if (!arguments.length) return (this._flags & Flags.Revises);
return this._setf(Flags.Revises, state);
};
prototype.reflows = function(state) {
if (!arguments.length) return (this._flags & Flags.Reflows);
return this._setf(Flags.Reflows, state);
};
prototype.batch = function(state) {
if (!arguments.length) return (this._flags & Flags.Batch);
return this._setf(Flags.Batch, state);
};
prototype.dependency = function(type, deps) {
var d = this._deps[type];
if (arguments.length === 1) {
return d;
}
if (deps === null) {
// Clear dependencies of the given type
d.splice(0, d.length);
} else if (deps !== undefined) {
if (!Array.isArray(deps)) {
if (d.indexOf(deps) < 0) { d.push(deps); }
} else {
// TODO: singleton case checks for inclusion already
// Should this be done here as well?
d.push.apply(d, deps);
}
}
return this;
};
prototype.listeners = function() {
return this._listeners;
};
prototype.addListener = function(l) {
if (!(l instanceof Node)) {
throw Error('Listener is not a Node');
}
if (this._registered[l._id]) return this;
this._listeners.push(l);
this._registered[l._id] = 1;
if (this._rank > l._rank) {
var q = [l],
g = this._graph, cur;
while (q.length) {
cur = q.shift();
cur._rank = g.rank();
q.push.apply(q, cur.listeners());
}
}
return this;
};
prototype.removeListener = function(l) {
var idx = this._listeners.indexOf(l),
b = idx >= 0;
if (b) {
this._listeners.splice(idx, 1);
this._registered[l._id] = null;
}
return b;
};
prototype.disconnect = function() {
this._listeners = [];
this._registered = {};
};
// Evaluate this dataflow node for the current pulse.
// Subclasses should override to perform custom processing.
prototype.evaluate = function(pulse) {
return pulse;
};
// Should this node be re-evaluated for the current pulse?
// Searches pulse to see if any dependencies have updated.
prototype.reevaluate = function(pulse) {
var prop, dep, i, n, j, m;
for (i=0, n=DEPS.length; i<n; ++i) {
prop = DEPS[i];
dep = this._deps[prop];
for (j=0, m=dep.length; j<m; ++j) {
if (pulse[prop][dep[j]]) return true;
}
}
return false;
};
module.exports = Node;
},{"./Dependencies":29}],32:[function(require,module,exports){
module.exports = {'sentinel': 1};
},{}],33:[function(require,module,exports){
var ChangeSet = require('./ChangeSet'),
Node = require('./Node'), // jshint ignore:line
Base = Node.prototype;
function Signal(graph, name, initialValue) {
Base.init.call(this, graph);
this._name = name;
this._value = initialValue;
this._verbose = false; // Verbose signals re-pulse the graph even if prev === val.
this._handlers = [];
return this;
}
var prototype = (Signal.prototype = Object.create(Base));
prototype.constructor = Signal;
prototype.name = function() {
return this._name;
};
prototype.value = function(val) {
if (!arguments.length) return this._value;
return (this._value = val, this);
};
prototype.verbose = function(v) {
if (!arguments.length) return this._verbose;
return (this._verbose = !!v, this);
};
prototype.evaluate = function(input) {
return input.signals[this._name] ? input : this._graph.doNotPropagate;
};
prototype.fire = function(cs) {
if (!cs) cs = ChangeSet.create(null, true);
cs.signals[this._name] = 1;
this._graph.propagate(cs, this);
};
prototype.on = function(handler) {
var signal = this,
node = new Node(this._graph);
node.evaluate = function(input) {
handler(signal.name(), signal.value());
return input;
};
this._handlers.push({
handler: handler,
node: node
});
return this.addListener(node);
};
prototype.off = function(handler) {
var h = this._handlers, i, x;
for (i=h.length; --i>=0;) {
if (!handler || h[i].handler === handler) {
x = h.splice(i, 1)[0];
this.removeListener(x.node);
}
}
return this;
};
module.exports = Signal;
},{"./ChangeSet":26,"./Node":31}],34:[function(require,module,exports){
var util = require('datalib/src/util'),
SENTINEL = require('./Sentinel'),
tupleID = 0;
// Object.create is expensive. So, when ingesting, trust that the
// datum is an object that has been appropriately sandboxed from
// the outside environment.
function ingest(datum, prev) {
datum = (datum === Object(datum)) ? datum : {data: datum};
datum._id = ++tupleID;
datum._prev = (prev !== undefined) ? (prev || SENTINEL) : undefined;
return datum;
}
function derive(datum, prev) {
return ingest(Object.create(datum), prev);
}
// WARNING: operators should only call this once per timestamp!
function set(t, k, v) {
var prev = t[k];
if (prev === v) return false;
set_prev(t, k);
t[k] = v;
return true;
}
function set_prev(t, k) {
if (t._prev === undefined) return;
t._prev = (t._prev === SENTINEL) ? {} : t._prev;
t._prev[k] = t[k];
}
function has_prev(t) {
return t._prev && t._prev !== SENTINEL;
}
function reset() {
tupleID = 0;
}
function idMap(a) {
for (var ids={}, i=0, n=a.length; i<n; ++i) {
ids[a[i]._id] = 1;
}
return ids;
}
function idFilter(data) {
var ids = {};
for (var i=1, len=arguments.length; i<len; ++i) {
util.extend(ids, idMap(arguments[i]));
}
return data.filter(function(x) { return !ids[x._id]; });
}
module.exports = {
ingest: ingest,
derive: derive,
set: set,
set_prev: set_prev,
has_prev: has_prev,
reset: reset,
idMap: idMap,
idFilter: idFilter
};
},{"./Sentinel":32,"datalib/src/util":22}],35:[function(require,module,exports){
module.exports = {
ChangeSet: require('./ChangeSet'),
Collector: require('./Collector'),
DataSource: require('./DataSource'),
Dependencies: require('./Dependencies'),
Graph: require('./Graph'),
Node: require('./Node'),
Sentinel: require('./Sentinel'),
Signal: require('./Signal'),
Tuple: require('./Tuple'),
debug: require('vega-logging').debug
};
},{"./ChangeSet":26,"./Collector":27,"./DataSource":28,"./Dependencies":29,"./Graph":30,"./Node":31,"./Sentinel":32,"./Signal":33,"./Tuple":34,"vega-logging":25}],36:[function(require,module,exports){
function toMap(list) {
var map = {}, i, n;
for (i=0, n=list.length; i<n; ++i) map[list[i]] = 1;
return map;
}
function keys(object) {
var list = [], k;
for (k in object) list.push(k);
return list;
}
module.exports = function(opt) {
opt = opt || {};
var constants = opt.constants || require('./constants'),
functions = (opt.functions || require('./functions'))(codegen),
idWhiteList = opt.idWhiteList ? toMap(opt.idWhiteList) : null,
idBlackList = opt.idBlackList ? toMap(opt.idBlackList) : null,
memberDepth = 0,
FIELD_VAR = opt.fieldVar || 'datum',
GLOBAL_VAR = opt.globalVar || 'signals',
globals = {},
fields = {};
function codegen_wrap(ast) {
var retval = {
code: codegen(ast),
globals: keys(globals),
fields: keys(fields)
};
globals = {};
fields = {};
return retval;
}
function lookupGlobal(id) {
return GLOBAL_VAR + '["' + id + '"]';
}
function codegen(ast) {
if (typeof ast === 'string') return ast;
var generator = CODEGEN_TYPES[ast.type];
if (generator == null) {
throw new Error('Unsupported type: ' + ast.type);
}
return generator(ast);
}
var CODEGEN_TYPES = {
'Literal': function(n) {
return n.raw;
},
'Identifier': function(n) {
var id = n.name;
if (memberDepth > 0) {
return id;
}
if (constants.hasOwnProperty(id)) {
return constants[id];
}
if (idWhiteList) {
if (idWhiteList.hasOwnProperty(id)) {
return id;
} else {
globals[id] = 1;
return lookupGlobal(id);
}
}
if (idBlackList && idBlackList.hasOwnProperty(id)) {
throw new Error('Illegal identifier: ' + id);
}
return id;
},
'Program': function(n) {
return n.body.map(codegen).join('\n');
},
'MemberExpression': function(n) {
var d = !n.computed;
var o = codegen(n.object);
if (d) memberDepth += 1;
var p = codegen(n.property);
if (o === FIELD_VAR) { fields[p] = 1; } // HACKish...
if (d) memberDepth -= 1;
return o + (d ? '.'+p : '['+p+']');
},
'CallExpression': function(n) {
if (n.callee.type !== 'Identifier') {
throw new Error('Illegal callee type: ' + n.callee.type);
}
var callee = n.callee.name;
var args = n.arguments;
var fn = functions.hasOwnProperty(callee) && functions[callee];
if (!fn) throw new Error('Unrecognized function: ' + callee);
return fn instanceof Function ?
fn(args) :
fn + '(' + args.map(codegen).join(',') + ')';
},
'ArrayExpression': function(n) {
return '[' + n.elements.map(codegen).join(',') + ']';
},
'BinaryExpression': function(n) {
return '(' + codegen(n.left) + n.operator + codegen(n.right) + ')';
},
'UnaryExpression': function(n) {
return '(' + n.operator + codegen(n.argument) + ')';
},
'ConditionalExpression': function(n) {
return '(' + codegen(n.test) +
'?' + codegen(n.consequent) +
':' + codegen(n.alternate) +
')';
},
'LogicalExpression': function(n) {
return '(' + codegen(n.left) + n.operator + codegen(n.right) + ')';
},
'ObjectExpression': function(n) {
return '{' + n.properties.map(codegen).join(',') + '}';
},
'Property': function(n) {
memberDepth += 1;
var k = codegen(n.key);
memberDepth -= 1;
return k + ':' + codegen(n.value);
},
'ExpressionStatement': function(n) {
return codegen(n.expression);
}
};
return codegen_wrap;
};
},{"./constants":37,"./functions":38}],37:[function(require,module,exports){
module.exports = {
'NaN': 'NaN',
'E': 'Math.E',
'LN2': 'Math.LN2',
'LN10': 'Math.LN10',
'LOG2E': 'Math.LOG2E',
'LOG10E': 'Math.LOG10E',
'PI': 'Math.PI',
'SQRT1_2': 'Math.SQRT1_2',
'SQRT2': 'Math.SQRT2'
};
},{}],38:[function(require,module,exports){
module.exports = function(codegen) {
function fncall(name, args, cast, type) {
var obj = codegen(args[0]);
if (cast) {
obj = cast + '(' + obj + ')';
if (cast.lastIndexOf('new ', 0) === 0) obj = '(' + obj + ')';
}
return obj + '.' + name + (type < 0 ? '' : type === 0 ?
'()' :
'(' + args.slice(1).map(codegen).join(',') + ')');
}
var DATE = 'new Date';
var STRING = 'String';
var REGEXP = 'RegExp';
return {
// MATH functions
'isNaN': 'isNaN',
'isFinite': 'isFinite',
'abs': 'Math.abs',
'acos': 'Math.acos',
'asin': 'Math.asin',
'atan': 'Math.atan',
'atan2': 'Math.atan2',
'ceil': 'Math.ceil',
'cos': 'Math.cos',
'exp': 'Math.exp',
'floor': 'Math.floor',
'log': 'Math.log',
'max': 'Math.max',
'min': 'Math.min',
'pow': 'Math.pow',
'random': 'Math.random',
'round': 'Math.round',
'sin': 'Math.sin',
'sqrt': 'Math.sqrt',
'tan': 'Math.tan',
'clamp': function(args) {
if (args.length < 3)
throw new Error('Missing arguments to clamp function.');
if (args.length > 3)
throw new Error('Too many arguments to clamp function.');
var a = args.map(codegen);
return 'Math.max('+a[1]+', Math.min('+a[2]+','+a[0]+'))';
},
// DATE functions
'now': 'Date.now',
'datetime': 'new Date',
'date': function(args) {
return fncall('getDate', args, DATE, 0);
},
'day': function(args) {
return fncall('getDay', args, DATE, 0);
},
'year': function(args) {
return fncall('getFullYear', args, DATE, 0);
},
'month': function(args) {
return fncall('getMonth', args, DATE, 0);
},
'hours': function(args) {
return fncall('getHours', args, DATE, 0);
},
'minutes': function(args) {
return fncall('getMinutes', args, DATE, 0);
},
'seconds': function(args) {
return fncall('getSeconds', args, DATE, 0);
},
'milliseconds': function(args) {
return fncall('getMilliseconds', args, DATE, 0);
},
'time': function(args) {
return fncall('getTime', args, DATE, 0);
},
'timezoneoffset': function(args) {
return fncall('getTimezoneOffset', args, DATE, 0);
},
'utcdate': function(args) {
return fncall('getUTCDate', args, DATE, 0);
},
'utcday': function(args) {
return fncall('getUTCDay', args, DATE, 0);
},
'utcyear': function(args) {
return fncall('getUTCFullYear', args, DATE, 0);
},
'utcmonth': function(args) {
return fncall('getUTCMonth', args, DATE, 0);
},
'utchours': function(args) {
return fncall('getUTCHours', args, DATE, 0);
},
'utcminutes': function(args) {
return fncall('getUTCMinutes', args, DATE, 0);
},
'utcseconds': function(args) {
return fncall('getUTCSeconds', args, DATE, 0);
},
'utcmilliseconds': function(args) {
return fncall('getUTCMilliseconds', args, DATE, 0);
},
// shared sequence functions
'length': function(args) {
return fncall('length', args, null, -1);
},
'indexof': function(args) {
return fncall('indexOf', args, null);
},
'lastindexof': function(args) {
return fncall('lastIndexOf', args, null);
},
// STRING functions
'parseFloat': 'parseFloat',
'parseInt': 'parseInt',
'upper': function(args) {
return fncall('toUpperCase', args, STRING, 0);
},
'lower': function(args) {
return fncall('toLowerCase', args, STRING, 0);
},
'slice': function(args) {
return fncall('slice', args, STRING);
},
'substring': function(args) {
return fncall('substring', args, STRING);
},
// REGEXP functions
'test': function(args) {
return fncall('test', args, REGEXP);
},
// Control Flow functions
'if': function(args) {
if (args.length < 3)
throw new Error('Missing arguments to if function.');
if (args.length > 3)
throw new Error('Too many arguments to if function.');
var a = args.map(codegen);
return a[0]+'?'+a[1]+':'+a[2];
}
};
};
},{}],39:[function(require,module,exports){
var parser = require('./parser'),
codegen = require('./codegen');
var expr = module.exports = {
parse: function(input, opt) {
return parser.parse('('+input+')', opt);
},
code: function(opt) {
return codegen(opt);
},
compiler: function(args, opt) {
args = args.slice();
var generator = codegen(opt),
len = args.length;
return function(str) {
var value = generator(expr.parse(str));
args[len] = '"use strict"; return (' + value.code + ');';
value.fn = Function.apply(null, args);
return value;
};
},
functions: require('./functions'),
constants: require('./constants')
};
},{"./codegen":36,"./constants":37,"./functions":38,"./parser":40}],40:[function(require,module,exports){
/*
The following expression parser is based on Esprima (http://esprima.org/).
Original header comment and license for Esprima is included here:
Copyright (C) 2013 Ariya Hidayat <ariya.hidayat@gmail.com>
Copyright (C) 2013 Thaddee Tyl <thaddee.tyl@gmail.com>
Copyright (C) 2013 Mathias Bynens <mathias@qiwi.be>
Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
Copyright (C) 2012 Mathias Bynens <mathias@qiwi.be>
Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com>
Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com>
Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
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.
*/
/* istanbul ignore next */
module.exports = (function() {
'use strict';
var Token,
TokenName,
Syntax,
PropertyKind,
Messages,
Regex,
source,
strict,
index,
lineNumber,
lineStart,
length,
lookahead,
state,
extra;
Token = {
BooleanLiteral: 1,
EOF: 2,
Identifier: 3,
Keyword: 4,
NullLiteral: 5,
NumericLiteral: 6,
Punctuator: 7,
StringLiteral: 8,
RegularExpression: 9
};
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.RegularExpression] = 'RegularExpression';
Syntax = {
AssignmentExpression: 'AssignmentExpression',
ArrayExpression: 'ArrayExpression',
BinaryExpression: 'BinaryExpression',
CallExpression: 'CallExpression',
ConditionalExpression: 'ConditionalExpression',
ExpressionStatement: 'ExpressionStatement',
Identifier: 'Identifier',
Literal: 'Literal',
LogicalExpression: 'LogicalExpression',
MemberExpression: 'MemberExpression',
ObjectExpression: 'ObjectExpression',
Program: 'Program',
Property: 'Property',
UnaryExpression: 'UnaryExpression'
};
PropertyKind = {
Data: 1,
Get: 2,
Set: 4
};
// 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',
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',
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',
IllegalReturn: 'Illegal return statement',
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',
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'
};
// 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\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\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-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\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-\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-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\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-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\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\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\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-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\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\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\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\u0D01-\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\u0DE6-\u0DEF\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-\u16F8\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-\u191E\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\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\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-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\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-\uFE2D\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]')
};
// 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) {
if (!condition) {
throw new Error('ASSERT: ' + message);
}
}
function isDecimalDigit(ch) {
return (ch >= 0x30 && ch <= 0x39); // 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 === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) ||
(ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0);
}
// 7.3 Line Terminators
function isLineTerminator(ch) {
return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029);
}
// 7.6 Identifier Names and Identifiers
function isIdentifierStart(ch) {
return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore)
(ch >= 0x41 && ch <= 0x5A) || // A..Z
(ch >= 0x61 && ch <= 0x7A) || // a..z
(ch === 0x5C) || // \ (backslash)
((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch)));
}
function isIdentifierPart(ch) {
return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore)
(ch >= 0x41 && ch <= 0x5A) || // A..Z
(ch >= 0x61 && ch <= 0x7A) || // a..z
(ch >= 0x30 && ch <= 0x39) || // 0..9
(ch === 0x5C) || // \ (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;
}
}
// 7.6.1.1 Keywords
function isKeyword(id) {
if (strict && isStrictModeReservedWord(id)) {
return true;
}
// 'const' is specialized as Keyword in V8.
// 'yield' and 'let' are 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 === 'yield') ||
(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;
}
}
function skipComment() {
var ch, start;
start = (index === 0);
while (index < length) {
ch = source.charCodeAt(index);
if (isWhiteSpace(ch)) {
++index;
} else if (isLineTerminator(ch)) {
++index;
if (ch === 0x0D && source.charCodeAt(index) === 0x0A) {
++index;
}
++lineNumber;
lineStart = index;
start = true;
} 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' (U+005C, U+0075) denotes an escaped character.
if (ch === 0x5C) {
if (source.charCodeAt(index) !== 0x75) {
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' (U+005C, U+0075) denotes an escaped character.
if (ch === 0x5C) {
id = id.substr(0, id.length - 1);
if (source.charCodeAt(index) !== 0x75) {
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 === 0x5C) {
// Blackslash (U+005C) 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 (U+005C) starts an escaped character.
id = (source.charCodeAt(index) === 0x5C) ? 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,
start: start,
end: index
};
}
// 7.7 Punctuators
function scanPunctuator() {
var start = index,
code = source.charCodeAt(index),
code2,
ch1 = source[index],
ch2,
ch3,
ch4;
switch (code) {
// Check for most common single-character punctuators.
case 0x2E: // . dot
case 0x28: // ( open bracket
case 0x29: // ) close bracket
case 0x3B: // ; semicolon
case 0x2C: // , comma
case 0x7B: // { open curly brace
case 0x7D: // } close curly brace
case 0x5B: // [
case 0x5D: // ]
case 0x3A: // :
case 0x3F: // ?
case 0x7E: // ~
++index;
if (extra.tokenize) {
if (code === 0x28) {
extra.openParenToken = extra.tokens.length;
} else if (code === 0x7B) {
extra.openCurlyToken = extra.tokens.length;
}
}
return {
type: Token.Punctuator,
value: String.fromCharCode(code),
lineNumber: lineNumber,
lineStart: lineStart,
start: start,
end: index
};
default:
code2 = source.charCodeAt(index + 1);
// '=' (U+003D) marks an assignment or comparison operator.
if (code2 === 0x3D) {
switch (code) {
case 0x2B: // +
case 0x2D: // -
case 0x2F: // /
case 0x3C: // <
case 0x3E: // >
case 0x5E: // ^
case 0x7C: // |
case 0x25: // %
case 0x26: // &
case 0x2A: // *
index += 2;
return {
type: Token.Punctuator,
value: String.fromCharCode(code) + String.fromCharCode(code2),
lineNumber: lineNumber,
lineStart: lineStart,
start: start,
end: index
};
case 0x21: // !
case 0x3D: // =
index += 2;
// !== and ===
if (source.charCodeAt(index) === 0x3D) {
++index;
}
return {
type: Token.Punctuator,
value: source.slice(start, index),
lineNumber: lineNumber,
lineStart: lineStart,
start: start,
end: index
};
}
}
}
// 4-character punctuator: >>>=
ch4 = source.substr(index, 4);
if (ch4 === '>>>=') {
index += 4;
return {
type: Token.Punctuator,
value: ch4,
lineNumber: lineNumber,
lineStart: lineStart,
start: start,
end: index
};
}
// 3-character punctuators: === !== >>> <<= >>=
ch3 = ch4.substr(0, 3);
if (ch3 === '>>>' || ch3 === '<<=' || ch3 === '>>=') {
index += 3;
return {
type: Token.Punctuator,
value: ch3,
lineNumber: lineNumber,
lineStart: lineStart,
start: start,
end: index
};
}
// Other 2-character punctuators: ++ -- << >> && ||
ch2 = ch3.substr(0, 2);
if ((ch1 === ch2[1] && ('+-<>&|'.indexOf(ch1) >= 0)) || ch2 === '=>') {
index += 2;
return {
type: Token.Punctuator,
value: ch2,
lineNumber: lineNumber,
lineStart: lineStart,
start: start,
end: index
};
}
// 1-character punctuators: < > = ! + - * % & | ^ /
if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) {
++index;
return {
type: Token.Punctuator,
value: ch1,
lineNumber: lineNumber,
lineStart: lineStart,
start: start,
end: 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,
start: start,
end: index
};
}
function scanOctalLiteral(start) {
var number = '0' + source[index++];
while (index < length) {
if (!isOctalDigit(source[index])) {
break;
}
number += source[index++];
}
if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.NumericLiteral,
value: parseInt(number, 8),
octal: true,
lineNumber: lineNumber,
lineStart: lineStart,
start: start,
end: 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'.
if (number === '0') {
if (ch === 'x' || ch === 'X') {
++index;
return scanHexLiteral(start);
}
if (isOctalDigit(ch)) {
return scanOctalLiteral(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,
start: start,
end: index
};
}
// 7.8.4 String Literals
function scanStringLiteral() {
var str = '', quote, start, ch, code, unescaped, restore, octal = false, startLineNumber, startLineStart;
startLineNumber = lineNumber;
startLineStart = lineStart;
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 '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 'n':
str += '\n';
break;
case 'r':
str += '\r';
break;
case 't':
str += '\t';
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;
}
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,
startLineNumber: startLineNumber,
startLineStart: startLineStart,
lineNumber: lineNumber,
lineStart: lineStart,
start: start,
end: index
};
}
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,
start: start,
end: index
};
}
return {
literal: body.literal + flags.literal,
value: value,
regex: {
pattern: body.value,
flags: flags.value
},
start: start,
end: index
};
}
function collectRegex() {
var pos, loc, regex, token;
skipComment();
pos = index;
loc = {
start: {
line: lineNumber,
column: index - lineStart
}
};
regex = scanRegExp();
loc.end = {
line: lineNumber,
column: index - lineStart
};
if (!extra.tokenize) {
// 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 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 collectRegex();
}
if (prevToken.type === 'Punctuator') {
if (prevToken.value === ']') {
return scanPunctuator();
}
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 collectRegex();
}
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 collectRegex();
}
} else {
return scanPunctuator();
}
return scanPunctuator();
}
return collectRegex();
}
if (prevToken.type === 'Keyword' && prevToken.value !== 'this') {
return collectRegex();
}
return scanPunctuator();
}
function advance() {
var ch;
skipComment();
if (index >= length) {
return {
type: Token.EOF,
lineNumber: lineNumber,
lineStart: lineStart,
start: index,
end: index
};
}
ch = source.charCodeAt(index);
if (isIdentifierStart(ch)) {
return scanIdentifier();
}
// Very common: ( and ) and ;
if (ch === 0x28 || ch === 0x29 || ch === 0x3B) {
return scanPunctuator();
}
// String literal starts with single quote (U+0027) or double quote (U+0022).
if (ch === 0x27 || ch === 0x22) {
return scanStringLiteral();
}
// Dot (.) U+002E can also start a floating-point number, hence the need
// to check the next character.
if (ch === 0x2E) {
if (isDecimalDigit(source.charCodeAt(index + 1))) {
return scanNumericLiteral();
}
return scanPunctuator();
}
if (isDecimalDigit(ch)) {
return scanNumericLiteral();
}
// Slash (/) U+002F can also start a regex.
if (extra.tokenize && ch === 0x2F) {
return advanceSlash();
}
return scanPunctuator();
}
function collectToken() {
var loc, token, value, entry;
skipComment();
loc = {
start: {
line: lineNumber,
column: index - lineStart
}
};
token = advance();
loc.end = {
line: lineNumber,
column: index - lineStart
};
if (token.type !== Token.EOF) {
value = source.slice(token.start, token.end);
entry = {
type: TokenName[token.type],
value: value,
range: [token.start, token.end],
loc: loc
};
if (token.regex) {
entry.regex = {
pattern: token.regex.pattern,
flags: token.regex.flags
};
}
extra.tokens.push(entry);
}
return token;
}
function lex() {
var token;
token = lookahead;
index = token.end;
lineNumber = token.lineNumber;
lineStart = token.lineStart;
lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();
index = token.end;
lineNumber = token.lineNumber;
lineStart = token.lineStart;
return token;
}
function peek() {
var pos, line, start;
pos = index;
line = lineNumber;
start = lineStart;
lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();
index = pos;
lineNumber = line;
lineStart = start;
}
function Position() {
this.line = lineNumber;
this.column = index - lineStart;
}
function SourceLocation() {
this.start = new Position();
this.end = null;
}
function WrappingSourceLocation(startToken) {
if (startToken.type === Token.StringLiteral) {
this.start = {
line: startToken.startLineNumber,
column: startToken.start - startToken.startLineStart
};
} else {
this.start = {
line: startToken.lineNumber,
column: startToken.start - startToken.lineStart
};
}
this.end = null;
}
function Node() {
// Skip comment.
index = lookahead.start;
if (lookahead.type === Token.StringLiteral) {
lineNumber = lookahead.startLineNumber;
lineStart = lookahead.startLineStart;
} else {
lineNumber = lookahead.lineNumber;
lineStart = lookahead.lineStart;
}
if (extra.range) {
this.range = [index, 0];
}
if (extra.loc) {
this.loc = new SourceLocation();
}
}
function WrappingNode(startToken) {
if (extra.range) {
this.range = [startToken.start, 0];
}
if (extra.loc) {
this.loc = new WrappingSourceLocation(startToken);
}
}
WrappingNode.prototype = Node.prototype = {
finish: function () {
if (extra.range) {
this.range[1] = index;
}
if (extra.loc) {
this.loc.end = new Position();
if (extra.source) {
this.loc.source = extra.source;
}
}
},
finishArrayExpression: function (elements) {
this.type = Syntax.ArrayExpression;
this.elements = elements;
this.finish();
return this;
},
finishAssignmentExpression: function (operator, left, right) {
this.type = Syntax.AssignmentExpression;
this.operator = operator;
this.left = left;
this.right = right;
this.finish();
return this;
},
finishBinaryExpression: function (operator, left, right) {
this.type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression : Syntax.BinaryExpression;
this.operator = operator;
this.left = left;
this.right = right;
this.finish();
return this;
},
finishCallExpression: function (callee, args) {
this.type = Syntax.CallExpression;
this.callee = callee;
this.arguments = args;
this.finish();
return this;
},
finishConditionalExpression: function (test, consequent, alternate) {
this.type = Syntax.ConditionalExpression;
this.test = test;
this.consequent = consequent;
this.alternate = alternate;
this.finish();
return this;
},
finishExpressionStatement: function (expression) {
this.type = Syntax.ExpressionStatement;
this.expression = expression;
this.finish();
return this;
},
finishIdentifier: function (name) {
this.type = Syntax.Identifier;
this.name = name;
this.finish();
return this;
},
finishLiteral: function (token) {
this.type = Syntax.Literal;
this.value = token.value;
this.raw = source.slice(token.start, token.end);
if (token.regex) {
if (this.raw == '//') {
this.raw = '/(?:)/';
}
this.regex = token.regex;
}
this.finish();
return this;
},
finishMemberExpression: function (accessor, object, property) {
this.type = Syntax.MemberExpression;
this.computed = accessor === '[';
this.object = object;
this.property = property;
this.finish();
return this;
},
finishObjectExpression: function (properties) {
this.type = Syntax.ObjectExpression;
this.properties = properties;
this.finish();
return this;
},
finishProgram: function (body) {
this.type = Syntax.Program;
this.body = body;
this.finish();
return this;
},
finishProperty: function (kind, key, value) {
this.type = Syntax.Property;
this.key = key;
this.value = value;
this.kind = kind;
this.finish();
return this;
},
finishUnaryExpression: function (operator, argument) {
this.type = Syntax.UnaryExpression;
this.operator = operator;
this.argument = argument;
this.prefix = true;
this.finish();
return this;
}
};
// 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, index) {
assert(index < args.length, 'Message reference must be in range');
return args[index];
}
);
if (typeof token.lineNumber === 'number') {
error = new Error('Line ' + token.lineNumber + ': ' + msg);
error.index = token.start;
error.lineNumber = token.lineNumber;
error.column = token.start - 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) {
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);
}
// 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);
}
}
/**
* @name expectTolerant
* @description Quietly expect the given token value when in tolerant mode, otherwise delegates
* to <code>expect(value)</code>
* @param {String} value The value we are expecting the lookahead token to have
* @since 2.0
*/
function expectTolerant(value) {
if (extra.errors) {
var token = lookahead;
if (token.type !== Token.Punctuator && token.value !== value) {
throwErrorTolerant(token, Messages.UnexpectedToken, token.value);
} else {
lex();
}
} else {
expect(value);
}
}
// 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) {
return lookahead.type === Token.Keyword && lookahead.value === keyword;
}
function consumeSemicolon() {
var line;
// Catch the very common case first: immediately a semicolon (U+003B).
if (source.charCodeAt(index) === 0x3B || match(';')) {
lex();
return;
}
line = lineNumber;
skipComment();
if (lineNumber !== line) {
return;
}
if (lookahead.type !== Token.EOF && !match('}')) {
throwUnexpected(lookahead);
}
}
// 11.1.4 Array Initialiser
function parseArrayInitialiser() {
var elements = [], node = new Node();
expect('[');
while (!match(']')) {
if (match(',')) {
lex();
elements.push(null);
} else {
elements.push(parseAssignmentExpression());
if (!match(']')) {
expect(',');
}
}
}
lex();
return node.finishArrayExpression(elements);
}
// 11.1.5 Object Initialiser
function parseObjectPropertyKey() {
var token, node = new Node();
token = lex();
// 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 node.finishLiteral(token);
}
return node.finishIdentifier(token.value);
}
function parseObjectProperty() {
var token, key, id, value, node = new Node();
token = lookahead;
if (token.type === Token.Identifier) {
id = parseObjectPropertyKey();
expect(':');
value = parseAssignmentExpression();
return node.finishProperty('init', id, value);
}
if (token.type === Token.EOF || token.type === Token.Punctuator) {
throwUnexpected(token);
} else {
key = parseObjectPropertyKey();
expect(':');
value = parseAssignmentExpression();
return node.finishProperty('init', key, value);
}
}
function parseObjectInitialiser() {
var properties = [], property, name, key, kind, map = {}, toString = String, node = new Node();
expect('{');
while (!match('}')) {
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;
key = '$' + name;
if (Object.prototype.hasOwnProperty.call(map, key)) {
if (map[key] === 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 (map[key] & kind) {
throwErrorTolerant({}, Messages.AccessorGetSet);
}
}
map[key] |= kind;
} else {
map[key] = kind;
}
properties.push(property);
if (!match('}')) {
expectTolerant(',');
}
}
expect('}');
return node.finishObjectExpression(properties);
}
// 11.1.6 The Grouping Operator
function parseGroupExpression() {
var expr;
expect('(');
++state.parenthesisCount;
expr = parseExpression();
expect(')');
return expr;
}
// 11.1 Primary Expressions
var legalKeywords = {"if":1, "this":1};
function parsePrimaryExpression() {
var type, token, expr, node;
if (match('(')) {
return parseGroupExpression();
}
if (match('[')) {
return parseArrayInitialiser();
}
if (match('{')) {
return parseObjectInitialiser();
}
type = lookahead.type;
node = new Node();
if (type === Token.Identifier || legalKeywords[lookahead.value]) {
expr = node.finishIdentifier(lex().value);
} else if (type === Token.StringLiteral || type === Token.NumericLiteral) {
if (strict && lookahead.octal) {
throwErrorTolerant(lookahead, Messages.StrictOctalLiteral);
}
expr = node.finishLiteral(lex());
} else if (type === Token.Keyword) {
throw new Error("Disabled.");
} else if (type === Token.BooleanLiteral) {
token = lex();
token.value = (token.value === 'true');
expr = node.finishLiteral(token);
} else if (type === Token.NullLiteral) {
token = lex();
token.value = null;
expr = node.finishLiteral(token);
} else if (match('/') || match('/=')) {
if (typeof extra.tokens !== 'undefined') {
expr = node.finishLiteral(collectRegex());
} else {
expr = node.finishLiteral(scanRegExp());
}
peek();
} else {
throwUnexpected(lex());
}
return expr;
}
// 11.2 Left-Hand-Side Expressions
function parseArguments() {
var args = [];
expect('(');
if (!match(')')) {
while (index < length) {
args.push(parseAssignmentExpression());
if (match(')')) {
break;
}
expectTolerant(',');
}
}
expect(')');
return args;
}
function parseNonComputedProperty() {
var token, node = new Node();
token = lex();
if (!isIdentifierName(token)) {
throwUnexpected(token);
}
return node.finishIdentifier(token.value);
}
function parseNonComputedMember() {
expect('.');
return parseNonComputedProperty();
}
function parseComputedMember() {
var expr;
expect('[');
expr = parseExpression();
expect(']');
return expr;
}
function parseLeftHandSideExpressionAllowCall() {
var expr, args, property, startToken, previousAllowIn = state.allowIn;
startToken = lookahead;
state.allowIn = true;
expr = parsePrimaryExpression();
for (;;) {
if (match('.')) {
property = parseNonComputedMember();
expr = new WrappingNode(startToken).finishMemberExpression('.', expr, property);
} else if (match('(')) {
args = parseArguments();
expr = new WrappingNode(startToken).finishCallExpression(expr, args);
} else if (match('[')) {
property = parseComputedMember();
expr = new WrappingNode(startToken).finishMemberExpression('[', expr, property);
} else {
break;
}
}
state.allowIn = previousAllowIn;
return expr;
}
// 11.3 Postfix Expressions
function parsePostfixExpression() {
var expr = parseLeftHandSideExpressionAllowCall();
if (lookahead.type === Token.Punctuator) {
if ((match('++') || match('--')) && !peekLineTerminator()) {
throw new Error("Disabled.");
}
}
return expr;
}
// 11.4 Unary Operators
function parseUnaryExpression() {
var token, expr, startToken;
if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) {
expr = parsePostfixExpression();
} else if (match('++') || match('--')) {
throw new Error("Disabled.");
} else if (match('+') || match('-') || match('~') || match('!')) {
startToken = lookahead;
token = lex();
expr = parseUnaryExpression();
expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
} else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
throw new Error("Disabled.");
} else {
expr = parsePostfixExpression();
}
return expr;
}
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 marker, markers, expr, token, prec, stack, right, operator, left, i;
marker = lookahead;
left = parseUnaryExpression();
token = lookahead;
prec = binaryPrecedence(token, state.allowIn);
if (prec === 0) {
return left;
}
token.prec = prec;
lex();
markers = [marker, lookahead];
right = parseUnaryExpression();
stack = [left, token, right];
while ((prec = binaryPrecedence(lookahead, state.allowIn)) > 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();
markers.pop();
expr = new WrappingNode(markers[markers.length - 1]).finishBinaryExpression(operator, left, right);
stack.push(expr);
}
// Shift.
token = lex();
token.prec = prec;
stack.push(token);
markers.push(lookahead);
expr = parseUnaryExpression();
stack.push(expr);
}
// Final reduce to clean-up the stack.
i = stack.length - 1;
expr = stack[i];
markers.pop();
while (i > 1) {
expr = new WrappingNode(markers.pop()).finishBinaryExpression(stack[i - 1].value, stack[i - 2], expr);
i -= 2;
}
return expr;
}
// 11.12 Conditional Operator
function parseConditionalExpression() {
var expr, previousAllowIn, consequent, alternate, startToken;
startToken = lookahead;
expr = parseBinaryExpression();
if (match('?')) {
lex();
previousAllowIn = state.allowIn;
state.allowIn = true;
consequent = parseAssignmentExpression();
state.allowIn = previousAllowIn;
expect(':');
alternate = parseAssignmentExpression();
expr = new WrappingNode(startToken).finishConditionalExpression(expr, consequent, alternate);
}
return expr;
}
// 11.13 Assignment Operators
function parseAssignmentExpression() {
var oldParenthesisCount, token, expr, startToken;
oldParenthesisCount = state.parenthesisCount;
startToken = lookahead;
token = lookahead;
expr = parseConditionalExpression();
return expr;
}
// 11.14 Comma Operator
function parseExpression() {
var expr = parseAssignmentExpression();
if (match(',')) {
throw new Error("Disabled."); // no sequence expressions
}
return expr;
}
// 12.4 Expression Statement
function parseExpressionStatement(node) {
var expr = parseExpression();
consumeSemicolon();
return node.finishExpressionStatement(expr);
}
// 12 Statements
function parseStatement() {
var type = lookahead.type,
expr,
node;
if (type === Token.EOF) {
throwUnexpected(lookahead);
}
if (type === Token.Punctuator && lookahead.value === '{') {
throw new Error("Disabled."); // block statement
}
node = new Node();
if (type === Token.Punctuator) {
switch (lookahead.value) {
case ';':
throw new Error("Disabled."); // empty statement
case '(':
return parseExpressionStatement(node);
default:
break;
}
} else if (type === Token.Keyword) {
throw new Error("Disabled."); // keyword
}
expr = parseExpression();
consumeSemicolon();
return node.finishExpressionStatement(expr);
}
// 14 Program
function parseSourceElement() {
if (lookahead.type === Token.Keyword) {
switch (lookahead.value) {
case 'const':
case 'let':
throw new Error("Disabled.");
case 'function':
throw new Error("Disabled.");
default:
return parseStatement();
}
}
if (lookahead.type !== Token.EOF) {
return parseStatement();
}
}
function parseSourceElements() {
var sourceElement, sourceElements = [], token, directive, firstRestricted;
while (index < length) {
token = lookahead;
if (token.type !== Token.StringLiteral) {
break;
}
sourceElement = parseSourceElement();
sourceElements.push(sourceElement);
if (sourceElement.expression.type !== Syntax.Literal) {
// this is not directive
break;
}
directive = source.slice(token.start + 1, token.end - 1);
if (directive === 'use strict') {
strict = true;
if (firstRestricted) {
throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
}
} else {
if (!firstRestricted && token.octal) {
firstRestricted = token;
}
}
}
while (index < length) {
sourceElement = parseSourceElement();
if (typeof sourceElement === 'undefined') {
break;
}
sourceElements.push(sourceElement);
}
return sourceElements;
}
function parseProgram() {
var body, node;
skipComment();
peek();
node = new Node();
strict = true; // assume strict
body = parseSourceElements();
return node.finishProgram(body);
}
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 tokenize(code, options) {
var toString,
tokens;
toString = String;
if (typeof code !== 'string' && !(code instanceof String)) {
code = toString(code);
}
source = code;
index = 0;
lineNumber = (source.length > 0) ? 1 : 0;
lineStart = 0;
length = source.length;
lookahead = null;
state = {
allowIn: true,
labelSet: {},
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.tolerant === 'boolean' && options.tolerant) {
extra.errors = [];
}
try {
peek();
if (lookahead.type === Token.EOF) {
return extra.tokens;
}
lex();
while (lookahead.type !== Token.EOF) {
try {
lex();
} catch (lexError) {
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.errors !== 'undefined') {
tokens.errors = extra.errors;
}
} catch (e) {
throw e;
} finally {
extra = {};
}
return tokens;
}
function parse(code, options) {
var program, toString;
toString = String;
if (typeof code !== 'string' && !(code instanceof String)) {
code = toString(code);
}
source = code;
index = 0;
lineNumber = (source.length > 0) ? 1 : 0;
lineStart = 0;
length = source.length;
lookahead = null;
state = {
allowIn: true,
labelSet: {},
parenthesisCount: 0,
inFunctionBody: false,
inIteration: false,
inSwitch: false,
lastCommentStart: -1
};
extra = {};
if (typeof options !== 'undefined') {
extra.range = (typeof options.range === 'boolean') && options.range;
extra.loc = (typeof options.loc === 'boolean') && options.loc;
if (extra.loc && options.source !== null && options.source !== undefined) {
extra.source = toString(options.source);
}
if (typeof options.tokens === 'boolean' && options.tokens) {
extra.tokens = [];
}
if (typeof options.tolerant === 'boolean' && options.tolerant) {
extra.errors = [];
}
}
try {
program = parseProgram();
if (typeof extra.tokens !== 'undefined') {
filterTokenLocation();
program.tokens = extra.tokens;
}
if (typeof extra.errors !== 'undefined') {
program.errors = extra.errors;
}
} catch (e) {
throw e;
} finally {
extra = {};
}
return program;
}
return {
tokenize: tokenize,
parse: parse
};
})();
},{}],41:[function(require,module,exports){
arguments[4][25][0].apply(exports,arguments)
},{"dup":25}],42:[function(require,module,exports){
arguments[4][13][0].apply(exports,arguments)
},{"dup":13,"fs":2,"request":2,"sync-request":2,"url":2}],43:[function(require,module,exports){
var segmentCache = {},
bezierCache = {},
join = [].join;
// Copied from Inkscape svgtopdf, thanks!
function segments(x, y, rx, ry, large, sweep, rotateX, ox, oy) {
var key = join.call(arguments);
if (segmentCache[key]) {
return segmentCache[key];
}
var th = rotateX * (Math.PI/180);
var sin_th = Math.sin(th);
var cos_th = Math.cos(th);
rx = Math.abs(rx);
ry = Math.abs(ry);
var px = cos_th * (ox - x) * 0.5 + sin_th * (oy - y) * 0.5;
var py = cos_th * (oy - y) * 0.5 - sin_th * (ox - x) * 0.5;
var pl = (px*px) / (rx*rx) + (py*py) / (ry*ry);
if (pl > 1) {
pl = Math.sqrt(pl);
rx *= pl;
ry *= pl;
}
var a00 = cos_th / rx;
var a01 = sin_th / rx;
var a10 = (-sin_th) / ry;
var a11 = (cos_th) / ry;
var x0 = a00 * ox + a01 * oy;
var y0 = a10 * ox + a11 * oy;
var x1 = a00 * x + a01 * y;
var y1 = a10 * x + a11 * y;
var d = (x1-x0) * (x1-x0) + (y1-y0) * (y1-y0);
var sfactor_sq = 1 / d - 0.25;
if (sfactor_sq < 0) sfactor_sq = 0;
var sfactor = Math.sqrt(sfactor_sq);
if (sweep == large) sfactor = -sfactor;
var xc = 0.5 * (x0 + x1) - sfactor * (y1-y0);
var yc = 0.5 * (y0 + y1) + sfactor * (x1-x0);
var th0 = Math.atan2(y0-yc, x0-xc);
var th1 = Math.atan2(y1-yc, x1-xc);
var th_arc = th1-th0;
if (th_arc < 0 && sweep === 1){
th_arc += 2 * Math.PI;
} else if (th_arc > 0 && sweep === 0) {
th_arc -= 2 * Math.PI;
}
var segs = Math.ceil(Math.abs(th_arc / (Math.PI * 0.5 + 0.001)));
var result = [];
for (var i=0; i<segs; ++i) {
var th2 = th0 + i * th_arc / segs;
var th3 = th0 + (i+1) * th_arc / segs;
result[i] = [xc, yc, th2, th3, rx, ry, sin_th, cos_th];
}
return (segmentCache[key] = result);
}
function bezier(params) {
var key = join.call(params);
if (bezierCache[key]) {
return bezierCache[key];
}
var cx = params[0],
cy = params[1],
th0 = params[2],
th1 = params[3],
rx = params[4],
ry = params[5],
sin_th = params[6],
cos_th = params[7];
var a00 = cos_th * rx;
var a01 = -sin_th * ry;
var a10 = sin_th * rx;
var a11 = cos_th * ry;
var cos_th0 = Math.cos(th0);
var sin_th0 = Math.sin(th0);
var cos_th1 = Math.cos(th1);
var sin_th1 = Math.sin(th1);
var th_half = 0.5 * (th1 - th0);
var sin_th_h2 = Math.sin(th_half * 0.5);
var t = (8/3) * sin_th_h2 * sin_th_h2 / Math.sin(th_half);
var x1 = cx + cos_th0 - t * sin_th0;
var y1 = cy + sin_th0 + t * cos_th0;
var x3 = cx + cos_th1;
var y3 = cy + sin_th1;
var x2 = x3 + t * sin_th1;
var y2 = y3 - t * cos_th1;
return (bezierCache[key] = [
a00 * x1 + a01 * y1, a10 * x1 + a11 * y1,
a00 * x2 + a01 * y2, a10 * x2 + a11 * y2,
a00 * x3 + a01 * y3, a10 * x3 + a11 * y3
]);
}
module.exports = {
segments: segments,
bezier: bezier,
cache: {
segments: segmentCache,
bezier: bezierCache
}
};
},{}],44:[function(require,module,exports){
var arc = require('./arc');
module.exports = function(path, bounds) {
var current, // current instruction
previous = null,
x = 0, // current x
y = 0, // current y
controlX = 0, // current control point x
controlY = 0, // current control point y
tempX,
tempY,
tempControlX,
tempControlY,
i, len;
for (i=0, len=path.length; i<len; ++i) {
current = path[i];
switch (current[0]) { // command
case 'l': // lineto, relative
x += current[1];
y += current[2];
bounds.add(x, y);
break;
case 'L': // lineto, absolute
x = current[1];
y = current[2];
bounds.add(x, y);
break;
case 'h': // horizontal lineto, relative
x += current[1];
bounds.add(x, y);
break;
case 'H': // horizontal lineto, absolute
x = current[1];
bounds.add(x, y);
break;
case 'v': // vertical lineto, relative
y += current[1];
bounds.add(x, y);
break;
case 'V': // verical lineto, absolute
y = current[1];
bounds.add(x, y);
break;
case 'm': // moveTo, relative
x += current[1];
y += current[2];
bounds.add(x, y);
break;
case 'M': // moveTo, absolute
x = current[1];
y = current[2];
bounds.add(x, y);
break;
case 'c': // bezierCurveTo, relative
tempX = x + current[5];
tempY = y + current[6];
controlX = x + current[3];
controlY = y + current[4];
bounds.add(x + current[1], y + current[2]);
bounds.add(controlX, controlY);
bounds.add(tempX, tempY);
x = tempX;
y = tempY;
break;
case 'C': // bezierCurveTo, absolute
x = current[5];
y = current[6];
controlX = current[3];
controlY = current[4];
bounds.add(current[1], current[2]);
bounds.add(controlX, controlY);
bounds.add(x, y);
break;
case 's': // shorthand cubic bezierCurveTo, relative
// transform to absolute x,y
tempX = x + current[3];
tempY = y + current[4];
// calculate reflection of previous control points
controlX = 2 * x - controlX;
controlY = 2 * y - controlY;
bounds.add(controlX, controlY);
bounds.add(x + current[1], y + current[2]);
bounds.add(tempX, tempY);
// set control point to 2nd one of this command
// the first control point is assumed to be the reflection of
// the second control point on the previous command relative
// to the current point.
controlX = x + current[1];
controlY = y + current[2];
x = tempX;
y = tempY;
break;
case 'S': // shorthand cubic bezierCurveTo, absolute
tempX = current[3];
tempY = current[4];
// calculate reflection of previous control points
controlX = 2*x - controlX;
controlY = 2*y - controlY;
x = tempX;
y = tempY;
bounds.add(current[1], current[2]);
bounds.add(controlX, controlY);
bounds.add(tempX, tempY);
// set control point to 2nd one of this command
// the first control point is assumed to be the reflection of
// the second control point on the previous command relative
// to the current point.
controlX = current[1];
controlY = current[2];
break;
case 'q': // quadraticCurveTo, relative
// transform to absolute x,y
tempX = x + current[3];
tempY = y + current[4];
controlX = x + current[1];
controlY = y + current[2];
x = tempX;
y = tempY;
bounds.add(controlX, controlY);
bounds.add(tempX, tempY);
break;
case 'Q': // quadraticCurveTo, absolute
tempX = current[3];
tempY = current[4];
x = tempX;
y = tempY;
controlX = current[1];
controlY = current[2];
bounds.add(controlX, controlY);
bounds.add(tempX, tempY);
break;
case 't': // shorthand quadraticCurveTo, relative
// transform to absolute x,y
tempX = x + current[1];
tempY = y + current[2];
if (previous[0].match(/[QqTt]/) === null) {
// If there is no previous command or if the previous command was not a Q, q, T or t,
// assume the control point is coincident with the current point
controlX = x;
controlY = y;
}
else if (previous[0] === 't') {
// calculate reflection of previous control points for t
controlX = 2 * x - tempControlX;
controlY = 2 * y - tempControlY;
}
else if (previous[0] === 'q') {
// calculate reflection of previous control points for q
controlX = 2 * x - controlX;
controlY = 2 * y - controlY;
}
tempControlX = controlX;
tempControlY = controlY;
x = tempX;
y = tempY;
controlX = x + current[1];
controlY = y + current[2];
bounds.add(controlX, controlY);
bounds.add(tempX, tempY);
break;
case 'T':
tempX = current[1];
tempY = current[2];
// calculate reflection of previous control points
controlX = 2 * x - controlX;
controlY = 2 * y - controlY;
x = tempX;
y = tempY;
bounds.add(controlX, controlY);
bounds.add(tempX, tempY);
break;
case 'a':
boundArc(x, y, [
current[1],
current[2],
current[3],
current[4],
current[5],
current[6] + x,
current[7] + y
], bounds);
x += current[6];
y += current[7];
break;
case 'A':
boundArc(x, y, [
current[1],
current[2],
current[3],
current[4],
current[5],
current[6],
current[7]
], bounds);
x = current[6];
y = current[7];
break;
case 'z':
case 'Z':
break;
}
previous = current;
}
return bounds;
};
function boundArc(x, y, coords, bounds) {
var seg = arc.segments(
coords[5], // ex
coords[6], // ey
coords[0], // rx
coords[1], // ry
coords[3], // large
coords[4], // sweep
coords[2], // rot
x, y
);
for (var i=0; i<seg.length; ++i) {
var bez = arc.bezier(seg[i]);
bounds.add(bez[0], bez[1]);
bounds.add(bez[2], bez[3]);
bounds.add(bez[4], bez[5]);
}
}
},{"./arc":43}],45:[function(require,module,exports){
module.exports = {
parse: require('./parse'),
render: require('./render'),
bounds: require('./bounds')
};
},{"./bounds":44,"./parse":46,"./render":47}],46:[function(require,module,exports){
// Path parsing and rendering code adapted from fabric.js -- Thanks!
var cmdlen = { m:2, l:2, h:1, v:1, c:6, s:4, q:4, t:2, a:7 },
regexp = [/([MLHVCSQTAZmlhvcsqtaz])/g, /###/, /(\d)-/g, /\s|,|###/];
module.exports = function(pathstr) {
var result = [],
path,
curr,
chunks,
parsed, param,
cmd, len, i, j, n, m;
// First, break path into command sequence
path = pathstr
.slice()
.replace(regexp[0], '###$1')
.split(regexp[1])
.slice(1);
// Next, parse each command in turn
for (i=0, n=path.length; i<n; ++i) {
curr = path[i];
chunks = curr
.slice(1)
.trim()
.replace(regexp[2],'$1###-')
.split(regexp[3]);
cmd = curr.charAt(0);
parsed = [cmd];
for (j=0, m=chunks.length; j<m; ++j) {
if ((param = +chunks[j]) === param) { // not NaN
parsed.push(param);
}
}
len = cmdlen[cmd.toLowerCase()];
if (parsed.length-1 > len) {
for (j=1, m=parsed.length; j<m; j+=len) {
result.push([cmd].concat(parsed.slice(j, j+len)));
}
}
else {
result.push(parsed);
}
}
return result;
};
},{}],47:[function(require,module,exports){
var arc = require('./arc');
module.exports = function(g, path, l, t) {
var current, // current instruction
previous = null,
x = 0, // current x
y = 0, // current y
controlX = 0, // current control point x
controlY = 0, // current control point y
tempX,
tempY,
tempControlX,
tempControlY;
if (l == null) l = 0;
if (t == null) t = 0;
g.beginPath();
for (var i=0, len=path.length; i<len; ++i) {
current = path[i];
switch (current[0]) { // first letter
case 'l': // lineto, relative
x += current[1];
y += current[2];
g.lineTo(x + l, y + t);
break;
case 'L': // lineto, absolute
x = current[1];
y = current[2];
g.lineTo(x + l, y + t);
break;
case 'h': // horizontal lineto, relative
x += current[1];
g.lineTo(x + l, y + t);
break;
case 'H': // horizontal lineto, absolute
x = current[1];
g.lineTo(x + l, y + t);
break;
case 'v': // vertical lineto, relative
y += current[1];
g.lineTo(x + l, y + t);
break;
case 'V': // verical lineto, absolute
y = current[1];
g.lineTo(x + l, y + t);
break;
case 'm': // moveTo, relative
x += current[1];
y += current[2];
g.moveTo(x + l, y + t);
break;
case 'M': // moveTo, absolute
x = current[1];
y = current[2];
g.moveTo(x + l, y + t);
break;
case 'c': // bezierCurveTo, relative
tempX = x + current[5];
tempY = y + current[6];
controlX = x + current[3];
controlY = y + current[4];
g.bezierCurveTo(
x + current[1] + l, // x1
y + current[2] + t, // y1
controlX + l, // x2
controlY + t, // y2
tempX + l,
tempY + t
);
x = tempX;
y = tempY;
break;
case 'C': // bezierCurveTo, absolute
x = current[5];
y = current[6];
controlX = current[3];
controlY = current[4];
g.bezierCurveTo(
current[1] + l,
current[2] + t,
controlX + l,
controlY + t,
x + l,
y + t
);
break;
case 's': // shorthand cubic bezierCurveTo, relative
// transform to absolute x,y
tempX = x + current[3];
tempY = y + current[4];
// calculate reflection of previous control points
controlX = 2 * x - controlX;
controlY = 2 * y - controlY;
g.bezierCurveTo(
controlX + l,
controlY + t,
x + current[1] + l,
y + current[2] + t,
tempX + l,
tempY + t
);
// set control point to 2nd one of this command
// the first control point is assumed to be the reflection of
// the second control point on the previous command relative
// to the current point.
controlX = x + current[1];
controlY = y + current[2];
x = tempX;
y = tempY;
break;
case 'S': // shorthand cubic bezierCurveTo, absolute
tempX = current[3];
tempY = current[4];
// calculate reflection of previous control points
controlX = 2*x - controlX;
controlY = 2*y - controlY;
g.bezierCurveTo(
controlX + l,
controlY + t,
current[1] + l,
current[2] + t,
tempX + l,
tempY + t
);
x = tempX;
y = tempY;
// set control point to 2nd one of this command
// the first control point is assumed to be the reflection of
// the second control point on the previous command relative
// to the current point.
controlX = current[1];
controlY = current[2];
break;
case 'q': // quadraticCurveTo, relative
// transform to absolute x,y
tempX = x + current[3];
tempY = y + current[4];
controlX = x + current[1];
controlY = y + current[2];
g.quadraticCurveTo(
controlX + l,
controlY + t,
tempX + l,
tempY + t
);
x = tempX;
y = tempY;
break;
case 'Q': // quadraticCurveTo, absolute
tempX = current[3];
tempY = current[4];
g.quadraticCurveTo(
current[1] + l,
current[2] + t,
tempX + l,
tempY + t
);
x = tempX;
y = tempY;
controlX = current[1];
controlY = current[2];
break;
case 't': // shorthand quadraticCurveTo, relative
// transform to absolute x,y
tempX = x + current[1];
tempY = y + current[2];
if (previous[0].match(/[QqTt]/) === null) {
// If there is no previous command or if the previous command was not a Q, q, T or t,
// assume the control point is coincident with the current point
controlX = x;
controlY = y;
}
else if (previous[0] === 't') {
// calculate reflection of previous control points for t
controlX = 2 * x - tempControlX;
controlY = 2 * y - tempControlY;
}
else if (previous[0] === 'q') {
// calculate reflection of previous control points for q
controlX = 2 * x - controlX;
controlY = 2 * y - controlY;
}
tempControlX = controlX;
tempControlY = controlY;
g.quadraticCurveTo(
controlX + l,
controlY + t,
tempX + l,
tempY + t
);
x = tempX;
y = tempY;
controlX = x + current[1];
controlY = y + current[2];
break;
case 'T':
tempX = current[1];
tempY = current[2];
// calculate reflection of previous control points
controlX = 2 * x - controlX;
controlY = 2 * y - controlY;
g.quadraticCurveTo(
controlX + l,
controlY + t,
tempX + l,
tempY + t
);
x = tempX;
y = tempY;
break;
case 'a':
drawArc(g, x + l, y + t, [
current[1],
current[2],
current[3],
current[4],
current[5],
current[6] + x + l,
current[7] + y + t
]);
x += current[6];
y += current[7];
break;
case 'A':
drawArc(g, x + l, y + t, [
current[1],
current[2],
current[3],
current[4],
current[5],
current[6] + l,
current[7] + t
]);
x = current[6];
y = current[7];
break;
case 'z':
case 'Z':
g.closePath();
break;
}
previous = current;
}
};
function drawArc(g, x, y, coords) {
var seg = arc.segments(
coords[5], // end x
coords[6], // end y
coords[0], // radius x
coords[1], // radius y
coords[3], // large flag
coords[4], // sweep flag
coords[2], // rotation
x, y
);
for (var i=0; i<seg.length; ++i) {
var bez = arc.bezier(seg[i]);
g.bezierCurveTo.apply(g, bez);
}
}
},{"./arc":43}],48:[function(require,module,exports){
function Handler() {
this._active = null;
this._handlers = {};
}
var prototype = Handler.prototype;
prototype.initialize = function(el, pad, obj) {
this._el = el;
this._obj = obj || null;
return this.padding(pad);
};
prototype.element = function() {
return this._el;
};
prototype.padding = function(pad) {
this._padding = pad || {top:0, left:0, bottom:0, right:0};
return this;
};
prototype.scene = function(scene) {
if (!arguments.length) return this._scene;
this._scene = scene;
return this;
};
// add an event handler
// subclasses should override
prototype.on = function(/*type, handler*/) {};
// remove an event handler
// subclasses should override
prototype.off = function(/*type, handler*/) {};
// return an array with all registered event handlers
prototype.handlers = function() {
var h = this._handlers, a = [], k;
for (k in h) { a.push.apply(a, h[k]); }
return a;
};
prototype.eventName = function(name) {
var i = name.indexOf('.');
return i < 0 ? name : name.slice(0,i);
};
module.exports = Handler;
},{}],49:[function(require,module,exports){
function Renderer() {
this._el = null;
this._bgcolor = null;
}
var prototype = Renderer.prototype;
prototype.initialize = function(el, width, height, padding) {
this._el = el;
return this.resize(width, height, padding);
};
prototype.element = function() {
return this._el;
};
prototype.background = function(bgcolor) {
if (arguments.length === 0) return this._bgcolor;
this._bgcolor = bgcolor;
return this;
};
prototype.resize = function(width, height, padding) {
this._width = width;
this._height = height;
this._padding = padding || {top:0, left:0, bottom:0, right:0};
return this;
};
prototype.render = function(/*scene, items*/) {
return this;
};
module.exports = Renderer;
},{}],50:[function(require,module,exports){
var DOM = require('../../util/dom'),
Handler = require('../Handler'),
marks = require('./marks');
function CanvasHandler() {
Handler.call(this);
this._down = null;
this._touch = null;
this._first = true;
}
var base = Handler.prototype;
var prototype = (CanvasHandler.prototype = Object.create(base));
prototype.constructor = CanvasHandler;
prototype.initialize = function(el, pad, obj) {
// add event listeners
var canvas = this._canvas = DOM.find(el, 'canvas'),
that = this;
this.events.forEach(function(type) {
canvas.addEventListener(type, function(evt) {
if (prototype[type]) {
prototype[type].call(that, evt);
} else {
that.fire(type, evt);
}
});
});
this._rect = this._canvas.getBoundingClientRect();
return base.initialize.call(this, el, pad, obj);
};
prototype.canvas = function() {
return this._canvas;
};
// retrieve the current canvas context
prototype.context = function() {
return this._canvas.getContext('2d');
};
// supported events
prototype.events = [
'keydown',
'keypress',
'keyup',
'mousedown',
'mouseup',
'mousemove',
'mouseout',
'mouseover',
'click',
'dblclick',
'wheel',
'mousewheel',
'touchstart',
'touchmove',
'touchend'
];
// to keep firefox happy
prototype.DOMMouseScroll = function(evt) {
this.fire('mousewheel', evt);
};
prototype.mousemove = function(evt) {
var a = this._active,
p = this.pickEvent(evt);
if (p === a) {
// active item and picked item are the same
this.fire('mousemove', evt); // fire move
} else {
// active item and picked item are different
this.fire('mouseout', evt); // fire out for prior active item
this._active = p; // set new active item
this.fire('mouseover', evt); // fire over for new active item
this.fire('mousemove', evt); // fire move for new active item
}
};
prototype.mouseout = function(evt) {
this.fire('mouseout', evt);
this._active = null;
};
prototype.mousedown = function(evt) {
this._down = this._active;
this.fire('mousedown', evt);
};
prototype.click = function(evt) {
if (this._down === this._active) {
this.fire('click', evt);
this._down = null;
}
};
prototype.touchstart = function(evt) {
this._touch = this.pickEvent(evt.changedTouches[0]);
if (this._first) {
this._active = this._touch;
this._first = false;
}
this.fire('touchstart', evt, true);
};
prototype.touchmove = function(evt) {
this.fire('touchmove', evt, true);
};
prototype.touchend = function(evt) {
this.fire('touchend', evt, true);
this._touch = null;
};
// fire an event
prototype.fire = function(type, evt, touch) {
var a = touch ? this._touch : this._active,
h = this._handlers[type], i, len;
if (h) {
evt.vegaType = type;
for (i=0, len=h.length; i<len; ++i) {
h[i].handler.call(this._obj, evt, a);
}
}
};
// add an event handler
prototype.on = function(type, handler) {
var name = this.eventName(type),
h = this._handlers;
(h[name] || (h[name] = [])).push({
type: type,
handler: handler
});
return this;
};
// remove an event handler
prototype.off = function(type, handler) {
var name = this.eventName(type),
h = this._handlers[name], i;
if (!h) return;
for (i=h.length; --i>=0;) {
if (h[i].type !== type) continue;
if (!handler || h[i].handler === handler) h.splice(i, 1);
}
return this;
};
prototype.pickEvent = function(evt) {
var pad = this._padding, x, y;
return this.pick(this._scene,
x = (evt.clientX - this._rect.left),
y = (evt.clientY - this._rect.top),
x - pad.left, y - pad.top);
};
// find the scenegraph item at the current mouse position
// x, y -- the absolute x, y mouse coordinates on the canvas element
// gx, gy -- the relative coordinates within the current group
prototype.pick = function(scene, x, y, gx, gy) {
var g = this.context(),
mark = marks[scene.marktype];
return mark.pick.call(this, g, scene, x, y, gx, gy);
};
module.exports = CanvasHandler;
},{"../../util/dom":76,"../Handler":48,"./marks":57}],51:[function(require,module,exports){
var DOM = require('../../util/dom'),
Bounds = require('../../util/Bounds'),
ImageLoader = require('../../util/ImageLoader'),
Canvas = require('../../util/canvas'),
Renderer = require('../Renderer'),
marks = require('./marks');
function CanvasRenderer(loadConfig) {
Renderer.call(this);
this._loader = new ImageLoader(loadConfig);
}
var base = Renderer.prototype;
var prototype = (CanvasRenderer.prototype = Object.create(base));
prototype.constructor = CanvasRenderer;
prototype.initialize = function(el, width, height, padding) {
this._canvas = Canvas.instance(width, height);
if (el) {
DOM.clear(el, 0).appendChild(this._canvas);
this._canvas.setAttribute('class', 'marks');
}
return base.initialize.call(this, el, width, height, padding);
};
prototype.resize = function(width, height, padding) {
base.resize.call(this, width, height, padding);
Canvas.resize(this._canvas, this._width, this._height, this._padding);
return this;
};
prototype.canvas = function() {
return this._canvas;
};
prototype.context = function() {
return this._canvas ? this._canvas.getContext('2d') : null;
};
prototype.pendingImages = function() {
return this._loader.pending();
};
function clipToBounds(g, items) {
if (!items) return null;
var b = new Bounds(), i, n, item, mark, group;
for (i=0, n=items.length; i<n; ++i) {
item = items[i];
mark = item.mark;
group = mark.group;
item = marks[mark.marktype].nested ? mark : item;
b.union(translate(item.bounds, group));
if (item['bounds:prev']) {
b.union(translate(item['bounds:prev'], group));
}
}
b.round();
g.beginPath();
g.rect(b.x1, b.y1, b.width(), b.height());
g.clip();
return b;
}
function translate(bounds, group) {
if (group == null) return bounds;
var b = bounds.clone();
for (; group != null; group = group.mark.group) {
b.translate(group.x || 0, group.y || 0);
}
return b;
}
prototype.render = function(scene, items) {
var g = this.context(),
p = this._padding,
w = this._width + p.left + p.right,
h = this._height + p.top + p.bottom,
b;
// setup
this._scene = scene; // cache scene for async redraw
g.save();
b = clipToBounds(g, items);
this.clear(-p.left, -p.top, w, h);
// render
this.draw(g, scene, b);
// takedown
g.restore();
this._scene = null; // clear scene cache
return this;
};
prototype.draw = function(ctx, scene, bounds) {
var mark = marks[scene.marktype];
mark.draw.call(this, ctx, scene, bounds);
};
prototype.clear = function(x, y, w, h) {
var g = this.context();
g.clearRect(x, y, w, h);
if (this._bgcolor != null) {
g.fillStyle = this._bgcolor;
g.fillRect(x, y, w, h);
}
};
prototype.loadImage = function(uri) {
var renderer = this,
scene = this._scene;
return this._loader.loadImage(uri, function() {
renderer.renderAsync(scene);
});
};
prototype.renderAsync = function(scene) {
// TODO make safe for multiple scene rendering?
var renderer = this;
if (renderer._async_id) {
clearTimeout(renderer._async_id);
}
renderer._async_id = setTimeout(function() {
renderer.render(scene);
delete renderer._async_id;
}, 10);
};
module.exports = CanvasRenderer;
},{"../../util/Bounds":70,"../../util/ImageLoader":72,"../../util/canvas":75,"../../util/dom":76,"../Renderer":49,"./marks":57}],52:[function(require,module,exports){
module.exports = {
Handler: require('./CanvasHandler'),
Renderer: require('./CanvasRenderer')
};
},{"./CanvasHandler":50,"./CanvasRenderer":51}],53:[function(require,module,exports){
var util = require('./util');
var halfpi = Math.PI / 2;
function path(g, o) {
var x = o.x || 0,
y = o.y || 0,
ir = o.innerRadius || 0,
or = o.outerRadius || 0,
sa = (o.startAngle || 0) - halfpi,
ea = (o.endAngle || 0) - halfpi;
g.beginPath();
if (ir === 0) g.moveTo(x, y);
else g.arc(x, y, ir, sa, ea, 0);
g.arc(x, y, or, ea, sa, 1);
g.closePath();
}
module.exports = {
draw: util.drawAll(path),
pick: util.pickPath(path)
};
},{"./util":64}],54:[function(require,module,exports){
var util = require('./util'),
parse = require('../../../path/parse'),
render = require('../../../path/render'),
areaPath = require('../../../util/svg').path.area;
function path(g, items) {
var o = items[0],
p = o.pathCache || (o.pathCache = parse(areaPath(items)));
render(g, p);
}
function pick(g, scene, x, y, gx, gy) {
var items = scene.items,
b = scene.bounds;
if (!items || !items.length || b && !b.contains(gx, gy)) {
return null;
}
if (g.pixelratio != null && g.pixelratio !== 1) {
x *= g.pixelratio;
y *= g.pixelratio;
}
return hit(g, items, x, y) ? items[0] : null;
}
var hit = util.testPath(path);
module.exports = {
draw: util.drawOne(path),
pick: pick,
nested: true
};
},{"../../../path/parse":46,"../../../path/render":47,"../../../util/svg":78,"./util":64}],55:[function(require,module,exports){
var util = require('./util'),
rect = require('./rect');
function draw(g, scene, bounds) {
if (!scene.items || !scene.items.length) return;
var groups = scene.items,
renderer = this,
group, items, axes, legends, gx, gy, i, n, j, m;
rect.draw.call(renderer, g, scene, bounds);
for (i=0, n=groups.length; i<n; ++i) {
group = groups[i];
axes = group.axisItems || [];
items = group.items || [];
legends = group.legendItems || [];
gx = group.x || 0;
gy = group.y || 0;
// render group contents
g.save();
g.translate(gx, gy);
if (group.clip) {
g.beginPath();
g.rect(0, 0, group.width || 0, group.height || 0);
g.clip();
}
if (bounds) bounds.translate(-gx, -gy);
for (j=0, m=axes.length; j<m; ++j) {
if (axes[j].layer === 'back') {
renderer.draw(g, axes[j], bounds);
}
}
for (j=0, m=items.length; j<m; ++j) {
renderer.draw(g, items[j], bounds);
}
for (j=0, m=axes.length; j<m; ++j) {
if (axes[j].layer !== 'back') {
renderer.draw(g, axes[j], bounds);
}
}
for (j=0, m=legends.length; j<m; ++j) {
renderer.draw(g, legends[j], bounds);
}
if (bounds) bounds.translate(gx, gy);
g.restore();
}
}
function hit(g, o) {
return o.fill || o.stroke;
}
function pick(g, scene, x, y, gx, gy) {
if (scene.bounds && !scene.bounds.contains(gx, gy)) {
return null;
}
var items = scene.items || [],
subscene, group, hits, dx, dy, i, j;
for (i=items.length; --i>=0;) {
group = items[i];
dx = group.x || 0;
dy = group.y || 0;
g.save();
g.translate(dx, dy);
for (j=group.items.length; --j >= 0;) {
subscene = group.items[j];
if (subscene.interactive === false) continue;
hits = this.pick(subscene, x, y, gx-dx, gy-dy);
if (hits) {
g.restore();
return hits;
}
}
g.restore();
}
return scene.interactive !== false ? pickSelf(g, scene, x, y, gx, gy) : null;
}
var pickSelf = util.pick(hit);
module.exports = {
draw: draw,
pick: pick
};
},{"./rect":60,"./util":64}],56:[function(require,module,exports){
var util = require('./util');
function draw(g, scene, bounds) {
if (!scene.items || !scene.items.length) return;
var renderer = this,
items = scene.items, o;
for (var i=0, len=items.length; i<len; ++i) {
o = items[i];
if (bounds && !bounds.intersects(o.bounds))
continue; // bounds check
if (!(o.image && o.image.url === o.url)) {
o.image = renderer.loadImage(o.url);
o.image.url = o.url;
}
var x = o.x || 0,
y = o.y || 0,
w = o.width || (o.image && o.image.width) || 0,
h = o.height || (o.image && o.image.height) || 0,
opac;
x = x - (o.align==='center' ? w/2 : o.align==='right' ? w : 0);
y = y - (o.baseline==='middle' ? h/2 : o.baseline==='bottom' ? h : 0);
if (o.image.loaded) {
g.globalAlpha = (opac = o.opacity) != null ? opac : 1;
g.drawImage(o.image, x, y, w, h);
}
}
}
module.exports = {
draw: draw,
pick: util.pick()
};
},{"./util":64}],57:[function(require,module,exports){
module.exports = {
arc: require('./arc'),
area: require('./area'),
group: require('./group'),
image: require('./image'),
line: require('./line'),
path: require('./path'),
rect: require('./rect'),
rule: require('./rule'),
symbol: require('./symbol'),
text: require('./text')
};
},{"./arc":53,"./area":54,"./group":55,"./image":56,"./line":58,"./path":59,"./rect":60,"./rule":61,"./symbol":62,"./text":63}],58:[function(require,module,exports){
var util = require('./util'),
parse = require('../../../path/parse'),
render = require('../../../path/render'),
linePath = require('../../../util/svg').path.line;
function path(g, items) {
var o = items[0],
p = o.pathCache || (o.pathCache = parse(linePath(items)));
render(g, p);
}
function pick(g, scene, x, y, gx, gy) {
var items = scene.items,
b = scene.bounds;
if (!items || !items.length || b && !b.contains(gx, gy)) {
return null;
}
if (g.pixelratio != null && g.pixelratio !== 1) {
x *= g.pixelratio;
y *= g.pixelratio;
}
return hit(g, items, x, y) ? items[0] : null;
}
var hit = util.testPath(path, false);
module.exports = {
draw: util.drawOne(path),
pick: pick,
nested: true
};
},{"../../../path/parse":46,"../../../path/render":47,"../../../util/svg":78,"./util":64}],59:[function(require,module,exports){
var util = require('./util'),
parse = require('../../../path/parse'),
render = require('../../../path/render');
function path(g, o) {
if (o.path == null) return true;
var p = o.pathCache || (o.pathCache = parse(o.path));
render(g, p, o.x, o.y);
}
module.exports = {
draw: util.drawAll(path),
pick: util.pickPath(path)
};
},{"../../../path/parse":46,"../../../path/render":47,"./util":64}],60:[function(require,module,exports){
var util = require('./util');
function draw(g, scene, bounds) {
if (!scene.items || !scene.items.length) return;
var items = scene.items,
o, opac, x, y, w, h;
for (var i=0, len=items.length; i<len; ++i) {
o = items[i];
if (bounds && !bounds.intersects(o.bounds))
continue; // bounds check
opac = o.opacity == null ? 1 : o.opacity;
if (opac === 0) continue;
x = o.x || 0;
y = o.y || 0;
w = o.width || 0;
h = o.height || 0;
if (o.fill && util.fill(g, o, opac)) {
g.fillRect(x, y, w, h);
}
if (o.stroke && util.stroke(g, o, opac)) {
g.strokeRect(x, y, w, h);
}
}
}
module.exports = {
draw: draw,
pick: util.pick()
};
},{"./util":64}],61:[function(require,module,exports){
var util = require('./util');
function draw(g, scene, bounds) {
if (!scene.items || !scene.items.length) return;
var items = scene.items,
o, opac, x1, y1, x2, y2;
for (var i=0, len=items.length; i<len; ++i) {
o = items[i];
if (bounds && !bounds.intersects(o.bounds))
continue; // bounds check
opac = o.opacity == null ? 1 : o.opacity;
if (opac === 0) continue;
x1 = o.x || 0;
y1 = o.y || 0;
x2 = o.x2 != null ? o.x2 : x1;
y2 = o.y2 != null ? o.y2 : y1;
if (o.stroke && util.stroke(g, o, opac)) {
g.beginPath();
g.moveTo(x1, y1);
g.lineTo(x2, y2);
g.stroke();
}
}
}
function stroke(g, o) {
var x1 = o.x || 0,
y1 = o.y || 0,
x2 = o.x2 != null ? o.x2 : x1,
y2 = o.y2 != null ? o.y2 : y1,
lw = o.strokeWidth,
lc = o.strokeCap;
g.lineWidth = lw != null ? lw : 1;
g.lineCap = lc != null ? lc : 'butt';
g.beginPath();
g.moveTo(x1, y1);
g.lineTo(x2, y2);
}
function hit(g, o, x, y) {
if (!g.isPointInStroke) return false;
stroke(g, o);
return g.isPointInStroke(x, y);
}
module.exports = {
draw: draw,
pick: util.pick(hit)
};
},{"./util":64}],62:[function(require,module,exports){
var util = require('./util');
var sqrt3 = Math.sqrt(3),
tan30 = Math.tan(30 * Math.PI / 180);
function path(g, o) {
var size = o.size != null ? o.size : 100,
x = o.x, y = o.y, r, t, rx, ry;
g.beginPath();
if (o.shape == null || o.shape === 'circle') {
r = Math.sqrt(size / Math.PI);
g.arc(x, y, r, 0, 2*Math.PI, 0);
g.closePath();
return;
}
switch (o.shape) {
case 'cross':
r = Math.sqrt(size / 5) / 2;
t = 3*r;
g.moveTo(x-t, y-r);
g.lineTo(x-r, y-r);
g.lineTo(x-r, y-t);
g.lineTo(x+r, y-t);
g.lineTo(x+r, y-r);
g.lineTo(x+t, y-r);
g.lineTo(x+t, y+r);
g.lineTo(x+r, y+r);
g.lineTo(x+r, y+t);
g.lineTo(x-r, y+t);
g.lineTo(x-r, y+r);
g.lineTo(x-t, y+r);
break;
case 'diamond':
ry = Math.sqrt(size / (2 * tan30));
rx = ry * tan30;
g.moveTo(x, y-ry);
g.lineTo(x+rx, y);
g.lineTo(x, y+ry);
g.lineTo(x-rx, y);
break;
case 'square':
t = Math.sqrt(size);
r = t / 2;
g.rect(x-r, y-r, t, t);
break;
case 'triangle-down':
rx = Math.sqrt(size / sqrt3);
ry = rx * sqrt3 / 2;
g.moveTo(x, y+ry);
g.lineTo(x+rx, y-ry);
g.lineTo(x-rx, y-ry);
break;
case 'triangle-up':
rx = Math.sqrt(size / sqrt3);
ry = rx * sqrt3 / 2;
g.moveTo(x, y-ry);
g.lineTo(x+rx, y+ry);
g.lineTo(x-rx, y+ry);
}
g.closePath();
}
module.exports = {
draw: util.drawAll(path),
pick: util.pickPath(path)
};
},{"./util":64}],63:[function(require,module,exports){
var Bounds = require('../../../util/Bounds'),
textBounds = require('../../../util/bound').text,
font = require('../../../util/font'),
util = require('./util'),
tempBounds = new Bounds();
function draw(g, scene, bounds) {
if (!scene.items || !scene.items.length) return;
var items = scene.items,
o, opac, x, y, r, t;
for (var i=0, len=items.length; i<len; ++i) {
o = items[i];
if (bounds && !bounds.intersects(o.bounds))
continue; // bounds check
opac = o.opacity == null ? 1 : o.opacity;
if (opac === 0) continue;
g.font = font.string(o);
g.textAlign = o.align || 'left';
x = (o.x || 0);
y = (o.y || 0);
if ((r = o.radius)) {
t = (o.theta || 0) - Math.PI/2;
x += r * Math.cos(t);
y += r * Math.sin(t);
}
if (o.angle) {
g.save();
g.translate(x, y);
g.rotate(o.angle * Math.PI/180);
x = y = 0; // reset x, y
}
x += (o.dx || 0);
y += (o.dy || 0) + font.offset(o);
if (o.fill && util.fill(g, o, opac)) {
g.fillText(o.text, x, y);
}
if (o.stroke && util.stroke(g, o, opac)) {
g.strokeText(o.text, x, y);
}
if (o.angle) g.restore();
}
}
function hit(g, o, x, y, gx, gy) {
if (o.fontSize <= 0) return false;
if (!o.angle) return true; // bounds sufficient if no rotation
// project point into space of unrotated bounds
var b = textBounds(o, tempBounds, true),
a = -o.angle * Math.PI / 180,
cos = Math.cos(a),
sin = Math.sin(a),
ox = o.x,
oy = o.y,
px = cos*gx - sin*gy + (ox - ox*cos + oy*sin),
py = sin*gx + cos*gy + (oy - ox*sin - oy*cos);
return b.contains(px, py);
}
module.exports = {
draw: draw,
pick: util.pick(hit)
};
},{"../../../util/Bounds":70,"../../../util/bound":74,"../../../util/font":77,"./util":64}],64:[function(require,module,exports){
function drawPathOne(path, g, o, items) {
if (path(g, items)) return;
var opac = o.opacity == null ? 1 : o.opacity;
if (opac===0) return;
if (o.fill && fill(g, o, opac)) { g.fill(); }
if (o.stroke && stroke(g, o, opac)) { g.stroke(); }
}
function drawPathAll(path, g, scene, bounds) {
var i, len, item;
for (i=0, len=scene.items.length; i<len; ++i) {
item = scene.items[i];
if (!bounds || bounds.intersects(item.bounds)) {
drawPathOne(path, g, item, item);
}
}
}
function drawAll(pathFunc) {
return function(g, scene, bounds) {
drawPathAll(pathFunc, g, scene, bounds);
};
}
function drawOne(pathFunc) {
return function(g, scene, bounds) {
if (!scene.items.length) return;
if (!bounds || bounds.intersects(scene.bounds)) {
drawPathOne(pathFunc, g, scene.items[0], scene.items);
}
};
}
function pick(test) {
if (!test) test = function() { return true; };
return function(g, scene, x, y, gx, gy) {
if (!scene.items.length) return null;
var o, b, i;
if (g.pixelratio != null && g.pixelratio !== 1) {
x *= g.pixelratio;
y *= g.pixelratio;
}
for (i=scene.items.length; --i >= 0;) {
o = scene.items[i]; b = o.bounds;
// first hit test against bounding box
if ((b && !b.contains(gx, gy)) || !b) continue;
// if in bounding box, perform more careful test
if (test(g, o, x, y, gx, gy)) return o;
}
return null;
};
}
function testPath(path, fill) {
return function(g, o, x, y) {
var item = Array.isArray(o) ? o[0] : o,
stroke = item.stroke && g.isPointInStroke, lw, lc;
fill = (fill == null) ? item.fill : fill;
if (stroke) {
lw = item.strokeWidth;
lc = item.strokeCap;
g.lineWidth = lw != null ? lw : 1;
g.lineCap = lc != null ? lc : 'butt';
}
return path(g, o) ? false :
(fill && g.isPointInPath(x, y)) ||
(stroke && g.isPointInStroke(x, y));
};
}
function pickPath(path) {
return pick(testPath(path));
}
function fill(g, o, opacity) {
opacity *= (o.fillOpacity==null ? 1 : o.fillOpacity);
if (opacity > 0) {
g.globalAlpha = opacity;
g.fillStyle = color(g, o, o.fill);
return true;
} else {
return false;
}
}
function stroke(g, o, opacity) {
var lw = (lw = o.strokeWidth) != null ? lw : 1, lc;
if (lw <= 0) return false;
opacity *= (o.strokeOpacity==null ? 1 : o.strokeOpacity);
if (opacity > 0) {
g.globalAlpha = opacity;
g.strokeStyle = color(g, o, o.stroke);
g.lineWidth = lw;
g.lineCap = (lc = o.strokeCap) != null ? lc : 'butt';
g.vgLineDash(o.strokeDash || null);
g.vgLineDashOffset(o.strokeDashOffset || 0);
return true;
} else {
return false;
}
}
function color(g, o, value) {
return (value.id) ?
gradient(g, value, o.bounds) :
value;
}
function gradient(g, p, b) {
var w = b.width(),
h = b.height(),
x1 = b.x1 + p.x1 * w,
y1 = b.y1 + p.y1 * h,
x2 = b.x1 + p.x2 * w,
y2 = b.y1 + p.y2 * h,
grad = g.createLinearGradient(x1, y1, x2, y2),
stop = p.stops,
i, n;
for (i=0, n=stop.length; i<n; ++i) {
grad.addColorStop(stop[i].offset, stop[i].color);
}
return grad;
}
module.exports = {
drawOne: drawOne,
drawAll: drawAll,
pick: pick,
pickPath: pickPath,
testPath: testPath,
stroke: stroke,
fill: fill,
color: color,
gradient: gradient
};
},{}],65:[function(require,module,exports){
var DOM = require('../../util/dom'),
Handler = require('../Handler');
function SVGHandler() {
Handler.call(this);
}
var base = Handler.prototype;
var prototype = (SVGHandler.prototype = Object.create(base));
prototype.constructor = SVGHandler;
prototype.initialize = function(el, pad, obj) {
this._svg = DOM.find(el, 'svg');
return base.initialize.call(this, el, pad, obj);
};
prototype.svg = function() {
return this._svg;
};
// wrap an event listener for the SVG DOM
prototype.listener = function(handler) {
var that = this;
return function(evt) {
var target = evt.target,
item = target.__data__;
evt.vegaType = evt.type;
item = Array.isArray(item) ? item[0] : item;
handler.call(that._obj, evt, item);
};
};
// add an event handler
prototype.on = function(type, handler) {
var name = this.eventName(type),
svg = this._svg,
h = this._handlers,
x = {
type: type,
handler: handler,
listener: this.listener(handler)
};
(h[name] || (h[name] = [])).push(x);
svg.addEventListener(name, x.listener);
return this;
};
// remove an event handler
prototype.off = function(type, handler) {
var name = this.eventName(type),
svg = this._svg,
h = this._handlers[name], i;
if (!h) return;
for (i=h.length; --i>=0;) {
if (h[i].type === type && !handler || h[i].handler === handler) {
svg.removeEventListener(name, h[i].listener);
h.splice(i, 1);
}
}
return this;
};
module.exports = SVGHandler;
},{"../../util/dom":76,"../Handler":48}],66:[function(require,module,exports){
var ImageLoader = require('../../util/ImageLoader'),
Renderer = require('../Renderer'),
font = require('../../util/font'),
DOM = require('../../util/dom'),
SVG = require('../../util/svg'),
ns = SVG.metadata.xmlns,
marks = require('./marks');
function SVGRenderer(loadConfig) {
Renderer.call(this);
this._loader = new ImageLoader(loadConfig);
this._dirtyID = 0;
}
var base = Renderer.prototype;
var prototype = (SVGRenderer.prototype = Object.create(base));
prototype.constructor = SVGRenderer;
prototype.initialize = function(el, width, height, padding) {
if (el) {
this._svg = DOM.child(el, 0, 'svg', ns, 'marks');
DOM.clear(el, 1);
// set the svg root group
this._root = DOM.child(this._svg, 0, 'g', ns);
DOM.clear(this._svg, 1);
}
// create the svg definitions cache
this._defs = {
clip_id: 1,
gradient: {},
clipping: {}
};
// set background color if defined
this.background(this._bgcolor);
return base.initialize.call(this, el, width, height, padding);
};
prototype.background = function(bgcolor) {
if (arguments.length && this._svg) {
this._svg.style.setProperty('background-color', bgcolor);
}
return base.background.apply(this, arguments);
};
prototype.resize = function(width, height, padding) {
base.resize.call(this, width, height, padding);
if (this._svg) {
var w = this._width,
h = this._height,
p = this._padding;
this._svg.setAttribute('width', w + p.left + p.right);
this._svg.setAttribute('height', h + p.top + p.bottom);
this._root.setAttribute('transform', 'translate('+p.left+','+p.top+')');
}
return this;
};
prototype.svg = function() {
if (!this._svg) return null;
var attr = {
'class': 'marks',
'width': this._width + this._padding.left + this._padding.right,
'height': this._height + this._padding.top + this._padding.bottom,
};
for (var key in SVG.metadata) {
attr[key] = SVG.metadata[key];
}
return DOM.openTag('svg', attr) + this._svg.innerHTML + DOM.closeTag('svg');
};
prototype.imageURL = function(url) {
return this._loader.imageURL(url);
};
// -- Render entry point --
prototype.render = function(scene, items) {
if (this._dirtyCheck(items)) {
if (this._dirtyAll) this._resetDefs();
this.draw(this._root, scene, -1);
DOM.clear(this._root, 1);
}
this.updateDefs();
return this;
};
prototype.draw = function(el, scene, index) {
this.drawMark(el, scene, index, marks[scene.marktype]);
};
// -- Manage SVG definitions ('defs') block --
prototype.updateDefs = function() {
var svg = this._svg,
defs = this._defs,
el = defs.el,
index = 0, id;
for (id in defs.gradient) {
if (!el) el = (defs.el = DOM.child(svg, 0, 'defs', ns));
updateGradient(el, defs.gradient[id], index++);
}
for (id in defs.clipping) {
if (!el) el = (defs.el = DOM.child(svg, 0, 'defs', ns));
updateClipping(el, defs.clipping[id], index++);
}
// clean-up
if (el) {
if (index === 0) {
svg.removeChild(el);
defs.el = null;
} else {
DOM.clear(el, index);
}
}
};
function updateGradient(el, grad, index) {
var i, n, stop;
el = DOM.child(el, index, 'linearGradient', ns);
el.setAttribute('id', grad.id);
el.setAttribute('x1', grad.x1);
el.setAttribute('x2', grad.x2);
el.setAttribute('y1', grad.y1);
el.setAttribute('y2', grad.y2);
for (i=0, n=grad.stops.length; i<n; ++i) {
stop = DOM.child(el, i, 'stop', ns);
stop.setAttribute('offset', grad.stops[i].offset);
stop.setAttribute('stop-color', grad.stops[i].color);
}
DOM.clear(el, i);
}
function updateClipping(el, clip, index) {
var rect;
el = DOM.child(el, index, 'clipPath', ns);
el.setAttribute('id', clip.id);
rect = DOM.child(el, 0, 'rect', ns);
rect.setAttribute('x', 0);
rect.setAttribute('y', 0);
rect.setAttribute('width', clip.width);
rect.setAttribute('height', clip.height);
}
prototype._resetDefs = function() {
var def = this._defs;
def.clip_id = 1;
def.gradient = {};
def.clipping = {};
};
// -- Manage rendering of items marked as dirty --
prototype.isDirty = function(item) {
return this._dirtyAll || item.dirty === this._dirtyID;
};
prototype._dirtyCheck = function(items) {
this._dirtyAll = true;
if (!items) return true;
var id = ++this._dirtyID,
item, mark, type, mdef, i, n, o;
for (i=0, n=items.length; i<n; ++i) {
item = items[i];
mark = item.mark;
if (mark.marktype !== type) {
// memoize mark instance lookup
type = mark.marktype;
mdef = marks[type];
}
if (item.status === 'exit') { // EXIT
if (item._svg) {
if (mdef.nest && item.mark.items.length) {
// if nested mark with remaining points, update instead
this._update(mdef, item._svg, item.mark.items[0]);
o = item.mark.items[0];
o._svg = item._svg;
o._update = id;
} else {
// otherwise remove from DOM
DOM.remove(item._svg);
}
item._svg = null;
}
continue;
}
item = (mdef.nest ? mark.items[0] : item);
if (item._update === id) { // Already processed
continue;
} else if (item._svg) { // UPDATE
this._update(mdef, item._svg, item);
} else { // ENTER
this._dirtyAll = false;
dirtyParents(item, id);
}
item._update = id;
}
return !this._dirtyAll;
};
function dirtyParents(item, id) {
for (; item && item.dirty !== id; item=item.mark.group) {
item.dirty = id;
if (item.mark && item.mark.dirty !== id) {
item.mark.dirty = id;
} else return;
}
}
// -- Construct & maintain scenegraph to SVG mapping ---
// Draw a mark container.
prototype.drawMark = function(el, scene, index, mdef) {
if (!this.isDirty(scene)) return;
var items = mdef.nest ?
(scene.items && scene.items.length ? [scene.items[0]] : []) :
scene.items || [],
events = scene.interactive === false ? 'none' : null,
isGroup = (mdef.tag === 'g'),
className = DOM.cssClass(scene),
p, i, n, c, d, insert;
p = DOM.child(el, index+1, 'g', ns, className);
p.setAttribute('class', className);
scene._svg = p;
if (!isGroup && events) {
p.style.setProperty('pointer-events', events);
}
for (i=0, n=items.length; i<n; ++i) {
if (this.isDirty(d = items[i])) {
insert = !(this._dirtyAll || d._svg);
c = insert ? bind(p, mdef, d, i, true)
: (p.childNodes[i] || bind(p, mdef, d, i));
this._update(mdef, c, d);
if (isGroup) {
if (insert) this._dirtyAll = true;
this._recurse(c, d);
if (insert) this._dirtyAll = false;
}
}
}
DOM.clear(p, i);
return p;
};
// Recursively process group contents.
prototype._recurse = function(el, group) {
var items = group.items || [],
legends = group.legendItems || [],
axes = group.axisItems || [],
idx = 0, j, m;
for (j=0, m=axes.length; j<m; ++j) {
if (axes[j].layer === 'back') {
this.drawMark(el, axes[j], idx++, marks.group);
}
}
for (j=0, m=items.length; j<m; ++j) {
this.draw(el, items[j], idx++);
}
for (j=0, m=axes.length; j<m; ++j) {
if (axes[j].layer !== 'back') {
this.drawMark(el, axes[j], idx++, marks.group);
}
}
for (j=0, m=legends.length; j<m; ++j) {
this.drawMark(el, legends[j], idx++, marks.group);
}
// remove any extraneous DOM elements
DOM.clear(el, 1 + idx);
};
// Bind a scenegraph item to an SVG DOM element.
// Create new SVG elements as needed.
function bind(el, mdef, item, index, insert) {
// create svg element, bind item data for D3 compatibility
var node = DOM.child(el, index, mdef.tag, ns, null, insert);
node.__data__ = item;
node.__values__ = {fill: 'default'};
// create background rect
if (mdef.tag === 'g') {
var bg = DOM.child(node, 0, 'rect', ns, 'background');
bg.__data__ = item;
}
// add pointer from scenegraph item to svg element
return (item._svg = node);
}
// -- Set attributes & styles on SVG elements ---
var href = (typeof window !== 'undefined' ? window.location.href : ''),
element = null, // temp var for current SVG element
values = null; // temp var for current values hash
// Extra configuration for certain mark types
var mark_extras = {
group: function(mdef, el, item) {
element = el.childNodes[0];
values = el.__values__; // use parent's values hash
mdef.background(emit, item, this);
var value = item.mark.interactive === false ? 'none' : null;
if (value !== values.events) {
element.style.setProperty('pointer-events', value);
values.events = value;
}
},
text: function(mdef, el, item) {
if (item.text !== values.text) {
el.textContent = item.text || '';
values.text = item.text;
}
var str = font.string(item);
if (str !== values.font) {
el.style.setProperty('font', str);
values.font = str;
}
}
};
prototype._update = function(mdef, el, item) {
// set dom element and values cache
// provides access to emit method
element = el;
values = el.__values__;
// apply svg attributes
mdef.attr(emit, item, this);
// some marks need special treatment
var extra = mark_extras[mdef.type];
if (extra) extra(mdef, el, item);
// apply svg css styles
// note: element may be modified by 'extra' method
this.style(element, item);
};
function emit(name, value, ns) {
// early exit if value is unchanged
if (value === values[name]) return;
if (value != null) {
// if value is provided, update DOM attribute
if (ns) {
element.setAttributeNS(ns, name, value);
} else {
element.setAttribute(name, value);
}
} else {
// else remove DOM attribute
if (ns) {
element.removeAttributeNS(ns, name);
} else {
element.removeAttribute(name);
}
}
// note current value for future comparison
values[name] = value;
}
prototype.style = function(el, o) {
if (o == null) return;
var i, n, prop, name, value;
for (i=0, n=SVG.styleProperties.length; i<n; ++i) {
prop = SVG.styleProperties[i];
value = o[prop];
if (value === values[prop]) continue;
name = SVG.styles[prop];
if (value == null) {
if (name === 'fill') {
el.style.setProperty(name, 'none');
} else {
el.style.removeProperty(name);
}
} else {
if (value.id) {
// ensure definition is included
this._defs.gradient[value.id] = value;
value = 'url(' + href + '#' + value.id + ')';
}
el.style.setProperty(name, value+'');
}
values[prop] = value;
}
};
module.exports = SVGRenderer;
},{"../../util/ImageLoader":72,"../../util/dom":76,"../../util/font":77,"../../util/svg":78,"../Renderer":49,"./marks":69}],67:[function(require,module,exports){
var Renderer = require('../Renderer'),
ImageLoader = require('../../util/ImageLoader'),
SVG = require('../../util/svg'),
font = require('../../util/font'),
DOM = require('../../util/dom'),
openTag = DOM.openTag,
closeTag = DOM.closeTag,
MARKS = require('./marks');
function SVGStringRenderer(loadConfig) {
Renderer.call(this);
this._loader = new ImageLoader(loadConfig);
this._text = {
head: '',
root: '',
foot: '',
defs: '',
body: ''
};
this._defs = {
clip_id: 1,
gradient: {},
clipping: {}
};
}
var base = Renderer.prototype;
var prototype = (SVGStringRenderer.prototype = Object.create(base));
prototype.constructor = SVGStringRenderer;
prototype.resize = function(width, height, padding) {
base.resize.call(this, width, height, padding);
var p = this._padding,
t = this._text;
var attr = {
'class': 'marks',
'width': this._width + p.left + p.right,
'height': this._height + p.top + p.bottom,
};
for (var key in SVG.metadata) {
attr[key] = SVG.metadata[key];
}
t.head = openTag('svg', attr);
t.root = openTag('g', {
transform: 'translate(' + p.left + ',' + p.top + ')'
});
t.foot = closeTag('g') + closeTag('svg');
return this;
};
prototype.svg = function() {
var t = this._text;
return t.head + t.defs + t.root + t.body + t.foot;
};
prototype.render = function(scene) {
this._text.body = this.mark(scene);
this._text.defs = this.buildDefs();
return this;
};
prototype.reset = function() {
this._defs.clip_id = 0;
return this;
};
prototype.buildDefs = function() {
var all = this._defs,
defs = '',
i, id, def, stops;
for (id in all.gradient) {
def = all.gradient[id];
stops = def.stops;
defs += openTag('linearGradient', {
id: id,
x1: def.x1,
x2: def.x2,
y1: def.y1,
y2: def.y2
});
for (i=0; i<stops.length; ++i) {
defs += openTag('stop', {
offset: stops[i].offset,
'stop-color': stops[i].color
}) + closeTag('stop');
}
defs += closeTag('linearGradient');
}
for (id in all.clipping) {
def = all.clipping[id];
defs += openTag('clipPath', {id: id});
defs += openTag('rect', {
x: 0,
y: 0,
width: def.width,
height: def.height
}) + closeTag('rect');
defs += closeTag('clipPath');
}
return (defs.length > 0) ? openTag('defs') + defs + closeTag('defs') : '';
};
prototype.imageURL = function(url) {
return this._loader.imageURL(url);
};
var object;
function emit(name, value, ns, prefixed) {
object[prefixed || name] = value;
}
prototype.attributes = function(attr, item) {
object = {};
attr(emit, item, this);
return object;
};
prototype.mark = function(scene) {
var mdef = MARKS[scene.marktype],
tag = mdef.tag,
attr = mdef.attr,
nest = mdef.nest || false,
data = nest ?
(scene.items && scene.items.length ? [scene.items[0]] : []) :
(scene.items || []),
defs = this._defs,
str = '',
style, i, item;
if (tag !== 'g' && scene.interactive === false) {
style = 'style="pointer-events: none;"';
}
// render opening group tag
str += openTag('g', {
'class': DOM.cssClass(scene)
}, style);
// render contained elements
for (i=0; i<data.length; ++i) {
item = data[i];
style = (tag !== 'g') ? styles(item, scene, tag, defs) : null;
str += openTag(tag, this.attributes(attr, item), style);
if (tag === 'text') {
str += escape_text(item.text);
} else if (tag === 'g') {
str += openTag('rect',
this.attributes(mdef.background, item),
styles(item, scene, 'bgrect', defs)) + closeTag('rect');
str += this.markGroup(item);
}
str += closeTag(tag);
}
// render closing group tag
return str + closeTag('g');
};
prototype.markGroup = function(scene) {
var str = '',
axes = scene.axisItems || [],
items = scene.items || [],
legends = scene.legendItems || [],
j, m;
for (j=0, m=axes.length; j<m; ++j) {
if (axes[j].layer === 'back') {
str += this.mark(axes[j]);
}
}
for (j=0, m=items.length; j<m; ++j) {
str += this.mark(items[j]);
}
for (j=0, m=axes.length; j<m; ++j) {
if (axes[j].layer !== 'back') {
str += this.mark(axes[j]);
}
}
for (j=0, m=legends.length; j<m; ++j) {
str += this.mark(legends[j]);
}
return str;
};
function styles(o, mark, tag, defs) {
if (o == null) return '';
var i, n, prop, name, value, s = '';
if (tag === 'bgrect' && mark.interactive === false) {
s += 'pointer-events: none;';
}
if (tag === 'text') {
s += 'font: ' + font.string(o) + ';';
}
for (i=0, n=SVG.styleProperties.length; i<n; ++i) {
prop = SVG.styleProperties[i];
name = SVG.styles[prop];
value = o[prop];
if (value == null) {
if (name === 'fill') {
s += (s.length ? ' ' : '') + 'fill: none;';
}
} else {
if (value.id) {
// ensure definition is included
defs.gradient[value.id] = value;
value = 'url(#' + value.id + ')';
}
s += (s.length ? ' ' : '') + name + ': ' + value + ';';
}
}
return s ? 'style="' + s + '"' : null;
}
function escape_text(s) {
s = (s == null ? '' : String(s));
return s.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
}
module.exports = SVGStringRenderer;
},{"../../util/ImageLoader":72,"../../util/dom":76,"../../util/font":77,"../../util/svg":78,"../Renderer":49,"./marks":69}],68:[function(require,module,exports){
module.exports = {
Handler: require('./SVGHandler'),
Renderer: require('./SVGRenderer'),
string: {
Renderer : require('./SVGStringRenderer')
}
};
},{"./SVGHandler":65,"./SVGRenderer":66,"./SVGStringRenderer":67}],69:[function(require,module,exports){
var font = require('../../util/font'),
SVG = require('../../util/svg'),
textAlign = SVG.textAlign,
path = SVG.path;
function translateItem(o) {
return translate(o.x || 0, o.y || 0);
}
function translate(x, y) {
return 'translate(' + x + ',' + y + ')';
}
module.exports = {
arc: {
tag: 'path',
type: 'arc',
attr: function(emit, o) {
emit('transform', translateItem(o));
emit('d', path.arc(o));
}
},
area: {
tag: 'path',
type: 'area',
nest: true,
attr: function(emit, o) {
var items = o.mark.items;
if (items.length) emit('d', path.area(items));
}
},
group: {
tag: 'g',
type: 'group',
attr: function(emit, o, renderer) {
var id = null, defs, c;
emit('transform', translateItem(o));
if (o.clip) {
defs = renderer._defs;
id = o.clip_id || (o.clip_id = 'clip' + defs.clip_id++);
c = defs.clipping[id] || (defs.clipping[id] = {id: id});
c.width = o.width || 0;
c.height = o.height || 0;
}
emit('clip-path', id ? ('url(#' + id + ')') : null);
},
background: function(emit, o) {
emit('class', 'background');
emit('width', o.width || 0);
emit('height', o.height || 0);
}
},
image: {
tag: 'image',
type: 'image',
attr: function(emit, o, renderer) {
var x = o.x || 0,
y = o.y || 0,
w = o.width || 0,
h = o.height || 0,
url = renderer.imageURL(o.url);
x = x - (o.align === 'center' ? w/2 : o.align === 'right' ? w : 0);
y = y - (o.baseline === 'middle' ? h/2 : o.baseline === 'bottom' ? h : 0);
emit('href', url, 'http://www.w3.org/1999/xlink', 'xlink:href');
emit('transform', translate(x, y));
emit('width', w);
emit('height', h);
}
},
line: {
tag: 'path',
type: 'line',
nest: true,
attr: function(emit, o) {
var items = o.mark.items;
if (items.length) emit('d', path.line(items));
}
},
path: {
tag: 'path',
type: 'path',
attr: function(emit, o) {
emit('transform', translateItem(o));
emit('d', o.path);
}
},
rect: {
tag: 'rect',
type: 'rect',
nest: false,
attr: function(emit, o) {
emit('transform', translateItem(o));
emit('width', o.width || 0);
emit('height', o.height || 0);
}
},
rule: {
tag: 'line',
type: 'rule',
attr: function(emit, o) {
emit('transform', translateItem(o));
emit('x2', o.x2 != null ? o.x2 - (o.x||0) : 0);
emit('y2', o.y2 != null ? o.y2 - (o.y||0) : 0);
}
},
symbol: {
tag: 'path',
type: 'symbol',
attr: function(emit, o) {
emit('transform', translateItem(o));
emit('d', path.symbol(o));
}
},
text: {
tag: 'text',
type: 'text',
nest: false,
attr: function(emit, o) {
var dx = (o.dx || 0),
dy = (o.dy || 0) + font.offset(o),
x = (o.x || 0),
y = (o.y || 0),
a = o.angle || 0,
r = o.radius || 0, t;
if (r) {
t = (o.theta || 0) - Math.PI/2;
x += r * Math.cos(t);
y += r * Math.sin(t);
}
emit('text-anchor', textAlign[o.align] || 'start');
if (a) {
t = translate(x, y) + ' rotate('+a+')';
if (dx || dy) t += ' ' + translate(dx, dy);
} else {
t = translate(x+dx, y+dy);
}
emit('transform', t);
}
}
};
},{"../../util/font":77,"../../util/svg":78}],70:[function(require,module,exports){
function Bounds(b) {
this.clear();
if (b) this.union(b);
}
var prototype = Bounds.prototype;
prototype.clone = function() {
return new Bounds(this);
};
prototype.clear = function() {
this.x1 = +Number.MAX_VALUE;
this.y1 = +Number.MAX_VALUE;
this.x2 = -Number.MAX_VALUE;
this.y2 = -Number.MAX_VALUE;
return this;
};
prototype.set = function(x1, y1, x2, y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
return this;
};
prototype.add = function(x, y) {
if (x < this.x1) this.x1 = x;
if (y < this.y1) this.y1 = y;
if (x > this.x2) this.x2 = x;
if (y > this.y2) this.y2 = y;
return this;
};
prototype.expand = function(d) {
this.x1 -= d;
this.y1 -= d;
this.x2 += d;
this.y2 += d;
return this;
};
prototype.round = function() {
this.x1 = Math.floor(this.x1);
this.y1 = Math.floor(this.y1);
this.x2 = Math.ceil(this.x2);
this.y2 = Math.ceil(this.y2);
return this;
};
prototype.translate = function(dx, dy) {
this.x1 += dx;
this.x2 += dx;
this.y1 += dy;
this.y2 += dy;
return this;
};
prototype.rotate = function(angle, x, y) {
var cos = Math.cos(angle),
sin = Math.sin(angle),
cx = x - x*cos + y*sin,
cy = y - x*sin - y*cos,
x1 = this.x1, x2 = this.x2,
y1 = this.y1, y2 = this.y2;
return this.clear()
.add(cos*x1 - sin*y1 + cx, sin*x1 + cos*y1 + cy)
.add(cos*x1 - sin*y2 + cx, sin*x1 + cos*y2 + cy)
.add(cos*x2 - sin*y1 + cx, sin*x2 + cos*y1 + cy)
.add(cos*x2 - sin*y2 + cx, sin*x2 + cos*y2 + cy);
};
prototype.union = function(b) {
if (b.x1 < this.x1) this.x1 = b.x1;
if (b.y1 < this.y1) this.y1 = b.y1;
if (b.x2 > this.x2) this.x2 = b.x2;
if (b.y2 > this.y2) this.y2 = b.y2;
return this;
};
prototype.encloses = function(b) {
return b && (
this.x1 <= b.x1 &&
this.x2 >= b.x2 &&
this.y1 <= b.y1 &&
this.y2 >= b.y2
);
};
prototype.intersects = function(b) {
return b && !(
this.x2 < b.x1 ||
this.x1 > b.x2 ||
this.y2 < b.y1 ||
this.y1 > b.y2
);
};
prototype.contains = function(x, y) {
return !(
x < this.x1 ||
x > this.x2 ||
y < this.y1 ||
y > this.y2
);
};
prototype.width = function() {
return this.x2 - this.x1;
};
prototype.height = function() {
return this.y2 - this.y1;
};
module.exports = Bounds;
},{}],71:[function(require,module,exports){
var gradient_id = 0;
function Gradient(type) {
this.id = 'gradient_' + (gradient_id++);
this.type = type || 'linear';
this.stops = [];
this.x1 = 0;
this.x2 = 1;
this.y1 = 0;
this.y2 = 0;
}
var prototype = Gradient.prototype;
prototype.stop = function(offset, color) {
this.stops.push({
offset: offset,
color: color
});
return this;
};
module.exports = Gradient;
},{}],72:[function(require,module,exports){
(function (global){
var load = require('datalib/src/import/load');
function ImageLoader(loadConfig) {
this._pending = 0;
this._config = loadConfig || ImageLoader.Config;
}
// Overridable global default load configuration
ImageLoader.Config = null;
var prototype = ImageLoader.prototype;
prototype.pending = function() {
return this._pending;
};
prototype.params = function(uri) {
var p = {url: uri}, k;
for (k in this._config) { p[k] = this._config[k]; }
return p;
};
prototype.imageURL = function(uri) {
return load.sanitizeUrl(this.params(uri));
};
function browser(uri, callback) {
var url = load.sanitizeUrl(this.params(uri));
if (!url) { // error
if (callback) callback(uri, null);
return null;
}
var loader = this,
image = new Image();
loader._pending += 1;
image.onload = function() {
loader._pending -= 1;
image.loaded = true;
if (callback) callback(null, image);
};
image.src = url;
return image;
}
function server(uri, callback) {
var loader = this,
image = new ((typeof window !== "undefined" ? window.canvas : typeof global !== "undefined" ? global.canvas : null).Image)();
loader._pending += 1;
load(this.params(uri), function(err, data) {
loader._pending -= 1;
if (err) {
if (callback) callback(err, null);
return null;
}
image.src = data;
image.loaded = true;
if (callback) callback(null, image);
});
return image;
}
prototype.loadImage = function(uri, callback) {
return load.useXHR ?
browser.call(this, uri, callback) :
server.call(this, uri, callback);
};
module.exports = ImageLoader;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy92ZWdhLXNjZW5lZ3JhcGgvc3JjL3V0aWwvSW1hZ2VMb2FkZXIuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwiZmlsZSI6ImdlbmVyYXRlZC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgbG9hZCA9IHJlcXVpcmUoJ2RhdGFsaWIvc3JjL2ltcG9ydC9sb2FkJyk7XG5cbmZ1bmN0aW9uIEltYWdlTG9hZGVyKGxvYWRDb25maWcpIHtcbiAgdGhpcy5fcGVuZGluZyA9IDA7XG4gIHRoaXMuX2NvbmZpZyA9IGxvYWRDb25maWcgfHwgSW1hZ2VMb2FkZXIuQ29uZmlnOyBcbn1cblxuLy8gT3ZlcnJpZGFibGUgZ2xvYmFsIGRlZmF1bHQgbG9hZCBjb25maWd1cmF0aW9uXG5JbWFnZUxvYWRlci5Db25maWcgPSBudWxsO1xuXG52YXIgcHJvdG90eXBlID0gSW1hZ2VMb2FkZXIucHJvdG90eXBlO1xuXG5wcm90b3R5cGUucGVuZGluZyA9IGZ1bmN0aW9uKCkge1xuICByZXR1cm4gdGhpcy5fcGVuZGluZztcbn07XG5cbnByb3RvdHlwZS5wYXJhbXMgPSBmdW5jdGlvbih1cmkpIHtcbiAgdmFyIHAgPSB7dXJsOiB1cml9LCBrO1xuICBmb3IgKGsgaW4gdGhpcy5fY29uZmlnKSB7IHBba10gPSB0aGlzLl9jb25maWdba107IH1cbiAgcmV0dXJuIHA7XG59O1xuXG5wcm90b3R5cGUuaW1hZ2VVUkwgPSBmdW5jdGlvbih1cmkpIHtcbiAgcmV0dXJuIGxvYWQuc2FuaXRpemVVcmwodGhpcy5wYXJhbXModXJpKSk7XG59O1xuXG5mdW5jdGlvbiBicm93c2VyKHVyaSwgY2FsbGJhY2spIHtcbiAgdmFyIHVybCA9IGxvYWQuc2FuaXRpemVVcmwodGhpcy5wYXJhbXModXJpKSk7XG4gIGlmICghdXJsKSB7IC8vIGVycm9yXG4gICAgaWYgKGNhbGxiYWNrKSBjYWxsYmFjayh1cmksIG51bGwpO1xuICAgIHJldHVybiBudWxsO1xuICB9XG5cbiAgdmFyIGxvYWRlciA9IHRoaXMsXG4gICAgICBpbWFnZSA9IG5ldyBJbWFnZSgpO1xuXG4gIGxvYWRlci5fcGVuZGluZyArPSAxO1xuXG4gIGltYWdlLm9ubG9hZCA9IGZ1bmN0aW9uKCkge1xuICAgIGxvYWRlci5fcGVuZGluZyAtPSAxO1xuICAgIGltYWdlLmxvYWRlZCA9IHRydWU7XG4gICAgaWYgKGNhbGxiYWNrKSBjYWxsYmFjayhudWxsLCBpbWFnZSk7XG4gIH07XG4gIGltYWdlLnNyYyA9IHVybDtcblxuICByZXR1cm4gaW1hZ2U7XG59XG5cbmZ1bmN0aW9uIHNlcnZlcih1cmksIGNhbGxiYWNrKSB7XG4gIHZhciBsb2FkZXIgPSB0aGlzLFxuICAgICAgaW1hZ2UgPSBuZXcgKCh0eXBlb2Ygd2luZG93ICE9PSBcInVuZGVmaW5lZFwiID8gd2luZG93LmNhbnZhcyA6IHR5cGVvZiBnbG9iYWwgIT09IFwidW5kZWZpbmVkXCIgPyBnbG9iYWwuY2FudmFzIDogbnVsbCkuSW1hZ2UpKCk7XG5cbiAgbG9hZGVyLl9wZW5kaW5nICs9IDE7XG5cbiAgbG9hZCh0aGlzLnBhcmFtcyh1cmkpLCBmdW5jdGlvbihlcnIsIGRhdGEpIHtcbiAgICBsb2FkZXIuX3BlbmRpbmcgLT0gMTtcbiAgICBpZiAoZXJyKSB7XG4gICAgICBpZiAoY2FsbGJhY2spIGNhbGxiYWNrKGVyciwgbnVsbCk7XG4gICAgICByZXR1cm4gbnVsbDtcbiAgICB9XG4gICAgaW1hZ2Uuc3JjID0gZGF0YTtcbiAgICBpbWFnZS5sb2FkZWQgPSB0cnVlO1xuICAgIGlmIChjYWxsYmFjaykgY2FsbGJhY2sobnVsbCwgaW1hZ2UpO1xuICB9KTtcblxuICByZXR1cm4gaW1hZ2U7XG59XG5cbnByb3RvdHlwZS5sb2FkSW1hZ2UgPSBmdW5jdGlvbih1cmksIGNhbGxiYWNrKSB7XG4gIHJldHVybiBsb2FkLnVzZVhIUiA/XG4gICAgYnJvd3Nlci5jYWxsKHRoaXMsIHVyaSwgY2FsbGJhY2spIDpcbiAgICBzZXJ2ZXIuY2FsbCh0aGlzLCB1cmksIGNhbGxiYWNrKTtcbn07XG5cbm1vZHVsZS5leHBvcnRzID0gSW1hZ2VMb2FkZXI7XG4iXX0=
},{"datalib/src/import/load":42}],73:[function(require,module,exports){
function Item(mark) {
this.mark = mark;
}
var prototype = Item.prototype;
prototype.hasPropertySet = function(name) {
var props = this.mark.def.properties;
return props && props[name] != null;
};
prototype.cousin = function(offset, index) {
if (offset === 0) return this;
offset = offset || -1;
var mark = this.mark,
group = mark.group,
iidx = index==null ? mark.items.indexOf(this) : index,
midx = group.items.indexOf(mark) + offset;
return group.items[midx].items[iidx];
};
prototype.sibling = function(offset) {
if (offset === 0) return this;
offset = offset || -1;
var mark = this.mark,
iidx = mark.items.indexOf(this) + offset;
return mark.items[iidx];
};
prototype.remove = function() {
var item = this,
list = item.mark.items,
i = list.indexOf(item);
if (i >= 0) {
if (i===list.length-1) {
list.pop();
} else {
list.splice(i, 1);
}
}
return item;
};
prototype.touch = function() {
if (this.pathCache) this.pathCache = null;
};
module.exports = Item;
},{}],74:[function(require,module,exports){
var Bounds = require('../util/Bounds'),
canvas = require('../util/canvas'),
svg = require('../util/svg'),
font = require('./font'),
paths = require('../path'),
parse = paths.parse,
boundPath = paths.bounds,
areaPath = svg.path.area,
linePath = svg.path.line,
halfpi = Math.PI / 2,
sqrt3 = Math.sqrt(3),
tan30 = Math.tan(30 * Math.PI / 180),
g2D = null;
function context() {
return g2D || (g2D = canvas.instance(1,1).getContext('2d'));
}
function strokeBounds(o, bounds) {
if (o.stroke && o.opacity !== 0 && o.stokeOpacity !== 0) {
bounds.expand(o.strokeWidth != null ? o.strokeWidth : 1);
}
return bounds;
}
function pathBounds(o, path, bounds) {
if (path == null) {
bounds.set(0, 0, 0, 0);
} else {
boundPath(path, bounds);
strokeBounds(o, bounds);
}
return bounds;
}
function path(o, bounds) {
var p = o.path ? o.pathCache || (o.pathCache = parse(o.path)) : null;
return pathBounds(o, p, bounds).translate(o.x || 0, o.y || 0);
}
function area(mark, bounds) {
if (mark.items.length === 0) return bounds;
var items = mark.items,
item = items[0],
p = item.pathCache || (item.pathCache = parse(areaPath(items)));
return pathBounds(item, p, bounds);
}
function line(mark, bounds) {
if (mark.items.length === 0) return bounds;
var items = mark.items,
item = items[0],
p = item.pathCache || (item.pathCache = parse(linePath(items)));
return pathBounds(item, p, bounds);
}
function rect(o, bounds) {
var x, y;
return strokeBounds(o, bounds.set(
x = o.x || 0,
y = o.y || 0,
(x + o.width) || 0,
(y + o.height) || 0
));
}
function image(o, bounds) {
var x = o.x || 0,
y = o.y || 0,
w = o.width || 0,
h = o.height || 0;
x = x - (o.align === 'center' ? w/2 : (o.align === 'right' ? w : 0));
y = y - (o.baseline === 'middle' ? h/2 : (o.baseline === 'bottom' ? h : 0));
return bounds.set(x, y, x+w, y+h);
}
function rule(o, bounds) {
var x1, y1;
return strokeBounds(o, bounds.set(
x1 = o.x || 0,
y1 = o.y || 0,
o.x2 != null ? o.x2 : x1,
o.y2 != null ? o.y2 : y1
));
}
function arc(o, bounds) {
var cx = o.x || 0,
cy = o.y || 0,
ir = o.innerRadius || 0,
or = o.outerRadius || 0,
sa = (o.startAngle || 0) - halfpi,
ea = (o.endAngle || 0) - halfpi,
xmin = Infinity, xmax = -Infinity,
ymin = Infinity, ymax = -Infinity,
a, i, n, x, y, ix, iy, ox, oy;
var angles = [sa, ea],
s = sa - (sa % halfpi);
for (i=0; i<4 && s<ea; ++i, s+=halfpi) {
angles.push(s);
}
for (i=0, n=angles.length; i<n; ++i) {
a = angles[i];
x = Math.cos(a); ix = ir*x; ox = or*x;
y = Math.sin(a); iy = ir*y; oy = or*y;
xmin = Math.min(xmin, ix, ox);
xmax = Math.max(xmax, ix, ox);
ymin = Math.min(ymin, iy, oy);
ymax = Math.max(ymax, iy, oy);
}
return strokeBounds(o, bounds.set(
cx + xmin,
cy + ymin,
cx + xmax,
cy + ymax
));
}
function symbol(o, bounds) {
var size = o.size != null ? o.size : 100,
x = o.x || 0,
y = o.y || 0,
r, t, rx, ry;
switch (o.shape) {
case 'cross':
t = 3 * Math.sqrt(size / 5) / 2;
bounds.set(x-t, y-t, x+t, y+t);
break;
case 'diamond':
ry = Math.sqrt(size / (2 * tan30));
rx = ry * tan30;
bounds.set(x-rx, y-ry, x+rx, y+ry);
break;
case 'square':
t = Math.sqrt(size);
r = t / 2;
bounds.set(x-r, y-r, x+r, y+r);
break;
case 'triangle-down':
rx = Math.sqrt(size / sqrt3);
ry = rx * sqrt3 / 2;
bounds.set(x-rx, y-ry, x+rx, y+ry);
break;
case 'triangle-up':
rx = Math.sqrt(size / sqrt3);
ry = rx * sqrt3 / 2;
bounds.set(x-rx, y-ry, x+rx, y+ry);
break;
default:
r = Math.sqrt(size/Math.PI);
bounds.set(x-r, y-r, x+r, y+r);
}
return strokeBounds(o, bounds);
}
function text(o, bounds, noRotate) {
var g = context(),
h = font.size(o),
a = o.align,
r = o.radius || 0,
x = (o.x || 0),
y = (o.y || 0),
dx = (o.dx || 0),
dy = (o.dy || 0) + font.offset(o) - Math.round(0.8*h), // use 4/5 offset
w, t;
if (r) {
t = (o.theta || 0) - Math.PI/2;
x += r * Math.cos(t);
y += r * Math.sin(t);
}
// horizontal alignment
g.font = font.string(o);
w = g.measureText(o.text || '').width;
if (a === 'center') {
dx -= (w / 2);
} else if (a === 'right') {
dx -= w;
} else {
// left by default, do nothing
}
bounds.set(dx+=x, dy+=y, dx+w, dy+h);
if (o.angle && !noRotate) {
bounds.rotate(o.angle*Math.PI/180, x, y);
}
return bounds.expand(noRotate ? 0 : 1);
}
function group(g, bounds, includeLegends) {
var axes = g.axisItems || [],
items = g.items || [],
legends = g.legendItems || [],
j, m;
for (j=0, m=axes.length; j<m; ++j) {
bounds.union(axes[j].bounds);
}
for (j=0, m=items.length; j<m; ++j) {
bounds.union(items[j].bounds);
}
if (includeLegends) {
for (j=0, m=legends.length; j<m; ++j) {
bounds.union(legends[j].bounds);
}
}
if (g.width || g.height) {
strokeBounds(g, bounds
.add(0, 0)
.add(g.width || 0, g.height || 0));
}
return bounds.translate(g.x || 0, g.y || 0);
}
var methods = {
group: group,
symbol: symbol,
image: image,
rect: rect,
rule: rule,
arc: arc,
text: text,
path: path,
area: area,
line: line
};
methods.area.nest = true;
methods.line.nest = true;
function itemBounds(item, func, opt) {
var type = item.mark.marktype;
func = func || methods[type];
if (func.nest) item = item.mark;
var curr = item.bounds,
prev = item['bounds:prev'] || (item['bounds:prev'] = new Bounds());
if (curr) {
prev.clear().union(curr);
curr.clear();
} else {
item.bounds = new Bounds();
}
func(item, item.bounds, opt);
if (!curr) prev.clear().union(item.bounds);
return item.bounds;
}
var DUMMY_ITEM = {mark: null};
function markBounds(mark, bounds, opt) {
var type = mark.marktype,
func = methods[type],
items = mark.items,
hasi = items && items.length,
i, n, o, b;
if (func.nest) {
o = hasi ? items[0]
: (DUMMY_ITEM.mark = mark, DUMMY_ITEM); // no items, so fake it
b = itemBounds(o, func, opt);
bounds = bounds && bounds.union(b) || b;
return bounds;
}
bounds = bounds || mark.bounds && mark.bounds.clear() || new Bounds();
if (hasi) {
for (i=0, n=items.length; i<n; ++i) {
bounds.union(itemBounds(items[i], func, opt));
}
}
return (mark.bounds = bounds);
}
module.exports = {
mark: markBounds,
item: itemBounds,
text: text,
group: group
};
},{"../path":45,"../util/Bounds":70,"../util/canvas":75,"../util/svg":78,"./font":77}],75:[function(require,module,exports){
(function (global){
function instance(w, h) {
w = w || 1;
h = h || 1;
var canvas;
if (typeof document !== 'undefined' && document.createElement) {
canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
} else {
var Canvas = (typeof window !== "undefined" ? window.canvas : typeof global !== "undefined" ? global.canvas : null);
if (!Canvas.prototype) return null;
canvas = new Canvas(w, h);
}
return lineDash(canvas);
}
function resize(canvas, w, h, p) {
var g = this._ctx = canvas.getContext('2d'),
s = 1;
canvas.width = w + p.left + p.right;
canvas.height = h + p.top + p.bottom;
// if browser canvas, attempt to modify for retina display
if (typeof HTMLElement !== 'undefined' && canvas instanceof HTMLElement) {
g.pixelratio = (s = pixelRatio(canvas) || 1);
}
g.setTransform(s, 0, 0, s, s*p.left, s*p.top);
return canvas;
}
function pixelRatio(canvas) {
var g = canvas.getContext('2d');
// get canvas pixel data
var devicePixelRatio = window && window.devicePixelRatio || 1,
backingStoreRatio = (
g.webkitBackingStorePixelRatio ||
g.mozBackingStorePixelRatio ||
g.msBackingStorePixelRatio ||
g.oBackingStorePixelRatio ||
g.backingStorePixelRatio) || 1,
ratio = devicePixelRatio / backingStoreRatio;
if (devicePixelRatio !== backingStoreRatio) {
// set actual and visible canvas size
var w = canvas.width,
h = canvas.height;
canvas.width = w * ratio;
canvas.height = h * ratio;
canvas.style.width = w + 'px';
canvas.style.height = h + 'px';
}
return ratio;
}
function lineDash(canvas) {
var g = canvas.getContext('2d');
if (g.vgLineDash) return; // already initialized!
var NOOP = function() {},
NODASH = [];
if (g.setLineDash) {
g.vgLineDash = function(dash) { this.setLineDash(dash || NODASH); };
g.vgLineDashOffset = function(off) { this.lineDashOffset = off; };
} else if (g.webkitLineDash !== undefined) {
g.vgLineDash = function(dash) { this.webkitLineDash = dash || NODASH; };
g.vgLineDashOffset = function(off) { this.webkitLineDashOffset = off; };
} else if (g.mozDash !== undefined) {
g.vgLineDash = function(dash) { this.mozDash = dash; };
g.vgLineDashOffset = NOOP;
} else {
g.vgLineDash = NOOP;
g.vgLineDashOffset = NOOP;
}
return canvas;
}
module.exports = {
instance: instance,
resize: resize,
pixelRatio: pixelRatio,
lineDash: lineDash
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy92ZWdhLXNjZW5lZ3JhcGgvc3JjL3V0aWwvY2FudmFzLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwiZmlsZSI6ImdlbmVyYXRlZC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzQ29udGVudCI6WyJmdW5jdGlvbiBpbnN0YW5jZSh3LCBoKSB7XG4gIHcgPSB3IHx8IDE7XG4gIGggPSBoIHx8IDE7XG4gIHZhciBjYW52YXM7XG5cbiAgaWYgKHR5cGVvZiBkb2N1bWVudCAhPT0gJ3VuZGVmaW5lZCcgJiYgZG9jdW1lbnQuY3JlYXRlRWxlbWVudCkge1xuICAgIGNhbnZhcyA9IGRvY3VtZW50LmNyZWF0ZUVsZW1lbnQoJ2NhbnZhcycpO1xuICAgIGNhbnZhcy53aWR0aCA9IHc7XG4gICAgY2FudmFzLmhlaWdodCA9IGg7XG4gIH0gZWxzZSB7XG4gICAgdmFyIENhbnZhcyA9ICh0eXBlb2Ygd2luZG93ICE9PSBcInVuZGVmaW5lZFwiID8gd2luZG93LmNhbnZhcyA6IHR5cGVvZiBnbG9iYWwgIT09IFwidW5kZWZpbmVkXCIgPyBnbG9iYWwuY2FudmFzIDogbnVsbCk7XG4gICAgaWYgKCFDYW52YXMucHJvdG90eXBlKSByZXR1cm4gbnVsbDtcbiAgICBjYW52YXMgPSBuZXcgQ2FudmFzKHcsIGgpO1xuICB9XG4gIHJldHVybiBsaW5lRGFzaChjYW52YXMpO1xufVxuXG5mdW5jdGlvbiByZXNpemUoY2FudmFzLCB3LCBoLCBwKSB7XG4gIHZhciBnID0gdGhpcy5fY3R4ID0gY2FudmFzLmdldENvbnRleHQoJzJkJyksIFxuICAgICAgcyA9IDE7XG5cbiAgY2FudmFzLndpZHRoID0gdyArIHAubGVmdCArIHAucmlnaHQ7XG4gIGNhbnZhcy5oZWlnaHQgPSBoICsgcC50b3AgKyBwLmJvdHRvbTtcblxuICAvLyBpZiBicm93c2VyIGNhbnZhcywgYXR0ZW1wdCB0byBtb2RpZnkgZm9yIHJldGluYSBkaXNwbGF5XG4gIGlmICh0eXBlb2YgSFRNTEVsZW1lbnQgIT09ICd1bmRlZmluZWQnICYmIGNhbnZhcyBpbnN0YW5jZW9mIEhUTUxFbGVtZW50KSB7XG4gICAgZy5waXhlbHJhdGlvID0gKHMgPSBwaXhlbFJhdGlvKGNhbnZhcykgfHwgMSk7XG4gIH1cblxuICBnLnNldFRyYW5zZm9ybShzLCAwLCAwLCBzLCBzKnAubGVmdCwgcypwLnRvcCk7XG4gIHJldHVybiBjYW52YXM7XG59XG5cbmZ1bmN0aW9uIHBpeGVsUmF0aW8oY2FudmFzKSB7XG4gIHZhciBnID0gY2FudmFzLmdldENvbnRleHQoJzJkJyk7XG5cbiAgLy8gZ2V0IGNhbnZhcyBwaXhlbCBkYXRhXG4gIHZhciBkZXZpY2VQaXhlbFJhdGlvID0gd2luZG93ICYmIHdpbmRvdy5kZXZpY2VQaXhlbFJhdGlvIHx8IDEsXG4gICAgICBiYWNraW5nU3RvcmVSYXRpbyA9IChcbiAgICAgICAgZy53ZWJraXRCYWNraW5nU3RvcmVQaXhlbFJhdGlvIHx8XG4gICAgICAgIGcubW96QmFja2luZ1N0b3JlUGl4ZWxSYXRpbyB8fFxuICAgICAgICBnLm1zQmFja2luZ1N0b3JlUGl4ZWxSYXRpbyB8fFxuICAgICAgICBnLm9CYWNraW5nU3RvcmVQaXhlbFJhdGlvIHx8XG4gICAgICAgIGcuYmFja2luZ1N0b3JlUGl4ZWxSYXRpbykgfHwgMSxcbiAgICAgIHJhdGlvID0gZGV2aWNlUGl4ZWxSYXRpbyAvIGJhY2tpbmdTdG9yZVJhdGlvO1xuXG4gIGlmIChkZXZpY2VQaXhlbFJhdGlvICE9PSBiYWNraW5nU3RvcmVSYXRpbykge1xuICAgIC8vIHNldCBhY3R1YWwgYW5kIHZpc2libGUgY2FudmFzIHNpemVcbiAgICB2YXIgdyA9IGNhbnZhcy53aWR0aCxcbiAgICAgICAgaCA9IGNhbnZhcy5oZWlnaHQ7XG4gICAgY2FudmFzLndpZHRoID0gdyAqIHJhdGlvO1xuICAgIGNhbnZhcy5oZWlnaHQgPSBoICogcmF0aW87XG4gICAgY2FudmFzLnN0eWxlLndpZHRoID0gdyArICdweCc7XG4gICAgY2FudmFzLnN0eWxlLmhlaWdodCA9IGggKyAncHgnO1xuICB9XG5cbiAgcmV0dXJuIHJhdGlvO1xufVxuXG5mdW5jdGlvbiBsaW5lRGFzaChjYW52YXMpIHtcbiAgdmFyIGcgPSBjYW52YXMuZ2V0Q29udGV4dCgnMmQnKTtcbiAgaWYgKGcudmdMaW5lRGFzaCkgcmV0dXJuOyAvLyBhbHJlYWR5IGluaXRpYWxpemVkIVxuXG4gIHZhciBOT09QID0gZnVuY3Rpb24oKSB7fSxcbiAgICAgIE5PREFTSCA9IFtdO1xuICBcbiAgaWYgKGcuc2V0TGluZURhc2gpIHtcbiAgICBnLnZnTGluZURhc2ggPSBmdW5jdGlvbihkYXNoKSB7IHRoaXMuc2V0TGluZURhc2goZGFzaCB8fCBOT0RBU0gpOyB9O1xuICAgIGcudmdMaW5lRGFzaE9mZnNldCA9IGZ1bmN0aW9uKG9mZikgeyB0aGlzLmxpbmVEYXNoT2Zmc2V0ID0gb2ZmOyB9O1xuICB9IGVsc2UgaWYgKGcud2Via2l0TGluZURhc2ggIT09IHVuZGVmaW5lZCkge1xuICBcdGcudmdMaW5lRGFzaCA9IGZ1bmN0aW9uKGRhc2gpIHsgdGhpcy53ZWJraXRMaW5lRGFzaCA9IGRhc2ggfHwgTk9EQVNIOyB9O1xuICAgIGcudmdMaW5lRGFzaE9mZnNldCA9IGZ1bmN0aW9uKG9mZikgeyB0aGlzLndlYmtpdExpbmVEYXNoT2Zmc2V0ID0gb2ZmOyB9O1xuICB9IGVsc2UgaWYgKGcubW96RGFzaCAhPT0gdW5kZWZpbmVkKSB7XG4gICAgZy52Z0xpbmVEYXNoID0gZnVuY3Rpb24oZGFzaCkgeyB0aGlzLm1vekRhc2ggPSBkYXNoOyB9O1xuICAgIGcudmdMaW5lRGFzaE9mZnNldCA9IE5PT1A7XG4gIH0gZWxzZSB7XG4gICAgZy52Z0xpbmVEYXNoID0gTk9PUDtcbiAgICBnLnZnTGluZURhc2hPZmZzZXQgPSBOT09QO1xuICB9XG4gIHJldHVybiBjYW52YXM7XG59XG5cbm1vZHVsZS5leHBvcnRzID0ge1xuICBpbnN0YW5jZTogICBpbnN0YW5jZSxcbiAgcmVzaXplOiAgICAgcmVzaXplLFxuICBwaXhlbFJhdGlvOiBwaXhlbFJhdGlvLFxuICBsaW5lRGFzaDogICBsaW5lRGFzaFxufTtcbiJdfQ==
},{}],76:[function(require,module,exports){
// create a new DOM element
function create(doc, tag, ns) {
return ns ? doc.createElementNS(ns, tag) : doc.createElement(tag);
}
// remove element from DOM
// recursively remove parent elements if empty
function remove(el) {
if (!el) return;
var p = el.parentNode;
if (p) {
p.removeChild(el);
if (!p.childNodes || !p.childNodes.length) remove(p);
}
}
module.exports = {
// find first child element with matching tag
find: function(el, tag) {
tag = tag.toLowerCase();
for (var i=0, n=el.childNodes.length; i<n; ++i) {
if (el.childNodes[i].tagName.toLowerCase() === tag) {
return el.childNodes[i];
}
}
},
// retrieve child element at given index
// create & insert if doesn't exist or if tag/className do not match
child: function(el, index, tag, ns, className, insert) {
var a, b;
a = b = el.childNodes[index];
if (!a || insert ||
a.tagName.toLowerCase() !== tag.toLowerCase() ||
className && a.getAttribute('class') != className) {
a = create(el.ownerDocument, tag, ns);
el.insertBefore(a, b);
if (className) a.setAttribute('class', className);
}
return a;
},
// remove all child elements at or above the given index
clear: function(el, index) {
var curr = el.childNodes.length;
while (curr > index) {
el.removeChild(el.childNodes[--curr]);
}
return el;
},
remove: remove,
// generate css class name for mark
cssClass: function(mark) {
return 'mark-' + mark.marktype + (mark.name ? ' '+mark.name : '');
},
// generate string for an opening xml tag
// tag: the name of the xml tag
// attr: hash of attribute name-value pairs to include
// raw: additional raw string to include in tag markup
openTag: function(tag, attr, raw) {
var s = '<' + tag, key, val;
if (attr) {
for (key in attr) {
val = attr[key];
if (val != null) {
s += ' ' + key + '="' + val + '"';
}
}
}
if (raw) s += ' ' + raw;
return s + '>';
},
// generate string for closing xml tag
// tag: the name of the xml tag
closeTag: function(tag) {
return '</' + tag + '>';
}
};
},{}],77:[function(require,module,exports){
function size(item) {
return item.fontSize != null ? item.fontSize : 11;
}
module.exports = {
size: size,
string: function(item, quote) {
var font = item.font;
if (quote && font) {
font = String(font).replace(/\"/g, '\'');
}
return '' +
(item.fontStyle ? item.fontStyle + ' ' : '') +
(item.fontVariant ? item.fontVariant + ' ' : '') +
(item.fontWeight ? item.fontWeight + ' ' : '') +
size(item) + 'px ' +
(font || 'sans-serif');
},
offset: function(item) {
// perform our own font baseline calculation
// why? not all browsers support SVG 1.1 'alignment-baseline' :(
var baseline = item.baseline,
h = size(item);
return Math.round(
baseline === 'top' ? 0.93*h :
baseline === 'middle' ? 0.30*h :
baseline === 'bottom' ? -0.21*h : 0
);
}
};
},{}],78:[function(require,module,exports){
(function (global){
var d3_svg = (typeof window !== "undefined" ? window.d3 : typeof global !== "undefined" ? global.d3 : null).svg;
function x(o) { return o.x || 0; }
function y(o) { return o.y || 0; }
function xw(o) { return (o.x || 0) + (o.width || 0); }
function yh(o) { return (o.y || 0) + (o.height || 0); }
function size(o) { return o.size == null ? 100 : o.size; }
function shape(o) { return o.shape || 'circle'; }
var areav = d3_svg.area().x(x).y1(y).y0(yh),
areah = d3_svg.area().y(y).x1(x).x0(xw),
line = d3_svg.line().x(x).y(y);
module.exports = {
metadata: {
'version': '1.1',
'xmlns': 'http://www.w3.org/2000/svg',
'xmlns:xlink': 'http://www.w3.org/1999/xlink'
},
path: {
arc: d3_svg.arc(),
symbol: d3_svg.symbol().type(shape).size(size),
area: function(items) {
var o = items[0];
return (o.orient === 'horizontal' ? areah : areav)
.interpolate(o.interpolate || 'linear')
.tension(o.tension || 0.7)
(items);
},
line: function(items) {
var o = items[0];
return line
.interpolate(o.interpolate || 'linear')
.tension(o.tension || 0.7)
(items);
}
},
textAlign: {
'left': 'start',
'center': 'middle',
'right': 'end'
},
textBaseline: {
'top': 'before-edge',
'bottom': 'after-edge',
'middle': 'central'
},
styles: {
'fill': 'fill',
'fillOpacity': 'fill-opacity',
'stroke': 'stroke',
'strokeWidth': 'stroke-width',
'strokeOpacity': 'stroke-opacity',
'strokeCap': 'stroke-linecap',
'strokeDash': 'stroke-dasharray',
'strokeDashOffset': 'stroke-dashoffset',
'opacity': 'opacity'
},
styleProperties: [
'fill',
'fillOpacity',
'stroke',
'strokeWidth',
'strokeOpacity',
'strokeCap',
'strokeDash',
'strokeDashOffset',
'opacity'
]
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy92ZWdhLXNjZW5lZ3JhcGgvc3JjL3V0aWwvc3ZnLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwiZmlsZSI6ImdlbmVyYXRlZC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgZDNfc3ZnID0gKHR5cGVvZiB3aW5kb3cgIT09IFwidW5kZWZpbmVkXCIgPyB3aW5kb3cuZDMgOiB0eXBlb2YgZ2xvYmFsICE9PSBcInVuZGVmaW5lZFwiID8gZ2xvYmFsLmQzIDogbnVsbCkuc3ZnO1xuXG5mdW5jdGlvbiB4KG8pICAgICB7IHJldHVybiBvLnggfHwgMDsgfVxuZnVuY3Rpb24geShvKSAgICAgeyByZXR1cm4gby55IHx8IDA7IH1cbmZ1bmN0aW9uIHh3KG8pICAgIHsgcmV0dXJuIChvLnggfHwgMCkgKyAoby53aWR0aCB8fCAwKTsgfVxuZnVuY3Rpb24geWgobykgICAgeyByZXR1cm4gKG8ueSB8fCAwKSArIChvLmhlaWdodCB8fCAwKTsgfVxuZnVuY3Rpb24gc2l6ZShvKSAgeyByZXR1cm4gby5zaXplID09IG51bGwgPyAxMDAgOiBvLnNpemU7IH1cbmZ1bmN0aW9uIHNoYXBlKG8pIHsgcmV0dXJuIG8uc2hhcGUgfHwgJ2NpcmNsZSc7IH1cblxudmFyIGFyZWF2ID0gZDNfc3ZnLmFyZWEoKS54KHgpLnkxKHkpLnkwKHloKSxcbiAgICBhcmVhaCA9IGQzX3N2Zy5hcmVhKCkueSh5KS54MSh4KS54MCh4dyksXG4gICAgbGluZSAgPSBkM19zdmcubGluZSgpLngoeCkueSh5KTtcblxubW9kdWxlLmV4cG9ydHMgPSB7XG4gIG1ldGFkYXRhOiB7XG4gICAgJ3ZlcnNpb24nOiAnMS4xJyxcbiAgICAneG1sbnMnOiAnaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnLFxuICAgICd4bWxuczp4bGluayc6ICdodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rJ1xuICB9LFxuICBwYXRoOiB7XG4gICAgYXJjOiBkM19zdmcuYXJjKCksXG4gICAgc3ltYm9sOiBkM19zdmcuc3ltYm9sKCkudHlwZShzaGFwZSkuc2l6ZShzaXplKSxcbiAgICBhcmVhOiBmdW5jdGlvbihpdGVtcykge1xuICAgICAgdmFyIG8gPSBpdGVtc1swXTtcbiAgICAgIHJldHVybiAoby5vcmllbnQgPT09ICdob3Jpem9udGFsJyA/IGFyZWFoIDogYXJlYXYpXG4gICAgICAgIC5pbnRlcnBvbGF0ZShvLmludGVycG9sYXRlIHx8ICdsaW5lYXInKVxuICAgICAgICAudGVuc2lvbihvLnRlbnNpb24gfHwgMC43KVxuICAgICAgICAoaXRlbXMpO1xuICAgIH0sXG4gICAgbGluZTogZnVuY3Rpb24oaXRlbXMpIHtcbiAgICAgIHZhciBvID0gaXRlbXNbMF07XG4gICAgICByZXR1cm4gbGluZVxuICAgICAgICAuaW50ZXJwb2xhdGUoby5pbnRlcnBvbGF0ZSB8fCAnbGluZWFyJylcbiAgICAgICAgLnRlbnNpb24oby50ZW5zaW9uIHx8IDAuNylcbiAgICAgICAgKGl0ZW1zKTtcbiAgICB9XG4gIH0sXG4gIHRleHRBbGlnbjoge1xuICAgICdsZWZ0JzogICAnc3RhcnQnLFxuICAgICdjZW50ZXInOiAnbWlkZGxlJyxcbiAgICAncmlnaHQnOiAgJ2VuZCdcbiAgfSxcbiAgdGV4dEJhc2VsaW5lOiB7XG4gICAgJ3RvcCc6ICAgICdiZWZvcmUtZWRnZScsXG4gICAgJ2JvdHRvbSc6ICdhZnRlci1lZGdlJyxcbiAgICAnbWlkZGxlJzogJ2NlbnRyYWwnXG4gIH0sXG4gIHN0eWxlczoge1xuICAgICdmaWxsJzogICAgICAgICAgICAgJ2ZpbGwnLFxuICAgICdmaWxsT3BhY2l0eSc6ICAgICAgJ2ZpbGwtb3BhY2l0eScsXG4gICAgJ3N0cm9rZSc6ICAgICAgICAgICAnc3Ryb2tlJyxcbiAgICAnc3Ryb2tlV2lkdGgnOiAgICAgICdzdHJva2Utd2lkdGgnLFxuICAgICdzdHJva2VPcGFjaXR5JzogICAgJ3N0cm9rZS1vcGFjaXR5JyxcbiAgICAnc3Ryb2tlQ2FwJzogICAgICAgICdzdHJva2UtbGluZWNhcCcsXG4gICAgJ3N0cm9rZURhc2gnOiAgICAgICAnc3Ryb2tlLWRhc2hhcnJheScsXG4gICAgJ3N0cm9rZURhc2hPZmZzZXQnOiAnc3Ryb2tlLWRhc2hvZmZzZXQnLFxuICAgICdvcGFjaXR5JzogICAgICAgICAgJ29wYWNpdHknXG4gIH0sXG4gIHN0eWxlUHJvcGVydGllczogW1xuICAgICdmaWxsJyxcbiAgICAnZmlsbE9wYWNpdHknLFxuICAgICdzdHJva2UnLFxuICAgICdzdHJva2VXaWR0aCcsXG4gICAgJ3N0cm9rZU9wYWNpdHknLFxuICAgICdzdHJva2VDYXAnLFxuICAgICdzdHJva2VEYXNoJyxcbiAgICAnc3Ryb2tlRGFzaE9mZnNldCcsXG4gICAgJ29wYWNpdHknXG4gIF1cbn07XG4iXX0=
},{}],79:[function(require,module,exports){
var canvas = require('vega-scenegraph/src/render/canvas'),
svg = require('vega-scenegraph/src/render/svg').string,
View = require('./View');
function HeadlessView(width, height, model) {
View.call(null, width, height, model);
this._type = 'canvas';
this._renderers = {canvas: canvas, svg: svg};
}
var prototype = (HeadlessView.prototype = new View());
prototype.renderer = function(type) {
if(type) this._type = type;
return View.prototype.renderer.apply(this, arguments);
};
prototype.canvas = function() {
return (this._type === 'canvas') ? this._renderer.canvas() : null;
};
prototype.canvasAsync = function(callback) {
var r = this._renderer, view = this;
function wait() {
if (r.pendingImages() === 0) {
view.render(); // re-render with all images
callback(view.canvas());
} else {
setTimeout(wait, 10);
}
}
// if images loading, poll until ready
if (this._type !== 'canvas') return null;
if (r.pendingImages() > 0) { wait(); } else { callback(this.canvas()); }
};
prototype.svg = function() {
return (this._type === 'svg') ? this._renderer.svg() : null;
};
prototype.initialize = function() {
var w = this._width,
h = this._height,
bg = this._bgcolor,
pad = this._padding,
config = this.model().config();
if (this._viewport) {
w = this._viewport[0] - (pad ? pad.left + pad.right : 0);
h = this._viewport[1] - (pad ? pad.top + pad.bottom : 0);
}
this._renderer = (this._renderer || new this._io.Renderer(config.load))
.initialize(null, w, h, pad)
.background(bg);
return this;
};
module.exports = HeadlessView;
},{"./View":81,"vega-scenegraph/src/render/canvas":52,"vega-scenegraph/src/render/svg":68}],80:[function(require,module,exports){
var util = require('datalib/src/util'),
ChangeSet = require('vega-dataflow/src/ChangeSet'),
Base = require('vega-dataflow/src/Graph').prototype,
Node = require('vega-dataflow/src/Node'), // jshint ignore:line
GroupBuilder = require('../scene/GroupBuilder'),
visit = require('../scene/visit'),
config = require('./config');
function Model(cfg) {
this._defs = {};
this._predicates = {};
this._scene = null;
this._node = null;
this._builder = null; // Top-level scenegraph builder
this._reset = {axes: false, legends: false};
this.config(cfg);
Base.init.call(this);
}
var prototype = (Model.prototype = Object.create(Base));
prototype.constructor = Model;
prototype.defs = function(defs) {
if (!arguments.length) return this._defs;
this._defs = defs;
return this;
};
prototype.config = function(cfg) {
if (!arguments.length) return this._config;
this._config = Object.create(config);
for (var name in cfg) {
var x = cfg[name], y = this._config[name];
if (util.isObject(x) && util.isObject(y)) {
util.extend(y, x);
} else {
this._config[name] = x;
}
}
return this;
};
prototype.width = function(width) {
if (this._defs) this._defs.width = width;
if (this._defs && this._defs.marks) this._defs.marks.width = width;
if (this._scene) {
this._scene.items[0].width = width;
this._scene.items[0]._dirty = true;
}
this._reset.axes = true;
return this;
};
prototype.height = function(height) {
if (this._defs) this._defs.height = height;
if (this._defs && this._defs.marks) this._defs.marks.height = height;
if (this._scene) {
this._scene.items[0].height = height;
this._scene.items[0]._dirty = true;
}
this._reset.axes = true;
return this;
};
prototype.node = function() {
return this._node || (this._node = new Node(this));
};
prototype.data = function() {
var data = Base.data.apply(this, arguments);
if (arguments.length > 1) { // new Datasource
this.node().addListener(data.pipeline()[0]);
}
return data;
};
function predicates(name) {
var m = this, pred = {};
if (!util.isArray(name)) return this._predicates[name];
name.forEach(function(n) { pred[n] = m._predicates[n]; });
return pred;
}
prototype.predicate = function(name, predicate) {
if (arguments.length === 1) return predicates.call(this, name);
return (this._predicates[name] = predicate);
};
prototype.predicates = function() { return this._predicates; };
prototype.scene = function(renderer) {
if (!arguments.length) return this._scene;
if (this._builder) this.node().removeListener(this._builder.disconnect());
this._builder = new GroupBuilder(this, this._defs.marks, this._scene={});
this.node().addListener(this._builder.connect());
var p = this._builder.pipeline();
p[p.length-1].addListener(renderer);
return this;
};
prototype.reset = function() {
if (this._scene && this._reset.axes) {
visit(this._scene, function(item) {
if (item.axes) item.axes.forEach(function(axis) { axis.reset(); });
});
this._reset.axes = false;
}
if (this._scene && this._reset.legends) {
visit(this._scene, function(item) {
if (item.legends) item.legends.forEach(function(l) { l.reset(); });
});
this._reset.legends = false;
}
return this;
};
prototype.addListener = function(l) {
this.node().addListener(l);
};
prototype.removeListener = function(l) {
this.node().removeListener(l);
};
prototype.fire = function(cs) {
if (!cs) cs = ChangeSet.create();
this.propagate(cs, this.node());
};
module.exports = Model;
},{"../scene/GroupBuilder":104,"../scene/visit":109,"./config":82,"datalib/src/util":20,"vega-dataflow/src/ChangeSet":26,"vega-dataflow/src/Graph":30,"vega-dataflow/src/Node":31}],81:[function(require,module,exports){
(function (global){
var d3 = (typeof window !== "undefined" ? window.d3 : typeof global !== "undefined" ? global.d3 : null),
util = require('datalib/src/util'),
canvas = require('vega-scenegraph/src/render/canvas'),
svg = require('vega-scenegraph/src/render/svg'),
Node = require('vega-dataflow/src/Node'), // jshint ignore:line
log = require('vega-logging'),
parseStreams = require('../parse/streams'),
Encoder = require('../scene/Encoder'),
Transition = require('../scene/Transition'),
changeset = require('vega-dataflow/src/ChangeSet');
function View(el, width, height) {
this._el = null;
this._model = null;
this._width = this.__width = width || 500;
this._height = this.__height = height || 300;
this._bgcolor = null;
this._autopad = 1;
this._padding = {top:0, left:0, bottom:0, right:0};
this._viewport = null;
this._renderer = null;
this._handler = null;
this._streamer = null; // Targeted update for streaming changes
this._changeset = null;
this._repaint = true; // Full re-render on every re-init
this._renderers = {canvas: canvas, svg: svg};
this._io = canvas;
this._api = {}; // Stash streaming data API sandboxes.
}
var prototype = View.prototype;
prototype.model = function(model) {
if (!arguments.length) return this._model;
if (this._model !== model) {
this._model = model;
this._streamer = new Node(model);
this._changeset = changeset.create();
if (this._handler) this._handler.model(model);
}
return this;
};
// Sandboxed streaming data API
function streaming(src) {
var view = this,
ds = this._model.data(src),
name = ds.name(),
listener = ds.pipeline()[0],
streamer = this._streamer,
api = {};
// If we have it stashed, don't create a new closure.
if (this._api[src]) return this._api[src];
api.insert = function(vals) {
ds.insert(util.duplicate(vals)); // Don't pollute the environment
streamer.addListener(listener);
view._changeset.data[name] = 1;
return api;
};
api.update = function() {
streamer.addListener(listener);
view._changeset.data[name] = 1;
return (ds.update.apply(ds, arguments), api);
};
api.remove = function() {
streamer.addListener(listener);
view._changeset.data[name] = 1;
return (ds.remove.apply(ds, arguments), api);
};
api.values = function() { return ds.values(); };
return (this._api[src] = api);
}
prototype.data = function(data) {
var v = this;
if (!arguments.length) return v._model.dataValues();
else if (util.isString(data)) return streaming.call(v, data);
else if (util.isObject(data)) {
util.keys(data).forEach(function(k) {
var api = streaming.call(v, k);
data[k](api);
});
}
return this;
};
prototype.signal = function(name, value) {
var m = this._model,
cs = this._changeset,
streamer = this._streamer,
setter = name;
if (!arguments.length) return m.signalValues();
else if (arguments.length == 1 && util.isString(name)) return m.signalValues(name);
if (arguments.length == 2) {
setter = {};
setter[name] = value;
}
util.keys(setter).forEach(function(k) {
streamer.addListener(m.signal(k).value(setter[k]));
cs.signals[k] = 1;
cs.reflow = true;
});
return this;
};
prototype.width = function(width) {
if (!arguments.length) return this.__width;
if (this.__width !== width) {
this._width = this.__width = width;
this.model().width(width);
this.initialize();
if (this._strict) this._autopad = 1;
}
return this;
};
prototype.height = function(height) {
if (!arguments.length) return this.__height;
if (this.__height !== height) {
this._height = this.__height = height;
this.model().height(height);
this.initialize();
if (this._strict) this._autopad = 1;
}
return this;
};
prototype.background = function(bgcolor) {
if (!arguments.length) return this._bgcolor;
if (this._bgcolor !== bgcolor) {
this._bgcolor = bgcolor;
this.initialize();
}
return this;
};
prototype.padding = function(pad) {
if (!arguments.length) return this._padding;
if (this._padding !== pad) {
if (util.isString(pad)) {
this._autopad = 1;
this._padding = {top:0, left:0, bottom:0, right:0};
this._strict = (pad === "strict");
} else {
this._autopad = 0;
this._padding = pad;
this._strict = false;
}
if (this._renderer) this._renderer.resize(this._width, this._height, pad);
if (this._handler) this._handler.padding(pad);
}
return (this._repaint = true, this);
};
prototype.autopad = function(opt) {
if (this._autopad < 1) return this;
else this._autopad = 0;
var b = this.model().scene().bounds,
pad = this._padding,
config = this.model().config(),
inset = config.autopadInset,
l = b.x1 < 0 ? Math.ceil(-b.x1) + inset : 0,
t = b.y1 < 0 ? Math.ceil(-b.y1) + inset : 0,
r = b.x2 > this._width ? Math.ceil(+b.x2 - this._width) + inset : 0;
b = b.y2 > this._height ? Math.ceil(+b.y2 - this._height) + inset : 0;
pad = {left:l, top:t, right:r, bottom:b};
if (this._strict) {
this._autopad = 0;
this._padding = pad;
this._width = Math.max(0, this.__width - (l+r));
this._height = Math.max(0, this.__height - (t+b));
this._model.width(this._width)
.height(this._height).reset();
this.initialize()
.update({props:"enter"}).update({props:"update"});
} else {
this.padding(pad).update(opt);
}
return this;
};
prototype.viewport = function(size) {
if (!arguments.length) return this._viewport;
if (this._viewport !== size) {
this._viewport = size;
this.initialize();
}
return this;
};
prototype.renderer = function(type) {
if (!arguments.length) return this._renderer;
if (this._renderers[type]) type = this._renderers[type];
else if (util.isString(type)) throw new Error("Unknown renderer: " + type);
else if (!type) throw new Error("No renderer specified");
if (this._io !== type) {
this._io = type;
this._renderer = null;
this.initialize();
if (this._build) this.render();
}
return this;
};
prototype.initialize = function(el) {
var v = this, prevHandler,
w = v._width, h = v._height, pad = v._padding, bg = v._bgcolor,
config = this.model().config();
if (!arguments.length || el === null) {
el = this._el ? this._el.parentNode : null;
if (!el) return this; // This View cannot init w/o an
}
// clear pre-existing container
d3.select(el).select("div.vega").remove();
// add div container
this._el = el = d3.select(el)
.append("div")
.attr("class", "vega")
.style("position", "relative")
.node();
if (v._viewport) {
d3.select(el)
.style("width", (v._viewport[0] || w)+"px")
.style("height", (v._viewport[1] || h)+"px")
.style("overflow", "auto");
}
// renderer
v._renderer = (v._renderer || new this._io.Renderer(config.load))
.initialize(el, w, h, pad)
.background(bg);
// input handler
prevHandler = v._handler;
v._handler = new this._io.Handler()
.initialize(el, pad, v);
if (prevHandler) {
prevHandler.handlers().forEach(function(h) {
v._handler.on(h.type, h.handler);
});
} else {
// Register event listeners for signal stream definitions.
v._detach = parseStreams(this);
}
return (this._repaint = true, this);
};
prototype.destroy = function() {
if (this._detach) this._detach();
};
function build() {
var v = this;
v._renderNode = new Node(v._model)
.router(true);
v._renderNode.evaluate = function(input) {
log.debug(input, ['rendering']);
var s = v._model.scene(),
h = v._handler,
d;
if (h && h.scene) h.scene(s);
if (input.trans) {
input.trans.start(function(items) { v._renderer.render(s, items); });
} else if (v._repaint) {
v._renderer.render(s);
v._repaint = false;
} else if (input.dirty.length) {
v._renderer.render(s, input.dirty);
}
if (input.dirty.length) {
input.dirty.forEach(function(i) { i._dirty = false; });
s.items[0]._dirty = false;
}
// For all updated datasources, clear their previous values.
for (d in input.data) v._model.data(d).finalize();
return input;
};
return (v._model.scene(v._renderNode), true);
}
prototype.update = function(opt) {
opt = opt || {};
var v = this,
trans = opt.duration ? new Transition(opt.duration, opt.ease) : null;
var cs = v._changeset;
if (trans) cs.trans = trans;
if (opt.props !== undefined) {
if (util.keys(cs.data).length > 0) {
throw Error(
"New data values are not reflected in the visualization." +
" Please call view.update() before updating a specified property set."
);
}
cs.reflow = true;
cs.request = opt.props;
}
var built = v._build;
v._build = v._build || build.call(this);
// If specific items are specified, short-circuit dataflow graph.
// Else-If there are streaming updates, perform a targeted propagation.
// Otherwise, reevaluate the entire model (datasources + scene).
if (opt.items && built) {
Encoder.update(this._model, opt.trans, opt.props, opt.items, cs.dirty);
v._renderNode.evaluate(cs);
} else if (v._streamer.listeners().length && built) {
v._model.propagate(cs, v._streamer);
v._streamer.disconnect();
} else {
v._model.fire(cs);
}
v._changeset = changeset.create();
return v.autopad(opt);
};
prototype.render = function(items) {
this._renderer.render(this._model.scene(), items);
return this;
};
prototype.on = function() {
this._handler.on.apply(this._handler, arguments);
return this;
};
prototype.onSignal = function(name, handler) {
this._model.signal(name).on(handler);
return this;
};
prototype.off = function() {
this._handler.off.apply(this._handler, arguments);
return this;
};
prototype.offSignal = function(name, handler) {
this._model.signal(name).off(handler);
return this;
};
View.factory = function(model) {
var HeadlessView = require('./HeadlessView');
return function(opt) {
opt = opt || {};
var defs = model.defs();
var v = (opt.el ? new View() : new HeadlessView())
.model(model)
.renderer(opt.renderer || "canvas")
.width(defs.width)
.height(defs.height)
.background(defs.background)
.padding(defs.padding)
.viewport(defs.viewport)
.initialize(opt.el);
if (opt.data) v.data(opt.data);
if (opt.hover !== false && opt.el) {
v.on("mouseover", function(evt, item) {
if (item && item.hasPropertySet("hover")) {
this.update({props:"hover", items:item});
}
})
.on("mouseout", function(evt, item) {
if (item && item.hasPropertySet("hover")) {
this.update({props:"update", items:item});
}
});
}
return v;
};
};
module.exports = View;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNyYy9jb3JlL1ZpZXcuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EiLCJmaWxlIjoiZ2VuZXJhdGVkLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXNDb250ZW50IjpbInZhciBkMyA9ICh0eXBlb2Ygd2luZG93ICE9PSBcInVuZGVmaW5lZFwiID8gd2luZG93LmQzIDogdHlwZW9mIGdsb2JhbCAhPT0gXCJ1bmRlZmluZWRcIiA/IGdsb2JhbC5kMyA6IG51bGwpLFxuICAgIHV0aWwgPSByZXF1aXJlKCdkYXRhbGliL3NyYy91dGlsJyksXG4gICAgY2FudmFzID0gcmVxdWlyZSgndmVnYS1zY2VuZWdyYXBoL3NyYy9yZW5kZXIvY2FudmFzJyksXG4gICAgc3ZnID0gcmVxdWlyZSgndmVnYS1zY2VuZWdyYXBoL3NyYy9yZW5kZXIvc3ZnJyksXG4gICAgTm9kZSA9IHJlcXVpcmUoJ3ZlZ2EtZGF0YWZsb3cvc3JjL05vZGUnKSwgLy8ganNoaW50IGlnbm9yZTpsaW5lXG4gICAgbG9nID0gcmVxdWlyZSgndmVnYS1sb2dnaW5nJyksXG4gICAgcGFyc2VTdHJlYW1zID0gcmVxdWlyZSgnLi4vcGFyc2Uvc3RyZWFtcycpLFxuICAgIEVuY29kZXIgPSByZXF1aXJlKCcuLi9zY2VuZS9FbmNvZGVyJyksXG4gICAgVHJhbnNpdGlvbiA9IHJlcXVpcmUoJy4uL3NjZW5lL1RyYW5zaXRpb24nKSxcbiAgICBjaGFuZ2VzZXQgPSByZXF1aXJlKCd2ZWdhLWRhdGFmbG93L3NyYy9DaGFuZ2VTZXQnKTtcblxuZnVuY3Rpb24gVmlldyhlbCwgd2lkdGgsIGhlaWdodCkge1xuICB0aGlzLl9lbCAgICA9IG51bGw7XG4gIHRoaXMuX21vZGVsID0gbnVsbDtcbiAgdGhpcy5fd2lkdGggPSB0aGlzLl9fd2lkdGggPSB3aWR0aCB8fCA1MDA7XG4gIHRoaXMuX2hlaWdodCAgPSB0aGlzLl9faGVpZ2h0ID0gaGVpZ2h0IHx8IDMwMDtcbiAgdGhpcy5fYmdjb2xvciA9IG51bGw7XG4gIHRoaXMuX2F1dG9wYWQgPSAxO1xuICB0aGlzLl9wYWRkaW5nID0ge3RvcDowLCBsZWZ0OjAsIGJvdHRvbTowLCByaWdodDowfTtcbiAgdGhpcy5fdmlld3BvcnQgPSBudWxsO1xuICB0aGlzLl9yZW5kZXJlciA9IG51bGw7XG4gIHRoaXMuX2hhbmRsZXIgID0gbnVsbDtcbiAgdGhpcy5fc3RyZWFtZXIgPSBudWxsOyAvLyBUYXJnZXRlZCB1cGRhdGUgZm9yIHN0cmVhbWluZyBjaGFuZ2VzXG4gIHRoaXMuX2NoYW5nZXNldCA9IG51bGw7XG4gIHRoaXMuX3JlcGFpbnQgPSB0cnVlOyAvLyBGdWxsIHJlLXJlbmRlciBvbiBldmVyeSByZS1pbml0XG4gIHRoaXMuX3JlbmRlcmVycyA9IHtjYW52YXM6IGNhbnZhcywgc3ZnOiBzdmd9O1xuICB0aGlzLl9pbyAgPSBjYW52YXM7XG4gIHRoaXMuX2FwaSA9IHt9OyAvLyBTdGFzaCBzdHJlYW1pbmcgZGF0YSBBUEkgc2FuZGJveGVzLlxufVxuXG52YXIgcHJvdG90eXBlID0gVmlldy5wcm90b3R5cGU7XG5cbnByb3RvdHlwZS5tb2RlbCA9IGZ1bmN0aW9uKG1vZGVsKSB7XG4gIGlmICghYXJndW1lbnRzLmxlbmd0aCkgcmV0dXJuIHRoaXMuX21vZGVsO1xuICBpZiAodGhpcy5fbW9kZWwgIT09IG1vZGVsKSB7XG4gICAgdGhpcy5fbW9kZWwgPSBtb2RlbDtcbiAgICB0aGlzLl9zdHJlYW1lciA9IG5ldyBOb2RlKG1vZGVsKTtcbiAgICB0aGlzLl9jaGFuZ2VzZXQgPSBjaGFuZ2VzZXQuY3JlYXRlKCk7XG4gICAgaWYgKHRoaXMuX2hhbmRsZXIpIHRoaXMuX2hhbmRsZXIubW9kZWwobW9kZWwpO1xuICB9XG4gIHJldHVybiB0aGlzO1xufTtcblxuLy8gU2FuZGJveGVkIHN0cmVhbWluZyBkYXRhIEFQSVxuZnVuY3Rpb24gc3RyZWFtaW5nKHNyYykge1xuICB2YXIgdmlldyA9IHRoaXMsXG4gICAgICBkcyA9IHRoaXMuX21vZGVsLmRhdGEoc3JjKSxcbiAgICAgIG5hbWUgPSBkcy5uYW1lKCksXG4gICAgICBsaXN0ZW5lciA9IGRzLnBpcGVsaW5lKClbMF0sXG4gICAgICBzdHJlYW1lciA9IHRoaXMuX3N0cmVhbWVyLFxuICAgICAgYXBpID0ge307XG5cbiAgLy8gSWYgd2UgaGF2ZSBpdCBzdGFzaGVkLCBkb24ndCBjcmVhdGUgYSBuZXcgY2xvc3VyZS4gXG4gIGlmICh0aGlzLl9hcGlbc3JjXSkgcmV0dXJuIHRoaXMuX2FwaVtzcmNdO1xuXG4gIGFwaS5pbnNlcnQgPSBmdW5jdGlvbih2YWxzKSB7XG4gICAgZHMuaW5zZXJ0KHV0aWwuZHVwbGljYXRlKHZhbHMpKTsgIC8vIERvbid0IHBvbGx1dGUgdGhlIGVudmlyb25tZW50XG4gICAgc3RyZWFtZXIuYWRkTGlzdGVuZXIobGlzdGVuZXIpO1xuICAgIHZpZXcuX2NoYW5nZXNldC5kYXRhW25hbWVdID0gMTtcbiAgICByZXR1cm4gYXBpO1xuICB9O1xuXG4gIGFwaS51cGRhdGUgPSBmdW5jdGlvbigpIHtcbiAgICBzdHJlYW1lci5hZGRMaXN0ZW5lcihsaXN0ZW5lcik7XG4gICAgdmlldy5fY2hhbmdlc2V0LmRhdGFbbmFtZV0gPSAxO1xuICAgIHJldHVybiAoZHMudXBkYXRlLmFwcGx5KGRzLCBhcmd1bWVudHMpLCBhcGkpO1xuICB9O1xuXG4gIGFwaS5yZW1vdmUgPSBmdW5jdGlvbigpIHtcbiAgICBzdHJlYW1lci5hZGRMaXN0ZW5lcihsaXN0ZW5lcik7XG4gICAgdmlldy5fY2hhbmdlc2V0LmRhdGFbbmFtZV0gPSAxO1xuICAgIHJldHVybiAoZHMucmVtb3ZlLmFwcGx5KGRzLCBhcmd1bWVudHMpLCBhcGkpO1xuICB9O1xuXG4gIGFwaS52YWx1ZXMgPSBmdW5jdGlvbigpIHsgcmV0dXJuIGRzLnZhbHVlcygpOyB9OyAgICBcblxuICByZXR1cm4gKHRoaXMuX2FwaVtzcmNdID0gYXBpKTtcbn1cblxucHJvdG90eXBlLmRhdGEgPSBmdW5jdGlvbihkYXRhKSB7XG4gIHZhciB2ID0gdGhpcztcbiAgaWYgKCFhcmd1bWVudHMubGVuZ3RoKSByZXR1cm4gdi5fbW9kZWwuZGF0YVZhbHVlcygpO1xuICBlbHNlIGlmICh1dGlsLmlzU3RyaW5nKGRhdGEpKSByZXR1cm4gc3RyZWFtaW5nLmNhbGwodiwgZGF0YSk7XG4gIGVsc2UgaWYgKHV0aWwuaXNPYmplY3QoZGF0YSkpIHtcbiAgICB1dGlsLmtleXMoZGF0YSkuZm9yRWFjaChmdW5jdGlvbihrKSB7XG4gICAgICB2YXIgYXBpID0gc3RyZWFtaW5nLmNhbGwodiwgayk7XG4gICAgICBkYXRhW2tdKGFwaSk7XG4gICAgfSk7XG4gIH1cbiAgcmV0dXJuIHRoaXM7XG59O1xuXG5wcm90b3R5cGUuc2lnbmFsID0gZnVuY3Rpb24obmFtZSwgdmFsdWUpIHtcbiAgdmFyIG0gID0gdGhpcy5fbW9kZWwsXG4gICAgICBjcyA9IHRoaXMuX2NoYW5nZXNldCxcbiAgICAgIHN0cmVhbWVyID0gdGhpcy5fc3RyZWFtZXIsXG4gICAgICBzZXR0ZXIgPSBuYW1lOyBcblxuICBpZiAoIWFyZ3VtZW50cy5sZW5ndGgpIHJldHVybiBtLnNpZ25hbFZhbHVlcygpO1xuICBlbHNlIGlmIChhcmd1bWVudHMubGVuZ3RoID09IDEgJiYgdXRpbC5pc1N0cmluZyhuYW1lKSkgcmV0dXJuIG0uc2lnbmFsVmFsdWVzKG5hbWUpO1xuXG4gIGlmIChhcmd1bWVudHMubGVuZ3RoID09IDIpIHtcbiAgICBzZXR0ZXIgPSB7fTtcbiAgICBzZXR0ZXJbbmFtZV0gPSB2YWx1ZTtcbiAgfVxuXG4gIHV0aWwua2V5cyhzZXR0ZXIpLmZvckVhY2goZnVuY3Rpb24oaykge1xuICAgIHN0cmVhbWVyLmFkZExpc3RlbmVyKG0uc2lnbmFsKGspLnZhbHVlKHNldHRlcltrXSkpO1xuICAgIGNzLnNpZ25hbHNba10gPSAxO1xuICAgIGNzLnJlZmxvdyA9IHRydWU7XG4gIH0pO1xuXG4gIHJldHVybiB0aGlzO1xufTtcblxucHJvdG90eXBlLndpZHRoID0gZnVuY3Rpb24od2lkdGgpIHtcbiAgaWYgKCFhcmd1bWVudHMubGVuZ3RoKSByZXR1cm4gdGhpcy5fX3dpZHRoO1xuICBpZiAodGhpcy5fX3dpZHRoICE9PSB3aWR0aCkge1xuICAgIHRoaXMuX3dpZHRoID0gdGhpcy5fX3dpZHRoID0gd2lkdGg7XG4gICAgdGhpcy5tb2RlbCgpLndpZHRoKHdpZHRoKTtcbiAgICB0aGlzLmluaXRpYWxpemUoKTtcbiAgICBpZiAodGhpcy5fc3RyaWN0KSB0aGlzLl9hdXRvcGFkID0gMTtcbiAgfVxuICByZXR1cm4gdGhpcztcbn07XG5cbnByb3RvdHlwZS5oZWlnaHQgPSBmdW5jdGlvbihoZWlnaHQpIHtcbiAgaWYgKCFhcmd1bWVudHMubGVuZ3RoKSByZXR1cm4gdGhpcy5fX2hlaWdodDtcbiAgaWYgKHRoaXMuX19oZWlnaHQgIT09IGhlaWdodCkge1xuICAgIHRoaXMuX2hlaWdodCA9IHRoaXMuX19oZWlnaHQgPSBoZWlnaHQ7XG4gICAgdGhpcy5tb2RlbCgpLmhlaWdodChoZWlnaHQpO1xuICAgIHRoaXMuaW5pdGlhbGl6ZSgpO1xuICAgIGlmICh0aGlzLl9zdHJpY3QpIHRoaXMuX2F1dG9wYWQgPSAxO1xuICB9XG4gIHJldHVybiB0aGlzO1xufTtcblxucHJvdG90eXBlLmJhY2tncm91bmQgPSBmdW5jdGlvbihiZ2NvbG9yKSB7XG4gIGlmICghYXJndW1lbnRzLmxlbmd0aCkgcmV0dXJuIHRoaXMuX2JnY29sb3I7XG4gIGlmICh0aGlzLl9iZ2NvbG9yICE9PSBiZ2NvbG9yKSB7XG4gICAgdGhpcy5fYmdjb2xvciA9IGJnY29sb3I7XG4gICAgdGhpcy5pbml0aWFsaXplKCk7XG4gIH1cbiAgcmV0dXJuIHRoaXM7XG59O1xuXG5wcm90b3R5cGUucGFkZGluZyA9IGZ1bmN0aW9uKHBhZCkge1xuICBpZiAoIWFyZ3VtZW50cy5sZW5ndGgpIHJldHVybiB0aGlzLl9wYWRkaW5nO1xuICBpZiAodGhpcy5fcGFkZGluZyAhPT0gcGFkKSB7XG4gICAgaWYgKHV0aWwuaXNTdHJpbmcocGFkKSkge1xuICAgICAgdGhpcy5fYXV0b3BhZCA9IDE7XG4gICAgICB0aGlzLl9wYWRkaW5nID0ge3RvcDowLCBsZWZ0OjAsIGJvdHRvbTowLCByaWdodDowfTtcbiAgICAgIHRoaXMuX3N0cmljdCA9IChwYWQgPT09IFwic3RyaWN0XCIpO1xuICAgIH0gZWxzZSB7XG4gICAgICB0aGlzLl9hdXRvcGFkID0gMDtcbiAgICAgIHRoaXMuX3BhZGRpbmcgPSBwYWQ7XG4gICAgICB0aGlzLl9zdHJpY3QgPSBmYWxzZTtcbiAgICB9XG4gICAgaWYgKHRoaXMuX3JlbmRlcmVyKSB0aGlzLl9yZW5kZXJlci5yZXNpemUodGhpcy5fd2lkdGgsIHRoaXMuX2hlaWdodCwgcGFkKTtcbiAgICBpZiAodGhpcy5faGFuZGxlcikgIHRoaXMuX2hhbmRsZXIucGFkZGluZyhwYWQpO1xuICB9XG4gIHJldHVybiAodGhpcy5fcmVwYWludCA9IHRydWUsIHRoaXMpO1xufTtcblxucHJvdG90eXBlLmF1dG9wYWQgPSBmdW5jdGlvbihvcHQpIHtcbiAgaWYgKHRoaXMuX2F1dG9wYWQgPCAxKSByZXR1cm4gdGhpcztcbiAgZWxzZSB0aGlzLl9hdXRvcGFkID0gMDtcblxuICB2YXIgYiA9IHRoaXMubW9kZWwoKS5zY2VuZSgpLmJvdW5kcyxcbiAgICAgIHBhZCA9IHRoaXMuX3BhZGRpbmcsXG4gICAgICBjb25maWcgPSB0aGlzLm1vZGVsKCkuY29uZmlnKCksXG4gICAgICBpbnNldCA9IGNvbmZpZy5hdXRvcGFkSW5zZXQsXG4gICAgICBsID0gYi54MSA8IDAgPyBNYXRoLmNlaWwoLWIueDEpICsgaW5zZXQgOiAwLFxuICAgICAgdCA9IGIueTEgPCAwID8gTWF0aC5jZWlsKC1iLnkxKSArIGluc2V0IDogMCxcbiAgICAgIHIgPSBiLngyID4gdGhpcy5fd2lkdGggID8gTWF0aC5jZWlsKCtiLngyIC0gdGhpcy5fd2lkdGgpICsgaW5zZXQgOiAwO1xuICBiID0gYi55MiA+IHRoaXMuX2hlaWdodCA/IE1hdGguY2VpbCgrYi55MiAtIHRoaXMuX2hlaWdodCkgKyBpbnNldCA6IDA7XG4gIHBhZCA9IHtsZWZ0OmwsIHRvcDp0LCByaWdodDpyLCBib3R0b206Yn07XG5cbiAgaWYgKHRoaXMuX3N0cmljdCkge1xuICAgIHRoaXMuX2F1dG9wYWQgPSAwO1xuICAgIHRoaXMuX3BhZGRpbmcgPSBwYWQ7XG4gICAgdGhpcy5fd2lkdGggPSBNYXRoLm1heCgwLCB0aGlzLl9fd2lkdGggLSAobCtyKSk7XG4gICAgdGhpcy5faGVpZ2h0ID0gTWF0aC5tYXgoMCwgdGhpcy5fX2hlaWdodCAtICh0K2IpKTtcblxuICAgIHRoaXMuX21vZGVsLndpZHRoKHRoaXMuX3dpZHRoKVxuICAgICAgLmhlaWdodCh0aGlzLl9oZWlnaHQpLnJlc2V0KCk7XG5cbiAgICB0aGlzLmluaXRpYWxpemUoKVxuICAgICAgLnVwZGF0ZSh7cHJvcHM6XCJlbnRlclwifSkudXBkYXRlKHtwcm9wczpcInVwZGF0ZVwifSk7XG4gIH0gZWxzZSB7XG4gICAgdGhpcy5wYWRkaW5nKHBhZCkudXBkYXRlKG9wdCk7XG4gIH1cbiAgcmV0dXJuIHRoaXM7XG59O1xuXG5wcm90b3R5cGUudmlld3BvcnQgPSBmdW5jdGlvbihzaXplKSB7XG4gIGlmICghYXJndW1lbnRzLmxlbmd0aCkgcmV0dXJuIHRoaXMuX3ZpZXdwb3J0O1xuICBpZiAodGhpcy5fdmlld3BvcnQgIT09IHNpemUpIHtcbiAgICB0aGlzLl92aWV3cG9ydCA9IHNpemU7XG4gICAgdGhpcy5pbml0aWFsaXplKCk7XG4gIH1cbiAgcmV0dXJuIHRoaXM7XG59O1xuXG5wcm90b3R5cGUucmVuZGVyZXIgPSBmdW5jdGlvbih0eXBlKSB7XG4gIGlmICghYXJndW1lbnRzLmxlbmd0aCkgcmV0dXJuIHRoaXMuX3JlbmRlcmVyO1xuICBpZiAodGhpcy5fcmVuZGVyZXJzW3R5cGVdKSB0eXBlID0gdGhpcy5fcmVuZGVyZXJzW3R5cGVdO1xuICBlbHNlIGlmICh1dGlsLmlzU3RyaW5nKHR5cGUpKSB0aHJvdyBuZXcgRXJyb3IoXCJVbmtub3duIHJlbmRlcmVyOiBcIiArIHR5cGUpO1xuICBlbHNlIGlmICghdHlwZSkgdGhyb3cgbmV3IEVycm9yKFwiTm8gcmVuZGVyZXIgc3BlY2lmaWVkXCIpO1xuXG4gIGlmICh0aGlzLl9pbyAhPT0gdHlwZSkge1xuICAgIHRoaXMuX2lvID0gdHlwZTtcbiAgICB0aGlzLl9yZW5kZXJlciA9IG51bGw7XG4gICAgdGhpcy5pbml0aWFsaXplKCk7XG4gICAgaWYgKHRoaXMuX2J1aWxkKSB0aGlzLnJlbmRlcigpO1xuICB9XG4gIHJldHVybiB0aGlzO1xufTtcblxucHJvdG90eXBlLmluaXRpYWxpemUgPSBmdW5jdGlvbihlbCkge1xuICB2YXIgdiA9IHRoaXMsIHByZXZIYW5kbGVyLFxuICAgICAgdyA9IHYuX3dpZHRoLCBoID0gdi5faGVpZ2h0LCBwYWQgPSB2Ll9wYWRkaW5nLCBiZyA9IHYuX2JnY29sb3IsXG4gICAgICBjb25maWcgPSB0aGlzLm1vZGVsKCkuY29uZmlnKCk7XG5cbiAgaWYgKCFhcmd1bWVudHMubGVuZ3RoIHx8IGVsID09PSBudWxsKSB7XG4gICAgZWwgPSB0aGlzLl9lbCA/IHRoaXMuX2VsLnBhcmVudE5vZGUgOiBudWxsO1xuICAgIGlmICghZWwpIHJldHVybiB0aGlzOyAgLy8gVGhpcyBWaWV3IGNhbm5vdCBpbml0IHcvbyBhblxuICB9XG5cbiAgLy8gY2xlYXIgcHJlLWV4aXN0aW5nIGNvbnRhaW5lclxuICBkMy5zZWxlY3QoZWwpLnNlbGVjdChcImRpdi52ZWdhXCIpLnJlbW92ZSgpO1xuICBcbiAgLy8gYWRkIGRpdiBjb250YWluZXJcbiAgdGhpcy5fZWwgPSBlbCA9IGQzLnNlbGVjdChlbClcbiAgICAuYXBwZW5kKFwiZGl2XCIpXG4gICAgLmF0dHIoXCJjbGFzc1wiLCBcInZlZ2FcIilcbiAgICAuc3R5bGUoXCJwb3NpdGlvblwiLCBcInJlbGF0aXZlXCIpXG4gICAgLm5vZGUoKTtcbiAgaWYgKHYuX3ZpZXdwb3J0KSB7XG4gICAgZDMuc2VsZWN0KGVsKVxuICAgICAgLnN0eWxlKFwid2lkdGhcIiwgICh2Ll92aWV3cG9ydFswXSB8fCB3KStcInB4XCIpXG4gICAgICAuc3R5bGUoXCJoZWlnaHRcIiwgKHYuX3ZpZXdwb3J0WzFdIHx8IGgpK1wicHhcIilcbiAgICAgIC5zdHlsZShcIm92ZXJmbG93XCIsIFwiYXV0b1wiKTtcbiAgfVxuXG4gIC8vIHJlbmRlcmVyXG4gIHYuX3JlbmRlcmVyID0gKHYuX3JlbmRlcmVyIHx8IG5ldyB0aGlzLl9pby5SZW5kZXJlcihjb25maWcubG9hZCkpXG4gICAgLmluaXRpYWxpemUoZWwsIHcsIGgsIHBhZClcbiAgICAuYmFja2dyb3VuZChiZyk7XG4gIFxuICAvLyBpbnB1dCBoYW5kbGVyXG4gIHByZXZIYW5kbGVyID0gdi5faGFuZGxlcjtcbiAgdi5faGFuZGxlciA9IG5ldyB0aGlzLl9pby5IYW5kbGVyKClcbiAgICAuaW5pdGlhbGl6ZShlbCwgcGFkLCB2KTtcblxuICBpZiAocHJldkhhbmRsZXIpIHtcbiAgICBwcmV2SGFuZGxlci5oYW5kbGVycygpLmZvckVhY2goZnVuY3Rpb24oaCkge1xuICAgICAgdi5faGFuZGxlci5vbihoLnR5cGUsIGguaGFuZGxlcik7XG4gICAgfSk7XG4gIH0gZWxzZSB7XG4gICAgLy8gUmVnaXN0ZXIgZXZlbnQgbGlzdGVuZXJzIGZvciBzaWduYWwgc3RyZWFtIGRlZmluaXRpb25zLlxuICAgIHYuX2RldGFjaCA9IHBhcnNlU3RyZWFtcyh0aGlzKTtcbiAgfVxuICBcbiAgcmV0dXJuICh0aGlzLl9yZXBhaW50ID0gdHJ1ZSwgdGhpcyk7XG59O1xuXG5wcm90b3R5cGUuZGVzdHJveSA9IGZ1bmN0aW9uKCkge1xuICBpZiAodGhpcy5fZGV0YWNoKSB0aGlzLl9kZXRhY2goKTtcbn07XG5cbmZ1bmN0aW9uIGJ1aWxkKCkge1xuICB2YXIgdiA9IHRoaXM7XG4gIHYuX3JlbmRlck5vZGUgPSBuZXcgTm9kZSh2Ll9tb2RlbClcbiAgICAucm91dGVyKHRydWUpO1xuXG4gIHYuX3JlbmRlck5vZGUuZXZhbHVhdGUgPSBmdW5jdGlvbihpbnB1dCkge1xuICAgIGxvZy5kZWJ1ZyhpbnB1dCwgWydyZW5kZXJpbmcnXSk7XG5cbiAgICB2YXIgcyA9IHYuX21vZGVsLnNjZW5lKCksXG4gICAgICAgIGggPSB2Ll9oYW5kbGVyLFxuICAgICAgICBkO1xuXG4gICAgaWYgKGggJiYgaC5zY2VuZSkgaC5zY2VuZShzKTtcblxuICAgIGlmIChpbnB1dC50cmFucykge1xuICAgICAgaW5wdXQudHJhbnMuc3RhcnQoZnVuY3Rpb24oaXRlbXMpIHsgdi5fcmVuZGVyZXIucmVuZGVyKHMsIGl0ZW1zKTsgfSk7XG4gICAgfSBlbHNlIGlmICh2Ll9yZXBhaW50KSB7XG4gICAgICB2Ll9yZW5kZXJlci5yZW5kZXIocyk7XG4gICAgICB2Ll9yZXBhaW50ID0gZmFsc2U7XG4gICAgfSBlbHNlIGlmIChpbnB1dC5kaXJ0eS5sZW5ndGgpIHtcbiAgICAgIHYuX3JlbmRlcmVyLnJlbmRlcihzLCBpbnB1dC5kaXJ0eSk7XG4gICAgfVxuXG4gICAgaWYgKGlucHV0LmRpcnR5Lmxlbmd0aCkge1xuICAgICAgaW5wdXQuZGlydHkuZm9yRWFjaChmdW5jdGlvbihpKSB7IGkuX2RpcnR5ID0gZmFsc2U7IH0pO1xuICAgICAgcy5pdGVtc1swXS5fZGlydHkgPSBmYWxzZTtcbiAgICB9XG5cbiAgICAvLyBGb3IgYWxsIHVwZGF0ZWQgZGF0YXNvdXJjZXMsIGNsZWFyIHRoZWlyIHByZXZpb3VzIHZhbHVlcy5cbiAgICBmb3IgKGQgaW4gaW5wdXQuZGF0YSkgdi5fbW9kZWwuZGF0YShkKS5maW5hbGl6ZSgpO1xuICAgIHJldHVybiBpbnB1dDtcbiAgfTtcblxuICByZXR1cm4gKHYuX21vZGVsLnNjZW5lKHYuX3JlbmRlck5vZGUpLCB0cnVlKTsgIFxufVxuXG5wcm90b3R5cGUudXBkYXRlID0gZnVuY3Rpb24ob3B0KSB7ICAgXG4gIG9wdCA9IG9wdCB8fCB7fTtcbiAgdmFyIHYgPSB0aGlzLFxuICAgICAgdHJhbnMgPSBvcHQuZHVyYXRpb24gPyBuZXcgVHJhbnNpdGlvbihvcHQuZHVyYXRpb24sIG9wdC5lYXNlKSA6IG51bGw7XG5cbiAgdmFyIGNzID0gdi5fY2hhbmdlc2V0O1xuICBpZiAodHJhbnMpIGNzLnRyYW5zID0gdHJhbnM7XG4gIGlmIChvcHQucHJvcHMgIT09IHVuZGVmaW5lZCkge1xuICAgIGlmICh1dGlsLmtleXMoY3MuZGF0YSkubGVuZ3RoID4gMCkge1xuICAgICAgdGhyb3cgRXJyb3IoXG4gICAgICAgIFwiTmV3IGRhdGEgdmFsdWVzIGFyZSBub3QgcmVmbGVjdGVkIGluIHRoZSB2aXN1YWxpemF0aW9uLlwiICtcbiAgICAgICAgXCIgUGxlYXNlIGNhbGwgdmlldy51cGRhdGUoKSBiZWZvcmUgdXBkYXRpbmcgYSBzcGVjaWZpZWQgcHJvcGVydHkgc2V0LlwiXG4gICAgICApO1xuICAgIH1cblxuICAgIGNzLnJlZmxvdyAgPSB0cnVlO1xuICAgIGNzLnJlcXVlc3QgPSBvcHQucHJvcHM7XG4gIH1cblxuICB2YXIgYnVpbHQgPSB2Ll9idWlsZDtcbiAgdi5fYnVpbGQgPSB2Ll9idWlsZCB8fCBidWlsZC5jYWxsKHRoaXMpO1xuXG4gIC8vIElmIHNwZWNpZmljIGl0ZW1zIGFyZSBzcGVjaWZpZWQsIHNob3J0LWNpcmN1aXQgZGF0YWZsb3cgZ3JhcGguXG4gIC8vIEVsc2UtSWYgdGhlcmUgYXJlIHN0cmVhbWluZyB1cGRhdGVzLCBwZXJmb3JtIGEgdGFyZ2V0ZWQgcHJvcGFnYXRpb24uXG4gIC8vIE90aGVyd2lzZSwgcmVldmFsdWF0ZSB0aGUgZW50aXJlIG1vZGVsIChkYXRhc291cmNlcyArIHNjZW5lKS5cbiAgaWYgKG9wdC5pdGVtcyAmJiBidWlsdCkgeyBcbiAgICBFbmNvZGVyLnVwZGF0ZSh0aGlzLl9tb2RlbCwgb3B0LnRyYW5zLCBvcHQucHJvcHMsIG9wdC5pdGVtcywgY3MuZGlydHkpO1xuICAgIHYuX3JlbmRlck5vZGUuZXZhbHVhdGUoY3MpO1xuICB9IGVsc2UgaWYgKHYuX3N0cmVhbWVyLmxpc3RlbmVycygpLmxlbmd0aCAmJiBidWlsdCkge1xuICAgIHYuX21vZGVsLnByb3BhZ2F0ZShjcywgdi5fc3RyZWFtZXIpO1xuICAgIHYuX3N0cmVhbWVyLmRpc2Nvbm5lY3QoKTtcbiAgfSBlbHNlIHtcbiAgICB2Ll9tb2RlbC5maXJlKGNzKTtcbiAgfVxuXG4gIHYuX2NoYW5nZXNldCA9IGNoYW5nZXNldC5jcmVhdGUoKTtcblxuICByZXR1cm4gdi5hdXRvcGFkKG9wdCk7XG59O1xuXG5wcm90b3R5cGUucmVuZGVyID0gZnVuY3Rpb24oaXRlbXMpIHtcbiAgdGhpcy5fcmVuZGVyZXIucmVuZGVyKHRoaXMuX21vZGVsLnNjZW5lKCksIGl0ZW1zKTtcbiAgcmV0dXJuIHRoaXM7XG59O1xuXG5wcm90b3R5cGUub24gPSBmdW5jdGlvbigpIHtcbiAgdGhpcy5faGFuZGxlci5vbi5hcHBseSh0aGlzLl9oYW5kbGVyLCBhcmd1bWVudHMpO1xuICByZXR1cm4gdGhpcztcbn07XG5cbnByb3RvdHlwZS5vblNpZ25hbCA9IGZ1bmN0aW9uKG5hbWUsIGhhbmRsZXIpIHtcbiAgdGhpcy5fbW9kZWwuc2lnbmFsKG5hbWUpLm9uKGhhbmRsZXIpO1xuICByZXR1cm4gdGhpcztcbn07XG5cbnByb3RvdHlwZS5vZmYgPSBmdW5jdGlvbigpIHtcbiAgdGhpcy5faGFuZGxlci5vZmYuYXBwbHkodGhpcy5faGFuZGxlciwgYXJndW1lbnRzKTtcbiAgcmV0dXJuIHRoaXM7XG59O1xuXG5wcm90b3R5cGUub2ZmU2lnbmFsID0gZnVuY3Rpb24obmFtZSwgaGFuZGxlcikge1xuICB0aGlzLl9tb2RlbC5zaWduYWwobmFtZSkub2ZmKGhhbmRsZXIpO1xuICByZXR1cm4gdGhpcztcbn07XG5cblZpZXcuZmFjdG9yeSA9IGZ1bmN0aW9uKG1vZGVsKSB7XG4gIHZhciBIZWFkbGVzc1ZpZXcgPSByZXF1aXJlKCcuL0hlYWRsZXNzVmlldycpO1xuICByZXR1cm4gZnVuY3Rpb24ob3B0KSB7XG4gICAgb3B0ID0gb3B0IHx8IHt9O1xuICAgIHZhciBkZWZzID0gbW9kZWwuZGVmcygpO1xuICAgIHZhciB2ID0gKG9wdC5lbCA/IG5ldyBWaWV3KCkgOiBuZXcgSGVhZGxlc3NWaWV3KCkpXG4gICAgICAubW9kZWwobW9kZWwpXG4gICAgICAucmVuZGVyZXIob3B0LnJlbmRlcmVyIHx8IFwiY2FudmFzXCIpXG4gICAgICAud2lkdGgoZGVmcy53aWR0aClcbiAgICAgIC5oZWlnaHQoZGVmcy5oZWlnaHQpXG4gICAgICAuYmFja2dyb3VuZChkZWZzLmJhY2tncm91bmQpXG4gICAgICAucGFkZGluZyhkZWZzLnBhZGRpbmcpXG4gICAgICAudmlld3BvcnQoZGVmcy52aWV3cG9ydClcbiAgICAgIC5pbml0aWFsaXplKG9wdC5lbCk7XG5cbiAgICBpZiAob3B0LmRhdGEpIHYuZGF0YShvcHQuZGF0YSk7XG5cbiAgICBpZiAob3B0LmhvdmVyICE9PSBmYWxzZSAmJiBvcHQuZWwpIHtcbiAgICAgIHYub24oXCJtb3VzZW92ZXJcIiwgZnVuY3Rpb24oZXZ0LCBpdGVtKSB7XG4gICAgICAgIGlmIChpdGVtICYmIGl0ZW0uaGFzUHJvcGVydHlTZXQoXCJob3ZlclwiKSkge1xuICAgICAgICAgIHRoaXMudXBkYXRlKHtwcm9wczpcImhvdmVyXCIsIGl0ZW1zOml0ZW19KTtcbiAgICAgICAgfVxuICAgICAgfSlcbiAgICAgIC5vbihcIm1vdXNlb3V0XCIsIGZ1bmN0aW9uKGV2dCwgaXRlbSkge1xuICAgICAgICBpZiAoaXRlbSAmJiBpdGVtLmhhc1Byb3BlcnR5U2V0KFwiaG92ZXJcIikpIHtcbiAgICAgICAgICB0aGlzLnVwZGF0ZSh7cHJvcHM6XCJ1cGRhdGVcIiwgaXRlbXM6aXRlbX0pO1xuICAgICAgICB9XG4gICAgICB9KTtcbiAgICB9XG4gIFxuICAgIHJldHVybiB2O1xuICB9OyAgICBcbn07XG5cbm1vZHVsZS5leHBvcnRzID0gVmlldzsiXX0=
},{"../parse/streams":99,"../scene/Encoder":103,"../scene/Transition":106,"./HeadlessView":79,"datalib/src/util":20,"vega-dataflow/src/ChangeSet":26,"vega-dataflow/src/Node":31,"vega-logging":41,"vega-scenegraph/src/render/canvas":52,"vega-scenegraph/src/render/svg":68}],82:[function(require,module,exports){
(function (global){
var d3 = (typeof window !== "undefined" ? window.d3 : typeof global !== "undefined" ? global.d3 : null),
config = {};
config.load = {
// base url for loading external data files
// used only for server-side operation
baseURL: '',
// Allows domain restriction when using data loading via XHR.
// To enable, set it to a list of allowed domains
// e.g., ['wikipedia.org', 'eff.org']
domainWhiteList: false
};
// inset padding for automatic padding calculation
config.autopadInset = 5;
// extensible scale lookup table
// all d3.scale.* instances also supported
config.scale = {
time: d3.time.scale,
utc: d3.time.scale.utc
};
// default rendering settings
config.render = {
lineWidth: 1,
lineCap: 'butt',
font: 'sans-serif',
fontSize: 11
};
// default axis properties
config.axis = {
orient: 'bottom',
ticks: 10,
padding: 3,
axisColor: '#000',
gridColor: '#000',
gridOpacity: 0.15,
tickColor: '#000',
tickLabelColor: '#000',
axisWidth: 1,
tickWidth: 1,
tickSize: 6,
tickLabelFontSize: 11,
tickLabelFont: 'sans-serif',
titleColor: '#000',
titleFont: 'sans-serif',
titleFontSize: 11,
titleFontWeight: 'bold',
titleOffset: 35
};
// default legend properties
config.legend = {
orient: 'right',
offset: 20,
padding: 3,
gradientStrokeColor: '#888',
gradientStrokeWidth: 1,
gradientHeight: 16,
gradientWidth: 100,
labelColor: '#000',
labelFontSize: 10,
labelFont: 'sans-serif',
labelAlign: 'left',
labelBaseline: 'middle',
labelOffset: 8,
symbolShape: 'circle',
symbolSize: 50,
symbolColor: '#888',
symbolStrokeWidth: 1,
titleColor: '#000',
titleFont: 'sans-serif',
titleFontSize: 11,
titleFontWeight: 'bold'
};
// default color values
config.color = {
rgb: [128, 128, 128],
lab: [50, 0, 0],
hcl: [0, 0, 50],
hsl: [0, 0, 0.5]
};
// default scale ranges
config.range = {
category10: [
'#1f77b4',
'#ff7f0e',
'#2ca02c',
'#d62728',
'#9467bd',
'#8c564b',
'#e377c2',
'#7f7f7f',
'#bcbd22',
'#17becf'
],
category20: [
'#1f77b4',
'#aec7e8',
'#ff7f0e',
'#ffbb78',
'#2ca02c',
'#98df8a',
'#d62728',
'#ff9896',
'#9467bd',
'#c5b0d5',
'#8c564b',
'#c49c94',
'#e377c2',
'#f7b6d2',
'#7f7f7f',
'#c7c7c7',
'#bcbd22',
'#dbdb8d',
'#17becf',
'#9edae5'
],
shapes: [
'circle',
'cross',
'diamond',
'square',
'triangle-down',
'triangle-up'
]
};
module.exports = config;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNyYy9jb3JlL2NvbmZpZy5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EiLCJmaWxlIjoiZ2VuZXJhdGVkLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXNDb250ZW50IjpbInZhciBkMyA9ICh0eXBlb2Ygd2luZG93ICE9PSBcInVuZGVmaW5lZFwiID8gd2luZG93LmQzIDogdHlwZW9mIGdsb2JhbCAhPT0gXCJ1bmRlZmluZWRcIiA/IGdsb2JhbC5kMyA6IG51bGwpLFxuICAgIGNvbmZpZyA9IHt9O1xuXG5jb25maWcubG9hZCA9IHtcbiAgLy8gYmFzZSB1cmwgZm9yIGxvYWRpbmcgZXh0ZXJuYWwgZGF0YSBmaWxlc1xuICAvLyB1c2VkIG9ubHkgZm9yIHNlcnZlci1zaWRlIG9wZXJhdGlvblxuICBiYXNlVVJMOiAnJyxcbiAgLy8gQWxsb3dzIGRvbWFpbiByZXN0cmljdGlvbiB3aGVuIHVzaW5nIGRhdGEgbG9hZGluZyB2aWEgWEhSLlxuICAvLyBUbyBlbmFibGUsIHNldCBpdCB0byBhIGxpc3Qgb2YgYWxsb3dlZCBkb21haW5zXG4gIC8vIGUuZy4sIFsnd2lraXBlZGlhLm9yZycsICdlZmYub3JnJ11cbiAgZG9tYWluV2hpdGVMaXN0OiBmYWxzZVxufTtcblxuLy8gaW5zZXQgcGFkZGluZyBmb3IgYXV0b21hdGljIHBhZGRpbmcgY2FsY3VsYXRpb25cbmNvbmZpZy5hdXRvcGFkSW5zZXQgPSA1O1xuXG4vLyBleHRlbnNpYmxlIHNjYWxlIGxvb2t1cCB0YWJsZVxuLy8gYWxsIGQzLnNjYWxlLiogaW5zdGFuY2VzIGFsc28gc3VwcG9ydGVkXG5jb25maWcuc2NhbGUgPSB7XG4gIHRpbWU6IGQzLnRpbWUuc2NhbGUsXG4gIHV0YzogIGQzLnRpbWUuc2NhbGUudXRjXG59O1xuXG4vLyBkZWZhdWx0IHJlbmRlcmluZyBzZXR0aW5nc1xuY29uZmlnLnJlbmRlciA9IHtcbiAgbGluZVdpZHRoOiAxLFxuICBsaW5lQ2FwOiAgICdidXR0JyxcbiAgZm9udDogICAgICAnc2Fucy1zZXJpZicsXG4gIGZvbnRTaXplOiAgMTFcbn07XG5cbi8vIGRlZmF1bHQgYXhpcyBwcm9wZXJ0aWVzXG5jb25maWcuYXhpcyA9IHtcbiAgb3JpZW50OiAnYm90dG9tJyxcbiAgdGlja3M6IDEwLFxuICBwYWRkaW5nOiAzLFxuICBheGlzQ29sb3I6ICcjMDAwJyxcbiAgZ3JpZENvbG9yOiAnIzAwMCcsXG4gIGdyaWRPcGFjaXR5OiAwLjE1LFxuICB0aWNrQ29sb3I6ICcjMDAwJyxcbiAgdGlja0xhYmVsQ29sb3I6ICcjMDAwJyxcbiAgYXhpc1dpZHRoOiAxLFxuICB0aWNrV2lkdGg6IDEsXG4gIHRpY2tTaXplOiA2LFxuICB0aWNrTGFiZWxGb250U2l6ZTogMTEsXG4gIHRpY2tMYWJlbEZvbnQ6ICdzYW5zLXNlcmlmJyxcbiAgdGl0bGVDb2xvcjogJyMwMDAnLFxuICB0aXRsZUZvbnQ6ICdzYW5zLXNlcmlmJyxcbiAgdGl0bGVGb250U2l6ZTogMTEsXG4gIHRpdGxlRm9udFdlaWdodDogJ2JvbGQnLFxuICB0aXRsZU9mZnNldDogMzVcbn07XG5cbi8vIGRlZmF1bHQgbGVnZW5kIHByb3BlcnRpZXNcbmNvbmZpZy5sZWdlbmQgPSB7XG4gIG9yaWVudDogJ3JpZ2h0JyxcbiAgb2Zmc2V0OiAyMCxcbiAgcGFkZGluZzogMyxcbiAgZ3JhZGllbnRTdHJva2VDb2xvcjogJyM4ODgnLFxuICBncmFkaWVudFN0cm9rZVdpZHRoOiAxLFxuICBncmFkaWVudEhlaWdodDogMTYsXG4gIGdyYWRpZW50V2lkdGg6IDEwMCxcbiAgbGFiZWxDb2xvcjogJyMwMDAnLFxuICBsYWJlbEZvbnRTaXplOiAxMCxcbiAgbGFiZWxGb250OiAnc2Fucy1zZXJpZicsXG4gIGxhYmVsQWxpZ246ICdsZWZ0JyxcbiAgbGFiZWxCYXNlbGluZTogJ21pZGRsZScsXG4gIGxhYmVsT2Zmc2V0OiA4LFxuICBzeW1ib2xTaGFwZTogJ2NpcmNsZScsXG4gIHN5bWJvbFNpemU6IDUwLFxuICBzeW1ib2xDb2xvcjogJyM4ODgnLFxuICBzeW1ib2xTdHJva2VXaWR0aDogMSxcbiAgdGl0bGVDb2xvcjogJyMwMDAnLFxuICB0aXRsZUZvbnQ6ICdzYW5zLXNlcmlmJyxcbiAgdGl0bGVGb250U2l6ZTogMTEsXG4gIHRpdGxlRm9udFdlaWdodDogJ2JvbGQnXG59O1xuXG4vLyBkZWZhdWx0IGNvbG9yIHZhbHVlc1xuY29uZmlnLmNvbG9yID0ge1xuICByZ2I6IFsxMjgsIDEyOCwgMTI4XSxcbiAgbGFiOiBbNTAsIDAsIDBdLFxuICBoY2w6IFswLCAwLCA1MF0sXG4gIGhzbDogWzAsIDAsIDAuNV1cbn07XG5cbi8vIGRlZmF1bHQgc2NhbGUgcmFuZ2VzXG5jb25maWcucmFuZ2UgPSB7XG4gIGNhdGVnb3J5MTA6IFtcbiAgICAnIzFmNzdiNCcsXG4gICAgJyNmZjdmMGUnLFxuICAgICcjMmNhMDJjJyxcbiAgICAnI2Q2MjcyOCcsXG4gICAgJyM5NDY3YmQnLFxuICAgICcjOGM1NjRiJyxcbiAgICAnI2UzNzdjMicsXG4gICAgJyM3ZjdmN2YnLFxuICAgICcjYmNiZDIyJyxcbiAgICAnIzE3YmVjZidcbiAgXSxcbiAgY2F0ZWdvcnkyMDogW1xuICAgICcjMWY3N2I0JyxcbiAgICAnI2FlYzdlOCcsXG4gICAgJyNmZjdmMGUnLFxuICAgICcjZmZiYjc4JyxcbiAgICAnIzJjYTAyYycsXG4gICAgJyM5OGRmOGEnLFxuICAgICcjZDYyNzI4JyxcbiAgICAnI2ZmOTg5NicsXG4gICAgJyM5NDY3YmQnLFxuICAgICcjYzViMGQ1JyxcbiAgICAnIzhjNTY0YicsXG4gICAgJyNjNDljOTQnLFxuICAgICcjZTM3N2MyJyxcbiAgICAnI2Y3YjZkMicsXG4gICAgJyM3ZjdmN2YnLFxuICAgICcjYzdjN2M3JyxcbiAgICAnI2JjYmQyMicsXG4gICAgJyNkYmRiOGQnLFxuICAgICcjMTdiZWNmJyxcbiAgICAnIzllZGFlNSdcbiAgXSxcbiAgc2hhcGVzOiBbXG4gICAgJ2NpcmNsZScsXG4gICAgJ2Nyb3NzJyxcbiAgICAnZGlhbW9uZCcsXG4gICAgJ3NxdWFyZScsXG4gICAgJ3RyaWFuZ2xlLWRvd24nLFxuICAgICd0cmlhbmdsZS11cCdcbiAgXVxufTtcblxubW9kdWxlLmV4cG9ydHMgPSBjb25maWc7Il19
},{}],83:[function(require,module,exports){
var util = require('datalib/src/util'),
load = require('datalib/src/import/readers'),
parse = require('../parse'),
Scale = require('../scene/Scale'),
config = require('./config');
function compile(module, opt, schema) {
var s = module.schema;
if (!s) return;
if (s.refs) util.extend(schema.refs, s.refs);
if (s.defs) util.extend(schema.defs, s.defs);
}
module.exports = function(opt) {
var schema = null;
opt = opt || {};
// Compile if we're not loading the schema from a URL.
// Load from a URL to extend the existing base schema.
if (opt.url) {
schema = load.json(util.extend({url: opt.url}, config.load));
} else {
schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Vega Visualization Specification Language",
"defs": {},
"refs": {},
"$ref": "#/defs/spec"
};
util.keys(parse).forEach(function(k) { compile(parse[k], opt, schema); });
// Scales aren't in the parser, add schema manually
compile(Scale, opt, schema);
}
// Extend schema to support custom mark properties or property sets.
if (opt.properties) util.keys(opt.properties).forEach(function(k) {
schema.defs.propset.properties[k] = {"$ref": "#/refs/"+opt.properties[k]+"Value"};
});
if (opt.propertySets) util.keys(opt.propertySets).forEach(function(k) {
schema.defs.mark.properties.properties.properties[k] = {"$ref": "#/defs/propset"};
});
return schema;
};
},{"../parse":89,"../scene/Scale":105,"./config":82,"datalib/src/import/readers":15,"datalib/src/util":20}],84:[function(require,module,exports){
var util = require('datalib/src/util'),
axs = require('../scene/axis');
var ORIENT = {
"x": "bottom",
"y": "left",
"top": "top",
"bottom": "bottom",
"left": "left",
"right": "right"
};
function parseAxes(model, spec, axes, group) {
var config = model.config();
(spec || []).forEach(function(def, index) {
axes[index] = axes[index] || axs(model);
parseAxis(config, def, index, axes[index], group);
});
}
function parseAxis(config, def, index, axis, group) {
// axis scale
if (def.scale !== undefined) {
axis.scale(group.scale(def.scale));
}
// axis orientation
axis.orient(def.orient || ORIENT[def.type]);
// axis offset
axis.offset(def.offset || 0);
// axis layer
axis.layer(def.layer || "front");
// axis grid lines
axis.grid(def.grid || false);
// axis title
axis.title(def.title || null);
// axis title offset
axis.titleOffset(def.titleOffset != null ?
def.titleOffset : config.axis.titleOffset);
// axis values
axis.tickValues(def.values || null);
// axis label formatting
axis.tickFormat(def.format || null);
// axis tick subdivision
axis.tickSubdivide(def.subdivide || 0);
// axis tick padding
axis.tickPadding(def.tickPadding || config.axis.padding);
// axis tick size(s)
var size = [];
if (def.tickSize !== undefined) {
for (var i=0; i<3; ++i) size.push(def.tickSize);
} else {
var ts = config.axis.tickSize;
size = [ts, ts, ts];
}
if (def.tickSizeMajor != null) size[0] = def.tickSizeMajor;
if (def.tickSizeMinor != null) size[1] = def.tickSizeMinor;
if (def.tickSizeEnd != null) size[2] = def.tickSizeEnd;
if (size.length) {
axis.tickSize.apply(axis, size);
}
// axis tick count
axis.tickCount(def.ticks || config.axis.ticks);
// style properties
var p = def.properties;
if (p && p.ticks) {
axis.majorTickProperties(p.majorTicks ?
util.extend({}, p.ticks, p.majorTicks) : p.ticks);
axis.minorTickProperties(p.minorTicks ?
util.extend({}, p.ticks, p.minorTicks) : p.ticks);
} else {
axis.majorTickProperties(p && p.majorTicks || {});
axis.minorTickProperties(p && p.minorTicks || {});
}
axis.tickLabelProperties(p && p.labels || {});
axis.titleProperties(p && p.title || {});
axis.gridLineProperties(p && p.grid || {});
axis.domainProperties(p && p.axis || {});
}
module.exports = parseAxes;
},{"../scene/axis":107,"datalib/src/util":20}],85:[function(require,module,exports){
(function (global){
var d3 = (typeof window !== "undefined" ? window.d3 : typeof global !== "undefined" ? global.d3 : null);
function parseBg(bg) {
// return null if input is null or undefined
if (bg == null) return null;
// run through d3 rgb to sanity check
return d3.rgb(bg) + "";
}
module.exports = parseBg;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNyYy9wYXJzZS9iYWNrZ3JvdW5kLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSIsImZpbGUiOiJnZW5lcmF0ZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlc0NvbnRlbnQiOlsidmFyIGQzID0gKHR5cGVvZiB3aW5kb3cgIT09IFwidW5kZWZpbmVkXCIgPyB3aW5kb3cuZDMgOiB0eXBlb2YgZ2xvYmFsICE9PSBcInVuZGVmaW5lZFwiID8gZ2xvYmFsLmQzIDogbnVsbCk7XG5cbmZ1bmN0aW9uIHBhcnNlQmcoYmcpIHtcbiAgLy8gcmV0dXJuIG51bGwgaWYgaW5wdXQgaXMgbnVsbCBvciB1bmRlZmluZWRcbiAgaWYgKGJnID09IG51bGwpIHJldHVybiBudWxsO1xuICAvLyBydW4gdGhyb3VnaCBkMyByZ2IgdG8gc2FuaXR5IGNoZWNrXG4gIHJldHVybiBkMy5yZ2IoYmcpICsgXCJcIjsgIFxufVxuXG5tb2R1bGUuZXhwb3J0cyA9IHBhcnNlQmc7Il19
},{}],86:[function(require,module,exports){
var load = require('datalib/src/import/load'),
read = require('datalib/src/import/read'),
util = require('datalib/src/util'),
log = require('vega-logging'),
parseTransforms = require('./transforms'),
parseModify = require('./modify');
function parseData(model, spec, callback) {
var config = model.config(),
count = 0;
function loaded(d) {
return function(error, data) {
if (error) {
log.error("LOADING FAILED: " + d.url + " " + error);
} else {
model.data(d.name).values(read(data, d.format));
}
if (--count === 0) callback();
};
}
// process each data set definition
(spec || []).forEach(function(d) {
if (d.url) {
count += 1;
load(util.extend({url: d.url}, config.load), loaded(d));
}
parseData.datasource(model, d);
});
if (count === 0) setTimeout(callback, 1);
return spec;
}
parseData.datasource = function(model, d) {
var transform = (d.transform || []).map(function(t) {
return parseTransforms(model, t);
}),
mod = (d.modify || []).map(function(m) {
return parseModify(model, m, d);
}),
ds = model.data(d.name, mod.concat(transform));
if (d.values) {
ds.values(read(d.values, d.format));
} else if (d.source) {
ds.source(d.source)
.revises(ds.revises()) // If new ds revises, then it's origin must revise too.
.addListener(ds); // Derived ds will be pulsed by its src rather than the model.
model.removeListener(ds.pipeline()[0]);
}
return ds;
};
module.exports = parseData;
},{"./modify":93,"./transforms":100,"datalib/src/import/load":13,"datalib/src/import/read":14,"datalib/src/util":20,"vega-logging":41}],87:[function(require,module,exports){
module.exports = (function() {
/*
* Generated by PEG.js 0.8.0.
*
* http://pegjs.majda.cz/
*/
function peg$subclass(child, parent) {
function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype;
child.prototype = new ctor();
}
function SyntaxError(message, expected, found, offset, line, column) {
this.message = message;
this.expected = expected;
this.found = found;
this.offset = offset;
this.line = line;
this.column = column;
this.name = "SyntaxError";
}
peg$subclass(SyntaxError, Error);
function parse(input) {
var options = arguments.length > 1 ? arguments[1] : {},
peg$FAILED = {},
peg$startRuleFunctions = { start: peg$parsestart },
peg$startRuleFunction = peg$parsestart,
peg$c0 = peg$FAILED,
peg$c1 = ",",
peg$c2 = { type: "literal", value: ",", description: "\",\"" },
peg$c3 = function(o, m) { return [o].concat(m); },
peg$c4 = function(o) { return [o]; },
peg$c5 = "[",
peg$c6 = { type: "literal", value: "[", description: "\"[\"" },
peg$c7 = "]",
peg$c8 = { type: "literal", value: "]", description: "\"]\"" },
peg$c9 = ">",
peg$c10 = { type: "literal", value: ">", description: "\">\"" },
peg$c11 = function(f1, f2, o) { return {start: f1, end: f2, middle: o}; },
peg$c12 = [],
peg$c13 = function(s, f) { return (s.filters = f, s); },
peg$c14 = function(s) { return s; },
peg$c15 = "(",
peg$c16 = { type: "literal", value: "(", description: "\"(\"" },
peg$c17 = ")",
peg$c18 = { type: "literal", value: ")", description: "\")\"" },
peg$c19 = function(m) { return {stream: m}; },
peg$c20 = "@",
peg$c21 = { type: "literal", value: "@", description: "\"@\"" },
peg$c22 = ":",
peg$c23 = { type: "literal", value: ":", description: "\":\"" },
peg$c24 = function(n, e) { return {event: e, name: n}; },
peg$c25 = function(m, e) { return {event: e, mark: m}; },
peg$c26 = function(t, e) { return {event: e, target: t}; },
peg$c27 = function(e) { return {event: e}; },
peg$c28 = function(s) { return {signal: s}; },
peg$c29 = "rect",
peg$c30 = { type: "literal", value: "rect", description: "\"rect\"" },
peg$c31 = "symbol",
peg$c32 = { type: "literal", value: "symbol", description: "\"symbol\"" },
peg$c33 = "path",
peg$c34 = { type: "literal", value: "path", description: "\"path\"" },
peg$c35 = "arc",
peg$c36 = { type: "literal", value: "arc", description: "\"arc\"" },
peg$c37 = "area",
peg$c38 = { type: "literal", value: "area", description: "\"area\"" },
peg$c39 = "line",
peg$c40 = { type: "literal", value: "line", description: "\"line\"" },
peg$c41 = "rule",
peg$c42 = { type: "literal", value: "rule", description: "\"rule\"" },
peg$c43 = "image",
peg$c44 = { type: "literal", value: "image", description: "\"image\"" },
peg$c45 = "text",
peg$c46 = { type: "literal", value: "text", description: "\"text\"" },
peg$c47 = "group",
peg$c48 = { type: "literal", value: "group", description: "\"group\"" },
peg$c49 = "mousedown",
peg$c50 = { type: "literal", value: "mousedown", description: "\"mousedown\"" },
peg$c51 = "mouseup",
peg$c52 = { type: "literal", value: "mouseup", description: "\"mouseup\"" },
peg$c53 = "click",
peg$c54 = { type: "literal", value: "click", description: "\"click\"" },
peg$c55 = "dblclick",
peg$c56 = { type: "literal", value: "dblclick", description: "\"dblclick\"" },
peg$c57 = "wheel",
peg$c58 = { type: "literal", value: "wheel", description: "\"wheel\"" },
peg$c59 = "keydown",
peg$c60 = { type: "literal", value: "keydown", description: "\"keydown\"" },
peg$c61 = "keypress",
peg$c62 = { type: "literal", value: "keypress", description: "\"keypress\"" },
peg$c63 = "keyup",
peg$c64 = { type: "literal", value: "keyup", description: "\"keyup\"" },
peg$c65 = "mousewheel",
peg$c66 = { type: "literal", value: "mousewheel", description: "\"mousewheel\"" },
peg$c67 = "mousemove",
peg$c68 = { type: "literal", value: "mousemove", description: "\"mousemove\"" },
peg$c69 = "mouseout",
peg$c70 = { type: "literal", value: "mouseout", description: "\"mouseout\"" },
peg$c71 = "mouseover",
peg$c72 = { type: "literal", value: "mouseover", description: "\"mouseover\"" },
peg$c73 = "mouseenter",
peg$c74 = { type: "literal", value: "mouseenter", description: "\"mouseenter\"" },
peg$c75 = "touchstart",
peg$c76 = { type: "literal", value: "touchstart", description: "\"touchstart\"" },
peg$c77 = "touchmove",
peg$c78 = { type: "literal", value: "touchmove", description: "\"touchmove\"" },
peg$c79 = "touchend",
peg$c80 = { type: "literal", value: "touchend", description: "\"touchend\"" },
peg$c81 = function(e) { return e; },
peg$c82 = /^[a-zA-Z0-9_\-]/,
peg$c83 = { type: "class", value: "[a-zA-Z0-9_\\-]", description: "[a-zA-Z0-9_\\-]" },
peg$c84 = function(n) { return n.join(""); },
peg$c85 = /^[a-zA-Z0-9\-_ #.>+~[\]=|\^$*]/,
peg$c86 = { type: "class", value: "[a-zA-Z0-9\\-_ #.>+~[\\]=|\\^$*]", description: "[a-zA-Z0-9\\-_ #.>+~[\\]=|\\^$*]" },
peg$c87 = function(c) { return c.join(""); },
peg$c88 = /^['"a-zA-Z0-9_().><=! \t-&|~]/,
peg$c89 = { type: "class", value: "['\"a-zA-Z0-9_().><=! \\t-&|~]", description: "['\"a-zA-Z0-9_().><=! \\t-&|~]" },
peg$c90 = function(v) { return v.join(""); },
peg$c91 = /^[ \t\r\n]/,
peg$c92 = { type: "class", value: "[ \\t\\r\\n]", description: "[ \\t\\r\\n]" },
peg$currPos = 0,
peg$reportedPos = 0,
peg$cachedPos = 0,
peg$cachedPosDetails = { line: 1, column: 1, seenCR: false },
peg$maxFailPos = 0,
peg$maxFailExpected = [],
peg$silentFails = 0,
peg$result;
if ("startRule" in options) {
if (!(options.startRule in peg$startRuleFunctions)) {
throw new Error("Can't start parsing from rule \"" + options.startRule + "\".");
}
peg$startRuleFunction = peg$startRuleFunctions[options.startRule];
}
function text() {
return input.substring(peg$reportedPos, peg$currPos);
}
function offset() {
return peg$reportedPos;
}
function line() {
return peg$computePosDetails(peg$reportedPos).line;
}
function column() {
return peg$computePosDetails(peg$reportedPos).column;
}
function expected(description) {
throw peg$buildException(
null,
[{ type: "other", description: description }],
peg$reportedPos
);
}
function error(message) {
throw peg$buildException(message, null, peg$reportedPos);
}
function peg$computePosDetails(pos) {
function advance(details, startPos, endPos) {
var p, ch;
for (p = startPos; p < endPos; p++) {
ch = input.charAt(p);
if (ch === "\n") {
if (!details.seenCR) { details.line++; }
details.column = 1;
details.seenCR = false;
} else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") {
details.line++;
details.column = 1;
details.seenCR = true;
} else {
details.column++;
details.seenCR = false;
}
}
}
if (peg$cachedPos !== pos) {
if (peg$cachedPos > pos) {
peg$cachedPos = 0;
peg$cachedPosDetails = { line: 1, column: 1, seenCR: false };
}
advance(peg$cachedPosDetails, peg$cachedPos, pos);
peg$cachedPos = pos;
}
return peg$cachedPosDetails;
}
function peg$fail(expected) {
if (peg$currPos < peg$maxFailPos) { return; }
if (peg$currPos > peg$maxFailPos) {
peg$maxFailPos = peg$currPos;
peg$maxFailExpected = [];
}
peg$maxFailExpected.push(expected);
}
function peg$buildException(message, expected, pos) {
function cleanupExpected(expected) {
var i = 1;
expected.sort(function(a, b) {
if (a.description < b.description) {
return -1;
} else if (a.description > b.description) {
return 1;
} else {
return 0;
}
});
while (i < expected.length) {
if (expected[i - 1] === expected[i]) {
expected.splice(i, 1);
} else {
i++;
}
}
}
function buildMessage(expected, found) {
function stringEscape(s) {
function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); }
return s
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\x08/g, '\\b')
.replace(/\t/g, '\\t')
.replace(/\n/g, '\\n')
.replace(/\f/g, '\\f')
.replace(/\r/g, '\\r')
.replace(/[\x00-\x07\x0B\x0E\x0F]/g, function(ch) { return '\\x0' + hex(ch); })
.replace(/[\x10-\x1F\x80-\xFF]/g, function(ch) { return '\\x' + hex(ch); })
.replace(/[\u0180-\u0FFF]/g, function(ch) { return '\\u0' + hex(ch); })
.replace(/[\u1080-\uFFFF]/g, function(ch) { return '\\u' + hex(ch); });
}
var expectedDescs = new Array(expected.length),
expectedDesc, foundDesc, i;
for (i = 0; i < expected.length; i++) {
expectedDescs[i] = expected[i].description;
}
expectedDesc = expected.length > 1
? expectedDescs.slice(0, -1).join(", ")
+ " or "
+ expectedDescs[expected.length - 1]
: expectedDescs[0];
foundDesc = found ? "\"" + stringEscape(found) + "\"" : "end of input";
return "Expected " + expectedDesc + " but " + foundDesc + " found.";
}
var posDetails = peg$computePosDetails(pos),
found = pos < input.length ? input.charAt(pos) : null;
if (expected !== null) {
cleanupExpected(expected);
}
return new SyntaxError(
message !== null ? message : buildMessage(expected, found),
expected,
found,
pos,
posDetails.line,
posDetails.column
);
}
function peg$parsestart() {
var s0;
s0 = peg$parsemerged();
return s0;
}
function peg$parsemerged() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
s1 = peg$parseordered();
if (s1 !== peg$FAILED) {
s2 = peg$parsesep();
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 44) {
s3 = peg$c1;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c2); }
}
if (s3 !== peg$FAILED) {
s4 = peg$parsesep();
if (s4 !== peg$FAILED) {
s5 = peg$parsemerged();
if (s5 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c3(s1, s5);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parseordered();
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c4(s1);
}
s0 = s1;
}
return s0;
}
function peg$parseordered() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 91) {
s1 = peg$c5;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c6); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parsesep();
if (s2 !== peg$FAILED) {
s3 = peg$parsefiltered();
if (s3 !== peg$FAILED) {
s4 = peg$parsesep();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 44) {
s5 = peg$c1;
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c2); }
}
if (s5 !== peg$FAILED) {
s6 = peg$parsesep();
if (s6 !== peg$FAILED) {
s7 = peg$parsefiltered();
if (s7 !== peg$FAILED) {
s8 = peg$parsesep();
if (s8 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 93) {
s9 = peg$c7;
peg$currPos++;
} else {
s9 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c8); }
}
if (s9 !== peg$FAILED) {
s10 = peg$parsesep();
if (s10 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 62) {
s11 = peg$c9;
peg$currPos++;
} else {
s11 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c10); }
}
if (s11 !== peg$FAILED) {
s12 = peg$parsesep();
if (s12 !== peg$FAILED) {
s13 = peg$parseordered();
if (s13 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c11(s3, s7, s13);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$parsefiltered();
}
return s0;
}
function peg$parsefiltered() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$parsestream();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parsefilter();
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parsefilter();
}
} else {
s2 = peg$c0;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c13(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parsestream();
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c14(s1);
}
s0 = s1;
}
return s0;
}
function peg$parsestream() {
var s0, s1, s2, s3, s4;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 40) {
s1 = peg$c15;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c16); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parsemerged();
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 41) {
s3 = peg$c17;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c18); }
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c19(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 64) {
s1 = peg$c20;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c21); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parsename();
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 58) {
s3 = peg$c22;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c23); }
}
if (s3 !== peg$FAILED) {
s4 = peg$parseeventType();
if (s4 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c24(s2, s4);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parsemarkType();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 58) {
s2 = peg$c22;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c23); }
}
if (s2 !== peg$FAILED) {
s3 = peg$parseeventType();
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c25(s1, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parsecss();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 58) {
s2 = peg$c22;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c23); }
}
if (s2 !== peg$FAILED) {
s3 = peg$parseeventType();
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c26(s1, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parseeventType();
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c27(s1);
}
s0 = s1;
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parsename();
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c28(s1);
}
s0 = s1;
}
}
}
}
}
return s0;
}
function peg$parsemarkType() {
var s0;
if (input.substr(peg$currPos, 4) === peg$c29) {
s0 = peg$c29;
peg$currPos += 4;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c30); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 6) === peg$c31) {
s0 = peg$c31;
peg$currPos += 6;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c32); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 4) === peg$c33) {
s0 = peg$c33;
peg$currPos += 4;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c34); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 3) === peg$c35) {
s0 = peg$c35;
peg$currPos += 3;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c36); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 4) === peg$c37) {
s0 = peg$c37;
peg$currPos += 4;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c38); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 4) === peg$c39) {
s0 = peg$c39;
peg$currPos += 4;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c40); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 4) === peg$c41) {
s0 = peg$c41;
peg$currPos += 4;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c42); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 5) === peg$c43) {
s0 = peg$c43;
peg$currPos += 5;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c44); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 4) === peg$c45) {
s0 = peg$c45;
peg$currPos += 4;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c46); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 5) === peg$c47) {
s0 = peg$c47;
peg$currPos += 5;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c48); }
}
}
}
}
}
}
}
}
}
}
return s0;
}
function peg$parseeventType() {
var s0;
if (input.substr(peg$currPos, 9) === peg$c49) {
s0 = peg$c49;
peg$currPos += 9;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c50); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 7) === peg$c51) {
s0 = peg$c51;
peg$currPos += 7;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c52); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 5) === peg$c53) {
s0 = peg$c53;
peg$currPos += 5;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c54); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 8) === peg$c55) {
s0 = peg$c55;
peg$currPos += 8;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c56); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 5) === peg$c57) {
s0 = peg$c57;
peg$currPos += 5;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c58); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 7) === peg$c59) {
s0 = peg$c59;
peg$currPos += 7;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c60); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 8) === peg$c61) {
s0 = peg$c61;
peg$currPos += 8;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c62); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 5) === peg$c63) {
s0 = peg$c63;
peg$currPos += 5;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c64); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 10) === peg$c65) {
s0 = peg$c65;
peg$currPos += 10;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c66); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 9) === peg$c67) {
s0 = peg$c67;
peg$currPos += 9;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c68); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 8) === peg$c69) {
s0 = peg$c69;
peg$currPos += 8;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c70); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 9) === peg$c71) {
s0 = peg$c71;
peg$currPos += 9;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c72); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 10) === peg$c73) {
s0 = peg$c73;
peg$currPos += 10;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c74); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 10) === peg$c75) {
s0 = peg$c75;
peg$currPos += 10;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c76); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 9) === peg$c77) {
s0 = peg$c77;
peg$currPos += 9;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c78); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 8) === peg$c79) {
s0 = peg$c79;
peg$currPos += 8;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c80); }
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
return s0;
}
function peg$parsefilter() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 91) {
s1 = peg$c5;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c6); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parseexpr();
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 93) {
s3 = peg$c7;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c8); }
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c81(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
} else {
peg$currPos = s0;
s0 = peg$c0;
}
return s0;
}
function peg$parsename() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = [];
if (peg$c82.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c83); }
}
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
if (peg$c82.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c83); }
}
}
} else {
s1 = peg$c0;
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c84(s1);
}
s0 = s1;
return s0;
}
function peg$parsecss() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = [];
if (peg$c85.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c86); }
}
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
if (peg$c85.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c86); }
}
}
} else {
s1 = peg$c0;
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c87(s1);
}
s0 = s1;
return s0;
}
function peg$parseexpr() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = [];
if (peg$c88.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c89); }
}
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
if (peg$c88.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c89); }
}
}
} else {
s1 = peg$c0;
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c90(s1);
}
s0 = s1;
return s0;
}
function peg$parsesep() {
var s0, s1;
s0 = [];
if (peg$c91.test(input.charAt(peg$currPos))) {
s1 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c92); }
}
while (s1 !== peg$FAILED) {
s0.push(s1);
if (peg$c91.test(input.charAt(peg$currPos))) {
s1 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c92); }
}
}
return s0;
}
peg$result = peg$startRuleFunction();
if (peg$result !== peg$FAILED && peg$currPos === input.length) {
return peg$result;
} else {
if (peg$result !== peg$FAILED && peg$currPos < input.length) {
peg$fail({ type: "end", description: "end of input" });
}
throw peg$buildException(null, peg$maxFailExpected, peg$maxFailPos);
}
}
return {
SyntaxError: SyntaxError,
parse: parse
};
})();
},{}],88:[function(require,module,exports){
var expr = require('vega-expression'),
args = ['datum', 'event', 'signals'];
module.exports = expr.compiler(args, {
idWhiteList: args,
fieldVar: args[0],
globalVar: args[2],
functions: function(codegen) {
var fn = expr.functions(codegen);
fn.eventItem = function() { return 'event.vg.item'; };
fn.eventGroup = 'event.vg.getGroup';
fn.eventX = 'event.vg.getX';
fn.eventY = 'event.vg.getY';
return fn;
}
});
},{"vega-expression":39}],89:[function(require,module,exports){
module.exports = {
axes: require('./axes'),
background: require('./background'),
data: require('./data'),
events: require('./events'),
expr: require('./expr'),
legends: require('./legends'),
mark: require('./mark'),
marks: require('./marks'),
modify: require('./modify'),
padding: require('./padding'),
predicates: require('./predicates'),
properties: require('./properties'),
signals: require('./signals'),
spec: require('./spec'),
streams: require('./streams'),
transforms: require('./transforms')
};
},{"./axes":84,"./background":85,"./data":86,"./events":87,"./expr":88,"./legends":90,"./mark":91,"./marks":92,"./modify":93,"./padding":94,"./predicates":95,"./properties":96,"./signals":97,"./spec":98,"./streams":99,"./transforms":100}],90:[function(require,module,exports){
var lgnd = require('../scene/legend');
function parseLegends(model, spec, legends, group) {
(spec || []).forEach(function(def, index) {
legends[index] = legends[index] || lgnd(model);
parseLegend(def, index, legends[index], group);
});
}
function parseLegend(def, index, legend, group) {
// legend scales
legend.size (def.size ? group.scale(def.size) : null);
legend.shape (def.shape ? group.scale(def.shape) : null);
legend.fill (def.fill ? group.scale(def.fill) : null);
legend.stroke(def.stroke ? group.scale(def.stroke) : null);
// legend orientation
if (def.orient) legend.orient(def.orient);
// legend offset
if (def.offset != null) legend.offset(def.offset);
// legend title
legend.title(def.title || null);
// legend values
legend.values(def.values || null);
// legend label formatting
legend.format(def.format !== undefined ? def.format : null);
// style properties
var p = def.properties;
legend.titleProperties(p && p.title || {});
legend.labelProperties(p && p.labels || {});
legend.legendProperties(p && p.legend || {});
legend.symbolProperties(p && p.symbols || {});
legend.gradientProperties(p && p.gradient || {});
}
module.exports = parseLegends;
},{"../scene/legend":108}],91:[function(require,module,exports){
var util = require('datalib/src/util'),
parseProperties = require('./properties');
function parseMark(model, mark) {
var props = mark.properties,
group = mark.marks;
// parse mark property definitions
util.keys(props).forEach(function(k) {
props[k] = parseProperties(model, mark.type, props[k]);
});
// parse delay function
if (mark.delay) {
mark.delay = parseProperties(model, mark.type, {delay: mark.delay});
}
// recurse if group type
if (group) {
mark.marks = group.map(function(g) { return parseMark(model, g); });
}
return mark;
}
module.exports = parseMark;
},{"./properties":96,"datalib/src/util":20}],92:[function(require,module,exports){
var parseMark = require('./mark');
function parseRootMark(model, spec, width, height) {
return {
type: "group",
width: width,
height: height,
scales: spec.scales || [],
axes: spec.axes || [],
legends: spec.legends || [],
marks: (spec.marks || []).map(function(m) { return parseMark(model, m); })
};
}
module.exports = parseRootMark;
},{"./mark":91}],93:[function(require,module,exports){
var util = require('datalib/src/util'),
Node = require('vega-dataflow/src/Node'), // jshint ignore:line
Tuple = require('vega-dataflow/src/Tuple'),
Deps = require('vega-dataflow/src/Dependencies'),
log = require('vega-logging');
var Types = {
INSERT: "insert",
REMOVE: "remove",
TOGGLE: "toggle",
CLEAR: "clear"
};
var filter = function(field, value, src, dest) {
for(var i = src.length-1; i >= 0; --i) {
if (src[i][field] == value)
dest.push.apply(dest, src.splice(i, 1));
}
};
function parseModify(model, def, ds) {
var signal = def.signal ? util.field(def.signal) : null,
signalName = signal ? signal[0] : null,
predicate = def.predicate ? model.predicate(def.predicate.name || def.predicate) : null,
reeval = (predicate === null),
node = new Node(model).router(def.type === Types.CLEAR);
node.evaluate = function(input) {
if (predicate !== null) { // TODO: predicate args
var db = model.dataValues(predicate.data||[]);
reeval = predicate.call(predicate, {}, db, model.signalValues(predicate.signals||[]), model._predicates);
}
log.debug(input, [def.type+"ing", reeval]);
if (!reeval) return input;
var datum = {},
value = signal ? model.signalRef(def.signal) : null,
d = model.data(ds.name),
prev = d.revises() ? null : undefined,
t = null;
datum[def.field] = value;
// We have to modify ds._data so that subsequent pulses contain
// our dynamic data. W/o modifying ds._data, only the output
// collector will contain dynamic tuples.
if (def.type === Types.INSERT) {
t = Tuple.ingest(datum, prev);
input.add.push(t);
d._data.push(t);
} else if (def.type === Types.REMOVE) {
filter(def.field, value, input.add, input.rem);
filter(def.field, value, input.mod, input.rem);
d._data = d._data.filter(function(x) { return x[def.field] !== value; });
} else if (def.type === Types.TOGGLE) {
var add = [], rem = [];
filter(def.field, value, input.rem, add);
filter(def.field, value, input.add, rem);
filter(def.field, value, input.mod, rem);
if (!(add.length || rem.length)) add.push(Tuple.ingest(datum));
input.add.push.apply(input.add, add);
d._data.push.apply(d._data, add);
input.rem.push.apply(input.rem, rem);
d._data = d._data.filter(function(x) { return rem.indexOf(x) === -1; });
} else if (def.type === Types.CLEAR) {
input.rem.push.apply(input.rem, input.add);
input.rem.push.apply(input.rem, input.mod);
input.add = [];
input.mod = [];
d._data = [];
}
input.fields[def.field] = 1;
return input;
};
if (signalName) node.dependency(Deps.SIGNALS, signalName);
if (predicate) node.dependency(Deps.SIGNALS, predicate.signals);
return node;
}
module.exports = parseModify;
},{"datalib/src/util":20,"vega-dataflow/src/Dependencies":29,"vega-dataflow/src/Node":31,"vega-dataflow/src/Tuple":34,"vega-logging":41}],94:[function(require,module,exports){
var util = require('datalib/src/util');
function parsePadding(pad) {
if (pad == null) return "auto";
else if (util.isString(pad)) return pad==="strict" ? "strict" : "auto";
else if (util.isObject(pad)) return pad;
var p = util.isNumber(pad) ? pad : 20;
return {top:p, left:p, right:p, bottom:p};
}
module.exports = parsePadding;
},{"datalib/src/util":20}],95:[function(require,module,exports){
var util = require('datalib/src/util');
var types = {
'=': parseComparator,
'==': parseComparator,
'!=': parseComparator,
'>': parseComparator,
'>=': parseComparator,
'<': parseComparator,
'<=': parseComparator,
'and': parseLogical,
'&&': parseLogical,
'or': parseLogical,
'||': parseLogical,
'in': parseIn
};
var nullScale = function() { return 0; };
nullScale.invert = nullScale;
function parsePredicates(model, spec) {
(spec || []).forEach(function(s) {
var parse = types[s.type](model, s);
/* jshint evil:true */
var pred = Function("args", "db", "signals", "predicates", parse.code);
pred.root = function() { return model.scene().items[0]; }; // For global scales
pred.nullScale = nullScale;
pred.isFunction = util.isFunction;
pred.signals = parse.signals;
pred.data = parse.data;
model.predicate(s.name, pred);
});
return spec;
}
function parseSignal(signal, signals) {
var s = util.field(signal),
code = "signals["+s.map(util.str).join("][")+"]";
signals[s[0]] = 1;
return code;
}
function parseOperands(model, operands) {
var decl = [], defs = [],
signals = {}, db = {};
function setSignal(s) { signals[s] = 1; }
function setData(d) { db[d] = 1; }
util.array(operands).forEach(function(o, i) {
var name = "o" + i,
def = "";
if (o.value !== undefined) {
def = util.str(o.value);
} else if (o.arg) {
def = "args["+util.str(o.arg)+"]";
} else if (o.signal) {
def = parseSignal(o.signal, signals);
} else if (o.predicate) {
var ref = o.predicate,
predName = ref && (ref.name || ref),
pred = model.predicate(predName),
p = "predicates["+util.str(predName)+"]";
pred.signals.forEach(setSignal);
pred.data.forEach(setData);
if (util.isObject(ref)) {
util.keys(ref).forEach(function(k) {
if (k === "name") return;
var i = ref[k];
def += "args["+util.str(k)+"] = ";
if (i.signal) {
def += parseSignal(i.signal, signals);
} else if (i.arg) {
def += "args["+util.str(i.arg)+"]";
}
def += ", ";
});
}
def += p+".call("+p+", args, db, signals, predicates)";
}
decl.push(name);
defs.push(name+"=("+def+")");
});
return {
code: "var " + decl.join(", ") + ";\n" + defs.join(";\n") + ";\n",
signals: util.keys(signals),
data: util.keys(db)
};
}
function parseComparator(model, spec) {
var ops = parseOperands(model, spec.operands);
if (spec.type === '=') spec.type = '==';
ops.code += "o0 = o0 instanceof Date ? o0.getTime() : o0;\n" +
"o1 = o1 instanceof Date ? o1.getTime() : o1;\n";
return {
code: ops.code + "return " + ["o0", "o1"].join(spec.type) + ";",
signals: ops.signals,
data: ops.data
};
}
function parseLogical(model, spec) {
var ops = parseOperands(model, spec.operands),
o = [], i = 0, len = spec.operands.length;
while (o.push("o"+i++) < len);
if (spec.type === 'and') spec.type = '&&';
else if (spec.type === 'or') spec.type = '||';
return {
code: ops.code + "return " + o.join(spec.type) + ";",
signals: ops.signals,
data: ops.data
};
}
function parseIn(model, spec) {
var o = [spec.item], code = "";
if (spec.range) o.push.apply(o, spec.range);
if (spec.scale) {
code = parseScale(spec.scale, o);
}
var ops = parseOperands(model, o);
code = ops.code + code + "\n var ordSet = null;\n";
if (spec.data) {
var field = util.field(spec.field).map(util.str);
code += "var where = function(d) { return d["+field.join("][")+"] == o0 };\n";
code += "return db["+util.str(spec.data)+"].filter(where).length > 0;";
} else if (spec.range) {
// TODO: inclusive/exclusive range?
if (spec.scale) {
code += "if (scale.length == 2) {\n" + // inverting ordinal scales
" ordSet = scale(o1, o2);\n" +
"} else {\n" +
" o1 = scale(o1);\no2 = scale(o2);\n" +
"}";
}
code += "return ordSet !== null ? ordSet.indexOf(o0) !== -1 :\n" +
" o1 < o2 ? o1 <= o0 && o0 <= o2 : o2 <= o0 && o0 <= o1;";
}
return {
code: code,
signals: ops.signals,
data: ops.data.concat(spec.data ? [spec.data] : [])
};
}
// Populate ops such that ultimate scale/inversion function will be in `scale` var.
function parseScale(spec, ops) {
var code = "var scale = ",
idx = ops.length;
if (util.isString(spec)) {
ops.push({ value: spec });
code += "this.root().scale(o"+idx+")";
} else if (spec.arg) { // Scale function is being passed as an arg
ops.push(spec);
code += "o"+idx;
} else if (spec.name) { // Full scale parameter {name: ..}
ops.push(util.isString(spec.name) ? {value: spec.name} : spec.name);
code += "(this.isFunction(o"+idx+") ? o"+idx+" : ";
if (spec.scope) {
ops.push(spec.scope);
code += "((o"+(idx+1)+".scale || this.root().scale)(o"+idx+") || this.nullScale)";
} else {
code += "this.root().scale(o"+idx+")";
}
code += ")";
}
if (spec.invert === true) { // Allow spec.invert.arg?
code += ".invert";
}
return code+";\n";
}
module.exports = parsePredicates;
},{"datalib/src/util":20}],96:[function(require,module,exports){
(function (global){
var d3 = (typeof window !== "undefined" ? window.d3 : typeof global !== "undefined" ? global.d3 : null),
template = require('datalib/src/template'),
util = require('datalib/src/util'),
Tuple = require('vega-dataflow/src/Tuple'),
log = require('vega-logging');
var DEPS = ["signals", "scales", "data", "fields"];
function properties(model, mark, spec) {
var config = model.config(),
code = "",
names = util.keys(spec),
i, len, name, ref, vars = {},
deps = {
signals: {},
scales: {},
data: {},
fields: {},
reflow: false
};
code += "var o = trans ? {} : item,\n" +
" dirty = false;\n" +
// Stash for util.template
" signals.datum = item.datum;\n" +
" signals.group = group;\n" +
" signals.parent = group.datum;\n";
function handleDep(p) {
if (ref[p] == null) return;
var k = util.array(ref[p]), i, n;
for (i=0, n=k.length; i<n; ++i) {
deps[p][k[i]] = 1;
}
}
for (i=0, len=names.length; i<len; ++i) {
ref = spec[name = names[i]];
code += (i > 0) ? "\n " : " ";
if (ref.rule) {
ref = rule(model, name, ref.rule);
code += "\n " + ref.code;
} else {
ref = valueRef(config, name, ref);
code += "dirty = this.tpl.set(o, "+util.str(name)+", "+ref.val+") || dirty;";
}
vars[name] = true;
DEPS.forEach(handleDep);
deps.reflow = deps.reflow || ref.reflow;
}
if (vars.x2) {
if (vars.x) {
code += "\n if (o.x > o.x2) { " +
"\n var t = o.x;" +
"\n dirty = this.tpl.set(o, 'x', o.x2) || dirty;" +
"\n dirty = this.tpl.set(o, 'x2', t) || dirty; " +
"\n };";
code += "\n dirty = this.tpl.set(o, 'width', (o.x2 - o.x)) || dirty;";
} else if (vars.width) {
code += "\n dirty = this.tpl.set(o, 'x', (o.x2 - o.width)) || dirty;";
} else {
code += "\n dirty = this.tpl.set(o, 'x', o.x2) || dirty;";
}
}
if (vars.xc) {
if (vars.width) {
code += "\n dirty = this.tpl.set(o, 'x', (o.xc - o.width/2)) || dirty;" ;
} else {
code += "\n dirty = this.tpl.set(o, 'x', o.xc) || dirty;" ;
}
}
if (vars.y2) {
if (vars.y) {
code += "\n if (o.y > o.y2) { " +
"\n var t = o.y;" +
"\n dirty = this.tpl.set(o, 'y', o.y2) || dirty;" +
"\n dirty = this.tpl.set(o, 'y2', t) || dirty;" +
"\n };";
code += "\n dirty = this.tpl.set(o, 'height', (o.y2 - o.y)) || dirty;";
} else if (vars.height) {
code += "\n dirty = this.tpl.set(o, 'y', (o.y2 - o.height)) || dirty;";
} else {
code += "\n dirty = this.tpl.set(o, 'y', o.y2) || dirty;";
}
}
if (vars.yc) {
if (vars.height) {
code += "\n dirty = this.tpl.set(o, 'y', (o.yc - o.height/2)) || dirty;" ;
} else {
code += "\n dirty = this.tpl.set(o, 'y', o.yc) || dirty;" ;
}
}
if (hasPath(mark, vars)) code += "\n dirty = (item.touch(), true);";
code += "\n if (trans) trans.interpolate(item, o);";
code += "\n return dirty;";
try {
/* jshint evil:true */
var encoder = Function("item", "group", "trans", "db",
"signals", "predicates", code);
encoder.tpl = Tuple;
encoder.util = util;
encoder.d3 = d3; // For color spaces
util.extend(encoder, template.context);
return {
encode: encoder,
signals: util.keys(deps.signals),
scales: util.keys(deps.scales),
data: util.keys(deps.data),
fields: util.keys(deps.fields),
reflow: deps.reflow
};
} catch (e) {
log.error(e);
log.log(code);
}
}
function hasPath(mark, vars) {
return vars.path ||
((mark==="area" || mark==="line") &&
(vars.x || vars.x2 || vars.width ||
vars.y || vars.y2 || vars.height ||
vars.tension || vars.interpolate));
}
function rule(model, name, rules) {
var config = model.config(),
signals = [], scales = [], db = [],
inputs = [], code = "";
(rules||[]).forEach(function(r, i) {
var def = r.predicate,
predName = def && (def.name || def),
pred = model.predicate(predName),
p = "predicates["+util.str(predName)+"]",
input = [], args = name+"_arg"+i,
ref;
if (util.isObject(def)) {
util.keys(def).forEach(function(k) {
if (k === "name") return;
var ref = valueRef(config, i, def[k]);
input.push(util.str(k)+": "+ref.val);
if (ref.signals) signals.push.apply(signals, util.array(ref.signals));
if (ref.scales) scales.push.apply(scales, util.array(ref.scales));
});
}
ref = valueRef(config, name, r);
if (ref.signals) signals.push.apply(signals, util.array(ref.signals));
if (ref.scales) scales.push.apply(scales, util.array(ref.scales));
if (predName) {
signals.push.apply(signals, pred.signals);
db.push.apply(db, pred.data);
inputs.push(args+" = {\n "+input.join(",\n ")+"\n }");
code += "if ("+p+".call("+p+","+args+", db, signals, predicates)) {" +
"\n dirty = this.tpl.set(o, "+util.str(name)+", "+ref.val+") || dirty;";
code += rules[i+1] ? "\n } else " : " }";
} else {
code += "{" +
"\n dirty = this.tpl.set(o, "+util.str(name)+", "+ref.val+") || dirty;"+
"\n }\n";
}
});
code = "var " + inputs.join(",\n ") + ";\n " + code;
return {code: code, signals: signals, scales: scales, data: db};
}
function valueRef(config, name, ref) {
if (ref == null) return null;
if (name==="fill" || name==="stroke") {
if (ref.c) {
return colorRef(config, "hcl", ref.h, ref.c, ref.l);
} else if (ref.h || ref.s) {
return colorRef(config, "hsl", ref.h, ref.s, ref.l);
} else if (ref.l || ref.a) {
return colorRef(config, "lab", ref.l, ref.a, ref.b);
} else if (ref.r || ref.g || ref.b) {
return colorRef(config, "rgb", ref.r, ref.g, ref.b);
}
}
// initialize value
var val = null, scale = null,
sgRef = {}, fRef = {}, sRef = {}, tmpl = {},
signals = [], fields = [], reflow = false;
if (ref.template !== undefined) {
val = template.source(ref.template, "signals", tmpl);
util.keys(tmpl).forEach(function(k) {
var f = util.field(k)[0];
if (f === 'parent' || f === 'group') {
reflow = true;
fRef[f] = 1;
} else if (k === 'datum') {
fRef[f] = 1;
} else {
sgRef[f] = 1;
}
});
}
if (ref.value !== undefined) {
val = util.str(ref.value);
}
if (ref.signal !== undefined) {
sgRef = util.field(ref.signal);
val = "signals["+sgRef.map(util.str).join("][")+"]";
signals.push(sgRef.shift());
}
if (ref.field !== undefined) {
ref.field = util.isString(ref.field) ? {datum: ref.field} : ref.field;
fRef = fieldRef(ref.field);
val = fRef.val;
}
if (ref.scale !== undefined) {
sRef = scaleRef(ref.scale);
scale = sRef.val;
// run through scale function if val specified.
// if no val, scale function is predicate arg.
if (val !== null || ref.band || ref.mult || ref.offset) {
val = scale + (ref.band ? ".rangeBand()" :
"("+(val !== null ? val : "item.datum.data")+")");
} else {
val = scale;
}
}
// multiply, offset, return value
val = "(" + (ref.mult?(util.number(ref.mult)+" * "):"") + val + ")" +
(ref.offset ? " + " + util.number(ref.offset) : "");
// Collate dependencies
return {
val: val,
signals: signals.concat(util.array(fRef.signals)).concat(util.array(sRef.signals)),
fields: fields.concat(util.array(fRef.fields)).concat(util.array(sRef.fields)),
scales: ref.scale ? (ref.scale.name || ref.scale) : null, // TODO: connect sRef'd scale?
reflow: reflow || fRef.reflow || sRef.reflow
};
}
function colorRef(config, type, x, y, z) {
var xx = x ? valueRef(config, "", x) : config.color[type][0],
yy = y ? valueRef(config, "", y) : config.color[type][1],
zz = z ? valueRef(config, "", z) : config.color[type][2],
signals = [], scales = [];
[xx, yy, zz].forEach(function(v) {
if (v.signals) signals.push.apply(signals, v.signals);
if (v.scales) scales.push(v.scales);
});
return {
val: "(this.d3." + type + "(" + [xx.val, yy.val, zz.val].join(",") + ') + "")',
signals: signals,
scales: scales
};
}
// {field: {datum: "foo"} } -> item.datum.foo
// {field: {group: "foo"} } -> group.foo
// {field: {parent: "foo"} } -> group.datum.foo
function fieldRef(ref) {
if (util.isString(ref)) {
return {val: util.field(ref).map(util.str).join("][")};
}
// Resolve nesting/parent lookups
var l = ref.level,
nested = (ref.group || ref.parent) && l,
scope = nested ? Array(l).join("group.mark.") : "",
r = fieldRef(ref.datum || ref.group || ref.parent || ref.signal),
val = r.val,
fields = r.fields || [],
signals = r.signals || [],
reflow = r.reflow || false; // Nested fieldrefs trigger full reeval of Encoder.
if (ref.datum) {
val = "item.datum["+val+"]";
fields.push(ref.datum);
} else if (ref.group) {
val = scope+"group["+val+"]";
reflow = true;
} else if (ref.parent) {
val = scope+"group.datum["+val+"]";
reflow = true;
} else if (ref.signal) {
val = "signals["+val+"]";
signals.push(util.field(ref.signal)[0]);
reflow = true;
}
return {val: val, fields: fields, signals: signals, reflow: reflow};
}
// {scale: "x"}
// {scale: {name: "x"}},
// {scale: fieldRef}
function scaleRef(ref) {
var scale = null,
fr = null;
if (util.isString(ref)) {
scale = util.str(ref);
} else if (ref.name) {
scale = util.isString(ref.name) ? util.str(ref.name) : (fr = fieldRef(ref.name)).val;
} else {
scale = (fr = fieldRef(ref)).val;
}
scale = "group.scale("+scale+")";
if (ref.invert) scale += ".invert";
return fr ? (fr.val = scale, fr) : {val: scale};
}
module.exports = properties;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNyYy9wYXJzZS9wcm9wZXJ0aWVzLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwiZmlsZSI6ImdlbmVyYXRlZC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgZDMgPSAodHlwZW9mIHdpbmRvdyAhPT0gXCJ1bmRlZmluZWRcIiA/IHdpbmRvdy5kMyA6IHR5cGVvZiBnbG9iYWwgIT09IFwidW5kZWZpbmVkXCIgPyBnbG9iYWwuZDMgOiBudWxsKSxcbiAgICB0ZW1wbGF0ZSA9IHJlcXVpcmUoJ2RhdGFsaWIvc3JjL3RlbXBsYXRlJyksXG4gICAgdXRpbCA9IHJlcXVpcmUoJ2RhdGFsaWIvc3JjL3V0aWwnKSxcbiAgICBUdXBsZSA9IHJlcXVpcmUoJ3ZlZ2EtZGF0YWZsb3cvc3JjL1R1cGxlJyksXG4gICAgbG9nID0gcmVxdWlyZSgndmVnYS1sb2dnaW5nJyk7XG5cbnZhciBERVBTID0gW1wic2lnbmFsc1wiLCBcInNjYWxlc1wiLCBcImRhdGFcIiwgXCJmaWVsZHNcIl07XG5cbmZ1bmN0aW9uIHByb3BlcnRpZXMobW9kZWwsIG1hcmssIHNwZWMpIHtcbiAgdmFyIGNvbmZpZyA9IG1vZGVsLmNvbmZpZygpLFxuICAgICAgY29kZSA9IFwiXCIsXG4gICAgICBuYW1lcyA9IHV0aWwua2V5cyhzcGVjKSxcbiAgICAgIGksIGxlbiwgbmFtZSwgcmVmLCB2YXJzID0ge30sIFxuICAgICAgZGVwcyA9IHtcbiAgICAgICAgc2lnbmFsczoge30sXG4gICAgICAgIHNjYWxlczogIHt9LFxuICAgICAgICBkYXRhOiAgICB7fSxcbiAgICAgICAgZmllbGRzOiAge30sXG4gICAgICAgIHJlZmxvdzogIGZhbHNlXG4gICAgICB9O1xuICAgICAgXG4gIGNvZGUgKz0gXCJ2YXIgbyA9IHRyYW5zID8ge30gOiBpdGVtLFxcblwiICtcbiAgICAgICAgICBcIiAgICBkaXJ0eSA9IGZhbHNlO1xcblwiICtcbiAgICAgICAgICAvLyBTdGFzaCBmb3IgdXRpbC50ZW1wbGF0ZVxuICAgICAgICAgIFwiICBzaWduYWxzLmRhdHVtICA9IGl0ZW0uZGF0dW07XFxuXCIgKyBcbiAgICAgICAgICBcIiAgc2lnbmFscy5ncm91cCAgPSBncm91cDtcXG5cIiArIFxuICAgICAgICAgIFwiICBzaWduYWxzLnBhcmVudCA9IGdyb3VwLmRhdHVtO1xcblwiO1xuXG4gIGZ1bmN0aW9uIGhhbmRsZURlcChwKSB7XG4gICAgaWYgKHJlZltwXSA9PSBudWxsKSByZXR1cm47XG4gICAgdmFyIGsgPSB1dGlsLmFycmF5KHJlZltwXSksIGksIG47XG4gICAgZm9yIChpPTAsIG49ay5sZW5ndGg7IGk8bjsgKytpKSB7XG4gICAgICBkZXBzW3BdW2tbaV1dID0gMTtcbiAgICB9XG4gIH1cblxuICBmb3IgKGk9MCwgbGVuPW5hbWVzLmxlbmd0aDsgaTxsZW47ICsraSkge1xuICAgIHJlZiA9IHNwZWNbbmFtZSA9IG5hbWVzW2ldXTtcbiAgICBjb2RlICs9IChpID4gMCkgPyBcIlxcbiAgXCIgOiBcIiAgXCI7XG4gICAgaWYgKHJlZi5ydWxlKSB7XG4gICAgICByZWYgPSBydWxlKG1vZGVsLCBuYW1lLCByZWYucnVsZSk7XG4gICAgICBjb2RlICs9IFwiXFxuICBcIiArIHJlZi5jb2RlO1xuICAgIH0gZWxzZSB7XG4gICAgICByZWYgPSB2YWx1ZVJlZihjb25maWcsIG5hbWUsIHJlZik7XG4gICAgICBjb2RlICs9IFwiZGlydHkgPSB0aGlzLnRwbC5zZXQobywgXCIrdXRpbC5zdHIobmFtZSkrXCIsIFwiK3JlZi52YWwrXCIpIHx8IGRpcnR5O1wiO1xuICAgIH1cblxuICAgIHZhcnNbbmFtZV0gPSB0cnVlO1xuICAgIERFUFMuZm9yRWFjaChoYW5kbGVEZXApO1xuICAgIGRlcHMucmVmbG93ID0gZGVwcy5yZWZsb3cgfHwgcmVmLnJlZmxvdztcbiAgfVxuXG4gIGlmICh2YXJzLngyKSB7XG4gICAgaWYgKHZhcnMueCkge1xuICAgICAgY29kZSArPSBcIlxcbiAgaWYgKG8ueCA+IG8ueDIpIHsgXCIgK1xuICAgICAgICAgICAgICBcIlxcbiAgICB2YXIgdCA9IG8ueDtcIiArXG4gICAgICAgICAgICAgIFwiXFxuICAgIGRpcnR5ID0gdGhpcy50cGwuc2V0KG8sICd4Jywgby54MikgfHwgZGlydHk7XCIgK1xuICAgICAgICAgICAgICBcIlxcbiAgICBkaXJ0eSA9IHRoaXMudHBsLnNldChvLCAneDInLCB0KSB8fCBkaXJ0eTsgXCIgK1xuICAgICAgICAgICAgICBcIlxcbiAgfTtcIjtcbiAgICAgIGNvZGUgKz0gXCJcXG4gIGRpcnR5ID0gdGhpcy50cGwuc2V0KG8sICd3aWR0aCcsIChvLngyIC0gby54KSkgfHwgZGlydHk7XCI7XG4gICAgfSBlbHNlIGlmICh2YXJzLndpZHRoKSB7XG4gICAgICBjb2RlICs9IFwiXFxuICBkaXJ0eSA9IHRoaXMudHBsLnNldChvLCAneCcsIChvLngyIC0gby53aWR0aCkpIHx8IGRpcnR5O1wiO1xuICAgIH0gZWxzZSB7XG4gICAgICBjb2RlICs9IFwiXFxuICBkaXJ0eSA9IHRoaXMudHBsLnNldChvLCAneCcsIG8ueDIpIHx8IGRpcnR5O1wiO1xuICAgIH1cbiAgfVxuXG4gIGlmICh2YXJzLnhjKSB7XG4gICAgaWYgKHZhcnMud2lkdGgpIHtcbiAgICAgIGNvZGUgKz0gXCJcXG4gIGRpcnR5ID0gdGhpcy50cGwuc2V0KG8sICd4JywgKG8ueGMgLSBvLndpZHRoLzIpKSB8fCBkaXJ0eTtcIiA7XG4gICAgfSBlbHNlIHtcbiAgICAgIGNvZGUgKz0gXCJcXG4gIGRpcnR5ID0gdGhpcy50cGwuc2V0KG8sICd4Jywgby54YykgfHwgZGlydHk7XCIgO1xuICAgIH1cbiAgfVxuXG4gIGlmICh2YXJzLnkyKSB7XG4gICAgaWYgKHZhcnMueSkge1xuICAgICAgY29kZSArPSBcIlxcbiAgaWYgKG8ueSA+IG8ueTIpIHsgXCIgK1xuICAgICAgICAgICAgICBcIlxcbiAgICB2YXIgdCA9IG8ueTtcIiArXG4gICAgICAgICAgICAgIFwiXFxuICAgIGRpcnR5ID0gdGhpcy50cGwuc2V0KG8sICd5Jywgby55MikgfHwgZGlydHk7XCIgK1xuICAgICAgICAgICAgICBcIlxcbiAgICBkaXJ0eSA9IHRoaXMudHBsLnNldChvLCAneTInLCB0KSB8fCBkaXJ0eTtcIiArXG4gICAgICAgICAgICAgIFwiXFxuICB9O1wiO1xuICAgICAgY29kZSArPSBcIlxcbiAgZGlydHkgPSB0aGlzLnRwbC5zZXQobywgJ2hlaWdodCcsIChvLnkyIC0gby55KSkgfHwgZGlydHk7XCI7XG4gICAgfSBlbHNlIGlmICh2YXJzLmhlaWdodCkge1xuICAgICAgY29kZSArPSBcIlxcbiAgZGlydHkgPSB0aGlzLnRwbC5zZXQobywgJ3knLCAoby55MiAtIG8uaGVpZ2h0KSkgfHwgZGlydHk7XCI7XG4gICAgfSBlbHNlIHtcbiAgICAgIGNvZGUgKz0gXCJcXG4gIGRpcnR5ID0gdGhpcy50cGwuc2V0KG8sICd5Jywgby55MikgfHwgZGlydHk7XCI7XG4gICAgfVxuICB9XG5cbiAgaWYgKHZhcnMueWMpIHtcbiAgICBpZiAodmFycy5oZWlnaHQpIHtcbiAgICAgIGNvZGUgKz0gXCJcXG4gIGRpcnR5ID0gdGhpcy50cGwuc2V0KG8sICd5JywgKG8ueWMgLSBvLmhlaWdodC8yKSkgfHwgZGlydHk7XCIgO1xuICAgIH0gZWxzZSB7XG4gICAgICBjb2RlICs9IFwiXFxuICBkaXJ0eSA9IHRoaXMudHBsLnNldChvLCAneScsIG8ueWMpIHx8IGRpcnR5O1wiIDtcbiAgICB9XG4gIH1cbiAgXG4gIGlmIChoYXNQYXRoKG1hcmssIHZhcnMpKSBjb2RlICs9IFwiXFxuICBkaXJ0eSA9IChpdGVtLnRvdWNoKCksIHRydWUpO1wiO1xuICBjb2RlICs9IFwiXFxuICBpZiAodHJhbnMpIHRyYW5zLmludGVycG9sYXRlKGl0ZW0sIG8pO1wiO1xuICBjb2RlICs9IFwiXFxuICByZXR1cm4gZGlydHk7XCI7XG5cbiAgdHJ5IHtcbiAgICAvKiBqc2hpbnQgZXZpbDp0cnVlICovXG4gICAgdmFyIGVuY29kZXIgPSBGdW5jdGlvbihcIml0ZW1cIiwgXCJncm91cFwiLCBcInRyYW5zXCIsIFwiZGJcIiwgXG4gICAgICBcInNpZ25hbHNcIiwgXCJwcmVkaWNhdGVzXCIsIGNvZGUpO1xuICAgIGVuY29kZXIudHBsICA9IFR1cGxlO1xuICAgIGVuY29kZXIudXRpbCA9IHV0aWw7XG4gICAgZW5jb2Rlci5kMyAgID0gZDM7IC8vIEZvciBjb2xvciBzcGFjZXNcbiAgICB1dGlsLmV4dGVuZChlbmNvZGVyLCB0ZW1wbGF0ZS5jb250ZXh0KTtcbiAgICByZXR1cm4ge1xuICAgICAgZW5jb2RlOiAgZW5jb2RlcixcbiAgICAgIHNpZ25hbHM6IHV0aWwua2V5cyhkZXBzLnNpZ25hbHMpLFxuICAgICAgc2NhbGVzOiAgdXRpbC5rZXlzKGRlcHMuc2NhbGVzKSxcbiAgICAgIGRhdGE6ICAgIHV0aWwua2V5cyhkZXBzLmRhdGEpLFxuICAgICAgZmllbGRzOiAgdXRpbC5rZXlzKGRlcHMuZmllbGRzKSxcbiAgICAgIHJlZmxvdzogIGRlcHMucmVmbG93XG4gICAgfTtcbiAgfSBjYXRjaCAoZSkge1xuICAgIGxvZy5lcnJvcihlKTtcbiAgICBsb2cubG9nKGNvZGUpO1xuICB9XG59XG5cbmZ1bmN0aW9uIGhhc1BhdGgobWFyaywgdmFycykge1xuICByZXR1cm4gdmFycy5wYXRoIHx8XG4gICAgKChtYXJrPT09XCJhcmVhXCIgfHwgbWFyaz09PVwibGluZVwiKSAmJlxuICAgICAgKHZhcnMueCB8fCB2YXJzLngyIHx8IHZhcnMud2lkdGggfHxcbiAgICAgICB2YXJzLnkgfHwgdmFycy55MiB8fCB2YXJzLmhlaWdodCB8fFxuICAgICAgIHZhcnMudGVuc2lvbiB8fCB2YXJzLmludGVycG9sYXRlKSk7XG59XG5cbmZ1bmN0aW9uIHJ1bGUobW9kZWwsIG5hbWUsIHJ1bGVzKSB7XG4gIHZhciBjb25maWcgID0gbW9kZWwuY29uZmlnKCksXG4gICAgICBzaWduYWxzID0gW10sIHNjYWxlcyA9IFtdLCBkYiA9IFtdLFxuICAgICAgaW5wdXRzICA9IFtdLCBjb2RlID0gXCJcIjtcblxuICAocnVsZXN8fFtdKS5mb3JFYWNoKGZ1bmN0aW9uKHIsIGkpIHtcbiAgICB2YXIgZGVmID0gci5wcmVkaWNhdGUsXG4gICAgICAgIHByZWROYW1lID0gZGVmICYmIChkZWYubmFtZSB8fCBkZWYpLFxuICAgICAgICBwcmVkID0gbW9kZWwucHJlZGljYXRlKHByZWROYW1lKSxcbiAgICAgICAgcCA9IFwicHJlZGljYXRlc1tcIit1dGlsLnN0cihwcmVkTmFtZSkrXCJdXCIsXG4gICAgICAgIGlucHV0ID0gW10sIGFyZ3MgPSBuYW1lK1wiX2FyZ1wiK2ksXG4gICAgICAgIHJlZjtcblxuICAgIGlmICh1dGlsLmlzT2JqZWN0KGRlZikpIHtcbiAgICAgIHV0aWwua2V5cyhkZWYpLmZvckVhY2goZnVuY3Rpb24oaykge1xuICAgICAgICBpZiAoayA9PT0gXCJuYW1lXCIpIHJldHVybjtcbiAgICAgICAgdmFyIHJlZiA9IHZhbHVlUmVmKGNvbmZpZywgaSwgZGVmW2tdKTtcbiAgICAgICAgaW5wdXQucHVzaCh1dGlsLnN0cihrKStcIjogXCIrcmVmLnZhbCk7XG4gICAgICAgIGlmIChyZWYuc2lnbmFscykgc2lnbmFscy5wdXNoLmFwcGx5KHNpZ25hbHMsIHV0aWwuYXJyYXkocmVmLnNpZ25hbHMpKTtcbiAgICAgICAgaWYgKHJlZi5zY2FsZXMpICBzY2FsZXMucHVzaC5hcHBseShzY2FsZXMsIHV0aWwuYXJyYXkocmVmLnNjYWxlcykpO1xuICAgICAgfSk7XG4gICAgfVxuXG4gICAgcmVmID0gdmFsdWVSZWYoY29uZmlnLCBuYW1lLCByKTtcbiAgICBpZiAocmVmLnNpZ25hbHMpIHNpZ25hbHMucHVzaC5hcHBseShzaWduYWxzLCB1dGlsLmFycmF5KHJlZi5zaWduYWxzKSk7XG4gICAgaWYgKHJlZi5zY2FsZXMpICBzY2FsZXMucHVzaC5hcHBseShzY2FsZXMsIHV0aWwuYXJyYXkocmVmLnNjYWxlcykpO1xuXG4gICAgaWYgKHByZWROYW1lKSB7XG4gICAgICBzaWduYWxzLnB1c2guYXBwbHkoc2lnbmFscywgcHJlZC5zaWduYWxzKTtcbiAgICAgIGRiLnB1c2guYXBwbHkoZGIsIHByZWQuZGF0YSk7XG4gICAgICBpbnB1dHMucHVzaChhcmdzK1wiID0ge1xcbiAgICBcIitpbnB1dC5qb2luKFwiLFxcbiAgICBcIikrXCJcXG4gIH1cIik7XG4gICAgICBjb2RlICs9IFwiaWYgKFwiK3ArXCIuY2FsbChcIitwK1wiLFwiK2FyZ3MrXCIsIGRiLCBzaWduYWxzLCBwcmVkaWNhdGVzKSkge1wiICtcbiAgICAgICAgXCJcXG4gICAgZGlydHkgPSB0aGlzLnRwbC5zZXQobywgXCIrdXRpbC5zdHIobmFtZSkrXCIsIFwiK3JlZi52YWwrXCIpIHx8IGRpcnR5O1wiO1xuICAgICAgY29kZSArPSBydWxlc1tpKzFdID8gXCJcXG4gIH0gZWxzZSBcIiA6IFwiICB9XCI7XG4gICAgfSBlbHNlIHtcbiAgICAgIGNvZGUgKz0gXCJ7XCIgKyBcbiAgICAgICAgXCJcXG4gICAgZGlydHkgPSB0aGlzLnRwbC5zZXQobywgXCIrdXRpbC5zdHIobmFtZSkrXCIsIFwiK3JlZi52YWwrXCIpIHx8IGRpcnR5O1wiK1xuICAgICAgICBcIlxcbiAgfVxcblwiO1xuICAgIH1cbiAgfSk7XG5cbiAgY29kZSA9IFwidmFyIFwiICsgaW5wdXRzLmpvaW4oXCIsXFxuICAgICAgXCIpICsgXCI7XFxuICBcIiArIGNvZGU7XG4gIHJldHVybiB7Y29kZTogY29kZSwgc2lnbmFsczogc2lnbmFscywgc2NhbGVzOiBzY2FsZXMsIGRhdGE6IGRifTtcbn1cblxuZnVuY3Rpb24gdmFsdWVSZWYoY29uZmlnLCBuYW1lLCByZWYpIHtcbiAgaWYgKHJlZiA9PSBudWxsKSByZXR1cm4gbnVsbDtcblxuICBpZiAobmFtZT09PVwiZmlsbFwiIHx8IG5hbWU9PT1cInN0cm9rZVwiKSB7XG4gICAgaWYgKHJlZi5jKSB7XG4gICAgICByZXR1cm4gY29sb3JSZWYoY29uZmlnLCBcImhjbFwiLCByZWYuaCwgcmVmLmMsIHJlZi5sKTtcbiAgICB9IGVsc2UgaWYgKHJlZi5oIHx8IHJlZi5zKSB7XG4gICAgICByZXR1cm4gY29sb3JSZWYoY29uZmlnLCBcImhzbFwiLCByZWYuaCwgcmVmLnMsIHJlZi5sKTtcbiAgICB9IGVsc2UgaWYgKHJlZi5sIHx8IHJlZi5hKSB7XG4gICAgICByZXR1cm4gY29sb3JSZWYoY29uZmlnLCBcImxhYlwiLCByZWYubCwgcmVmLmEsIHJlZi5iKTtcbiAgICB9IGVsc2UgaWYgKHJlZi5yIHx8IHJlZi5nIHx8IHJlZi5iKSB7XG4gICAgICByZXR1cm4gY29sb3JSZWYoY29uZmlnLCBcInJnYlwiLCByZWYuciwgcmVmLmcsIHJlZi5iKTtcbiAgICB9XG4gIH1cblxuICAvLyBpbml0aWFsaXplIHZhbHVlXG4gIHZhciB2YWwgPSBudWxsLCBzY2FsZSA9IG51bGwsIFxuICAgICAgc2dSZWYgPSB7fSwgZlJlZiA9IHt9LCBzUmVmID0ge30sIHRtcGwgPSB7fSxcbiAgICAgIHNpZ25hbHMgPSBbXSwgZmllbGRzID0gW10sIHJlZmxvdyA9IGZhbHNlO1xuXG4gIGlmIChyZWYudGVtcGxhdGUgIT09IHVuZGVmaW5lZCkge1xuICAgIHZhbCA9IHRlbXBsYXRlLnNvdXJjZShyZWYudGVtcGxhdGUsIFwic2lnbmFsc1wiLCB0bXBsKTtcbiAgICB1dGlsLmtleXModG1wbCkuZm9yRWFjaChmdW5jdGlvbihrKSB7XG4gICAgICB2YXIgZiA9IHV0aWwuZmllbGQoaylbMF07XG4gICAgICBpZiAoZiA9PT0gJ3BhcmVudCcgfHwgZiA9PT0gJ2dyb3VwJykge1xuICAgICAgICByZWZsb3cgPSB0cnVlO1xuICAgICAgICBmUmVmW2ZdID0gMTtcbiAgICAgIH0gZWxzZSBpZiAoayA9PT0gJ2RhdHVtJykge1xuICAgICAgICBmUmVmW2ZdID0gMTtcbiAgICAgIH0gZWxzZSB7XG4gICAgICAgIHNnUmVmW2ZdID0gMTtcbiAgICAgIH1cbiAgICB9KTtcbiAgfVxuXG4gIGlmIChyZWYudmFsdWUgIT09IHVuZGVmaW5lZCkge1xuICAgIHZhbCA9IHV0aWwuc3RyKHJlZi52YWx1ZSk7XG4gIH1cblxuICBpZiAocmVmLnNpZ25hbCAhPT0gdW5kZWZpbmVkKSB7XG4gICAgc2dSZWYgPSB1dGlsLmZpZWxkKHJlZi5zaWduYWwpO1xuICAgIHZhbCA9IFwic2lnbmFsc1tcIitzZ1JlZi5tYXAodXRpbC5zdHIpLmpvaW4oXCJdW1wiKStcIl1cIjsgXG4gICAgc2lnbmFscy5wdXNoKHNnUmVmLnNoaWZ0KCkpO1xuICB9XG5cbiAgaWYgKHJlZi5maWVsZCAhPT0gdW5kZWZpbmVkKSB7XG4gICAgcmVmLmZpZWxkID0gdXRpbC5pc1N0cmluZyhyZWYuZmllbGQpID8ge2RhdHVtOiByZWYuZmllbGR9IDogcmVmLmZpZWxkO1xuICAgIGZSZWYgID0gZmllbGRSZWYocmVmLmZpZWxkKTtcbiAgICB2YWwgPSBmUmVmLnZhbDtcbiAgfVxuXG4gIGlmIChyZWYuc2NhbGUgIT09IHVuZGVmaW5lZCkge1xuICAgIHNSZWYgPSBzY2FsZVJlZihyZWYuc2NhbGUpO1xuICAgIHNjYWxlID0gc1JlZi52YWw7XG5cbiAgICAvLyBydW4gdGhyb3VnaCBzY2FsZSBmdW5jdGlvbiBpZiB2YWwgc3BlY2lmaWVkLlxuICAgIC8vIGlmIG5vIHZhbCwgc2NhbGUgZnVuY3Rpb24gaXMgcHJlZGljYXRlIGFyZy5cbiAgICBpZiAodmFsICE9PSBudWxsIHx8IHJlZi5iYW5kIHx8IHJlZi5tdWx0IHx8IHJlZi5vZmZzZXQpIHtcbiAgICAgIHZhbCA9IHNjYWxlICsgKHJlZi5iYW5kID8gXCIucmFuZ2VCYW5kKClcIiA6IFxuICAgICAgICBcIihcIisodmFsICE9PSBudWxsID8gdmFsIDogXCJpdGVtLmRhdHVtLmRhdGFcIikrXCIpXCIpO1xuICAgIH0gZWxzZSB7XG4gICAgICB2YWwgPSBzY2FsZTtcbiAgICB9XG4gIH1cbiAgXG4gIC8vIG11bHRpcGx5LCBvZmZzZXQsIHJldHVybiB2YWx1ZVxuICB2YWwgPSBcIihcIiArIChyZWYubXVsdD8odXRpbC5udW1iZXIocmVmLm11bHQpK1wiICogXCIpOlwiXCIpICsgdmFsICsgXCIpXCIgK1xuICAgICAgICAocmVmLm9mZnNldCA/IFwiICsgXCIgKyB1dGlsLm51bWJlcihyZWYub2Zmc2V0KSA6IFwiXCIpO1xuXG4gIC8vIENvbGxhdGUgZGVwZW5kZW5jaWVzXG4gIHJldHVybiB7XG4gICAgdmFsOiB2YWwsXG4gICAgc2lnbmFsczogc2lnbmFscy5jb25jYXQodXRpbC5hcnJheShmUmVmLnNpZ25hbHMpKS5jb25jYXQodXRpbC5hcnJheShzUmVmLnNpZ25hbHMpKSxcbiAgICBmaWVsZHM6ICBmaWVsZHMuY29uY2F0KHV0aWwuYXJyYXkoZlJlZi5maWVsZHMpKS5jb25jYXQodXRpbC5hcnJheShzUmVmLmZpZWxkcykpLFxuICAgIHNjYWxlczogIHJlZi5zY2FsZSA/IChyZWYuc2NhbGUubmFtZSB8fCByZWYuc2NhbGUpIDogbnVsbCwgLy8gVE9ETzogY29ubmVjdCBzUmVmJ2Qgc2NhbGU/XG4gICAgcmVmbG93OiAgcmVmbG93IHx8IGZSZWYucmVmbG93IHx8IHNSZWYucmVmbG93XG4gIH07XG59XG5cbmZ1bmN0aW9uIGNvbG9yUmVmKGNvbmZpZywgdHlwZSwgeCwgeSwgeikge1xuICB2YXIgeHggPSB4ID8gdmFsdWVSZWYoY29uZmlnLCBcIlwiLCB4KSA6IGNvbmZpZy5jb2xvclt0eXBlXVswXSxcbiAgICAgIHl5ID0geSA/IHZhbHVlUmVmKGNvbmZpZywgXCJcIiwgeSkgOiBjb25maWcuY29sb3JbdHlwZV1bMV0sXG4gICAgICB6eiA9IHogPyB2YWx1ZVJlZihjb25maWcsIFwiXCIsIHopIDogY29uZmlnLmNvbG9yW3R5cGVdWzJdLFxuICAgICAgc2lnbmFscyA9IFtdLCBzY2FsZXMgPSBbXTtcblxuICBbeHgsIHl5LCB6el0uZm9yRWFjaChmdW5jdGlvbih2KSB7XG4gICAgaWYgKHYuc2lnbmFscykgc2lnbmFscy5wdXNoLmFwcGx5KHNpZ25hbHMsIHYuc2lnbmFscyk7XG4gICAgaWYgKHYuc2NhbGVzKSAgc2NhbGVzLnB1c2godi5zY2FsZXMpO1xuICB9KTtcblxuICByZXR1cm4ge1xuICAgIHZhbDogXCIodGhpcy5kMy5cIiArIHR5cGUgKyBcIihcIiArIFt4eC52YWwsIHl5LnZhbCwgenoudmFsXS5qb2luKFwiLFwiKSArICcpICsgXCJcIiknLFxuICAgIHNpZ25hbHM6IHNpZ25hbHMsXG4gICAgc2NhbGVzOiBzY2FsZXNcbiAgfTtcbn1cblxuLy8ge2ZpZWxkOiB7ZGF0dW06IFwiZm9vXCJ9IH0gIC0+IGl0ZW0uZGF0dW0uZm9vXG4vLyB7ZmllbGQ6IHtncm91cDogXCJmb29cIn0gfSAgLT4gZ3JvdXAuZm9vXG4vLyB7ZmllbGQ6IHtwYXJlbnQ6IFwiZm9vXCJ9IH0gLT4gZ3JvdXAuZGF0dW0uZm9vXG5mdW5jdGlvbiBmaWVsZFJlZihyZWYpIHtcbiAgaWYgKHV0aWwuaXNTdHJpbmcocmVmKSkge1xuICAgIHJldHVybiB7dmFsOiB1dGlsLmZpZWxkKHJlZikubWFwKHV0aWwuc3RyKS5qb2luKFwiXVtcIil9O1xuICB9IFxuXG4gIC8vIFJlc29sdmUgbmVzdGluZy9wYXJlbnQgbG9va3Vwc1xuICB2YXIgbCA9IHJlZi5sZXZlbCxcbiAgICAgIG5lc3RlZCA9IChyZWYuZ3JvdXAgfHwgcmVmLnBhcmVudCkgJiYgbCxcbiAgICAgIHNjb3BlID0gbmVzdGVkID8gQXJyYXkobCkuam9pbihcImdyb3VwLm1hcmsuXCIpIDogXCJcIixcbiAgICAgIHIgPSBmaWVsZFJlZihyZWYuZGF0dW0gfHwgcmVmLmdyb3VwIHx8IHJlZi5wYXJlbnQgfHwgcmVmLnNpZ25hbCksXG4gICAgICB2YWwgPSByLnZhbCxcbiAgICAgIGZpZWxkcyAgPSByLmZpZWxkcyAgfHwgW10sXG4gICAgICBzaWduYWxzID0gci5zaWduYWxzIHx8IFtdLFxuICAgICAgcmVmbG93ICA9IHIucmVmbG93ICB8fCBmYWxzZTsgLy8gTmVzdGVkIGZpZWxkcmVmcyB0cmlnZ2VyIGZ1bGwgcmVldmFsIG9mIEVuY29kZXIuXG5cbiAgaWYgKHJlZi5kYXR1bSkge1xuICAgIHZhbCA9IFwiaXRlbS5kYXR1bVtcIit2YWwrXCJdXCI7XG4gICAgZmllbGRzLnB1c2gocmVmLmRhdHVtKTtcbiAgfSBlbHNlIGlmIChyZWYuZ3JvdXApIHtcbiAgICB2YWwgPSBzY29wZStcImdyb3VwW1wiK3ZhbCtcIl1cIjtcbiAgICByZWZsb3cgPSB0cnVlO1xuICB9IGVsc2UgaWYgKHJlZi5wYXJlbnQpIHtcbiAgICB2YWwgPSBzY29wZStcImdyb3VwLmRhdHVtW1wiK3ZhbCtcIl1cIjtcbiAgICByZWZsb3cgPSB0cnVlO1xuICB9IGVsc2UgaWYgKHJlZi5zaWduYWwpIHtcbiAgICB2YWwgPSBcInNpZ25hbHNbXCIrdmFsK1wiXVwiO1xuICAgIHNpZ25hbHMucHVzaCh1dGlsLmZpZWxkKHJlZi5zaWduYWwpWzBdKTtcbiAgICByZWZsb3cgPSB0cnVlO1xuICB9XG5cbiAgcmV0dXJuIHt2YWw6IHZhbCwgZmllbGRzOiBmaWVsZHMsIHNpZ25hbHM6IHNpZ25hbHMsIHJlZmxvdzogcmVmbG93fTtcbn1cblxuLy8ge3NjYWxlOiBcInhcIn1cbi8vIHtzY2FsZToge25hbWU6IFwieFwifX0sXG4vLyB7c2NhbGU6IGZpZWxkUmVmfVxuZnVuY3Rpb24gc2NhbGVSZWYocmVmKSB7XG4gIHZhciBzY2FsZSA9IG51bGwsXG4gICAgICBmciA9IG51bGw7XG5cbiAgaWYgKHV0aWwuaXNTdHJpbmcocmVmKSkge1xuICAgIHNjYWxlID0gdXRpbC5zdHIocmVmKTtcbiAgfSBlbHNlIGlmIChyZWYubmFtZSkge1xuICAgIHNjYWxlID0gdXRpbC5pc1N0cmluZyhyZWYubmFtZSkgPyB1dGlsLnN0cihyZWYubmFtZSkgOiAoZnIgPSBmaWVsZFJlZihyZWYubmFtZSkpLnZhbDtcbiAgfSBlbHNlIHtcbiAgICBzY2FsZSA9IChmciA9IGZpZWxkUmVmKHJlZikpLnZhbDtcbiAgfVxuXG4gIHNjYWxlID0gXCJncm91cC5zY2FsZShcIitzY2FsZStcIilcIjtcbiAgaWYgKHJlZi5pbnZlcnQpIHNjYWxlICs9IFwiLmludmVydFwiO1xuXG4gIHJldHVybiBmciA/IChmci52YWwgPSBzY2FsZSwgZnIpIDoge3ZhbDogc2NhbGV9O1xufVxuXG5tb2R1bGUuZXhwb3J0cyA9IHByb3BlcnRpZXM7Il19
},{"datalib/src/template":18,"datalib/src/util":20,"vega-dataflow/src/Tuple":34,"vega-logging":41}],97:[function(require,module,exports){
var util = require('datalib/src/util'),
functions = require('vega-expression/src/functions')(),
Deps = require('vega-dataflow/src/Dependencies'),
expr = require('./expr');
var RESERVED = ['datum', 'event', 'signals'].concat(util.keys(functions));
function parseSignals(model, spec) {
// process each signal definition
(spec || []).forEach(function(s) {
if (RESERVED.indexOf(s.name) !== -1) {
throw Error('Signal name "'+s.name+'" is a '+
'reserved keyword ('+RESERVED.join(', ')+').');
}
var signal = model.signal(s.name, s.init)
.verbose(s.verbose);
if (s.init && s.init.expr) {
s.init.expr = expr(s.init.expr);
signal.value(exprVal(model, s.init));
}
if (s.expr) {
s.expr = expr(s.expr);
signal.evaluate = function(input) {
var val = exprVal(model, s);
if (val !== signal.value() || signal.verbose()) {
signal.value(val);
input.signals[s.name] = 1;
return input;
}
return model.doNotPropagate;
};
signal.dependency(Deps.SIGNALS, s.expr.globals);
s.expr.globals.forEach(function(dep) {
model.signal(dep).addListener(signal);
});
}
});
return spec;
}
function exprVal(model, spec) {
var e = spec.expr,
val = e.fn(null, null, model.signalValues(e.globals));
return spec.scale ? parseSignals.scale(model, spec, val) : val;
}
parseSignals.scale = function scale(model, spec, value, datum, evt) {
var def = spec.scale,
name = def.name || def.signal || def,
scope = def.scope, e;
if (scope) {
if (scope.signal) {
scope = model.signalRef(scope.signal);
} else if (util.isString(scope)) { // Scope is an expression
e = def._expr = (def._expr || expr(scope));
scope = e.fn(datum, evt, model.signalValues(e.globals));
}
}
if (!scope || !scope.scale) {
scope = (scope && scope.mark) ? scope.mark.group : model.scene().items[0];
}
var s = scope.scale(name);
return !s ? value : (def.invert ? s.invert(value) : s(value));
};
module.exports = parseSignals;
},{"./expr":88,"datalib/src/util":20,"vega-dataflow/src/Dependencies":29,"vega-expression/src/functions":38}],98:[function(require,module,exports){
var load = require('datalib/src/import/load'),
util = require('datalib/src/util'),
log = require('vega-logging'),
Model = require('../core/Model'),
View = require('../core/View'),
parseBg = require('../parse/background'),
parsePadding = require('../parse/padding'),
parseMarks = require('../parse/marks'),
parseSignals = require('../parse/signals'),
parsePredicates = require('../parse/predicates'),
parseData = require('../parse/data');
function parseSpec(spec, callback) {
var vf = arguments[arguments.length-1],
viewFactory = arguments.length > 2 && util.isFunction(vf) ? vf : View.factory,
config = arguments[2] !== viewFactory ? arguments[2] : {},
model = new Model(config);
function parse(spec) {
// protect against subsequent spec modification
spec = util.duplicate(spec);
var width = spec.width || 500,
height = spec.height || 500,
viewport = spec.viewport || null;
model.defs({
width: width,
height: height,
viewport: viewport,
background: parseBg(spec.background),
padding: parsePadding(spec.padding),
signals: parseSignals(model, spec.signals),
predicates: parsePredicates(model, spec.predicates),
marks: parseMarks(model, spec, width, height),
data: parseData(model, spec.data, function() { callback(viewFactory(model)); })
});
}
if (util.isObject(spec)) {
parse(spec);
} else if (util.isString(spec)) {
var opts = util.extend({url: spec}, model.config().load);
load(opts, function(err, data) {
if (err) {
log.error('LOADING SPECIFICATION FAILED: ' + err.statusText);
} else {
try {
parse(JSON.parse(data));
} catch (e) {
log.error('INVALID SPECIFICATION: Must be a valid JSON object. '+e);
}
}
});
} else {
log.error('INVALID SPECIFICATION: Must be a valid JSON object or URL.');
}
}
module.exports = parseSpec;
},{"../core/Model":80,"../core/View":81,"../parse/background":85,"../parse/data":86,"../parse/marks":92,"../parse/padding":94,"../parse/predicates":95,"../parse/signals":97,"datalib/src/import/load":13,"datalib/src/util":20,"vega-logging":41}],99:[function(require,module,exports){
(function (global){
var d3 = (typeof window !== "undefined" ? window.d3 : typeof global !== "undefined" ? global.d3 : null),
util = require('datalib/src/util'),
changeset = require('vega-dataflow/src/ChangeSet'),
Node = require('vega-dataflow/src/Node'), // jshint ignore:line
Deps = require('vega-dataflow/src/Dependencies'),
parseSignals = require('./signals'),
selector = require('./events'),
expr = require('./expr');
var GATEKEEPER = '_vgGATEKEEPER';
var vgEvent = {
getGroup: function(name) { return name ? this.name[name] : this.group; },
getXY: function(item) {
var p = {x: this.x, y: this.y};
if (typeof item === 'string') {
item = this.name[item];
}
for (; item; item = item.mark && item.mark.group) {
p.x -= item.x || 0;
p.y -= item.y || 0;
}
return p;
},
getX: function(item) { return this.getXY(item).x; },
getY: function(item) { return this.getXY(item).y; }
};
function parseStreams(view) {
var model = view.model(),
spec = model.defs().signals,
registry = {handlers: {}, nodes: {}},
internal = util.duplicate(registry), // Internal event processing
external = util.duplicate(registry); // External event processing
(spec || []).forEach(function(sig) {
var signal = model.signal(sig.name);
if (sig.expr) return; // Cannot have an expr and stream definition.
(sig.streams || []).forEach(function(stream) {
var sel = selector.parse(stream.type),
exp = expr(stream.expr);
mergedStream(signal, sel, exp, stream);
});
});
// We register the event listeners all together so that if multiple
// signals are registered on the same event, they will receive the
// new value on the same pulse.
util.keys(internal.handlers).forEach(function(type) {
view.on(type, function(evt, item) {
evt.preventDefault(); // stop text selection
extendEvent(evt, item);
fire(internal, type, (item && item.datum) || {}, evt);
});
});
// add external event listeners
util.keys(external.handlers).forEach(function(type) {
if (typeof window === 'undefined') return; // No external support
var h = external.handlers[type],
t = type.split(':'), // --> no element pseudo-selectors
elt = (t[0] === 'window') ? [window] :
window.document.querySelectorAll(t[0]);
function handler(evt) {
extendEvent(evt);
fire(external, type, d3.select(this).datum(), evt);
}
for (var i=0; i<elt.length; ++i) {
elt[i].addEventListener(t[1], handler);
}
h.elements = elt;
h.listener = handler;
});
// remove external event listeners
external.detach = function() {
util.keys(external.handlers).forEach(function(type) {
var h = external.handlers[type],
t = type.split(':'),
elt = h.elements || [];
for (var i=0; i<elt.length; ++i) {
elt[i].removeEventListener(t[1], h.listener);
}
});
};
// export detach method
return external.detach;
// -- helper functions -----
function extendEvent(evt, item) {
var mouse = d3.mouse((d3.event=evt, view._el)),
pad = view.padding(),
names = {}, mark, group, i;
if (item) {
mark = item.mark;
group = mark.marktype === 'group' ? item : mark.group;
for (i=item; i!=null; i=i.mark.group) {
if (i.mark.def.name) {
names[i.mark.def.name] = i;
}
}
}
names.root = view.model().scene().items[0];
evt.vg = Object.create(vgEvent);
evt.vg.group = group;
evt.vg.item = item || {};
evt.vg.name = names;
evt.vg.x = mouse[0] - pad.left;
evt.vg.y = mouse[1] - pad.top;
}
function fire(registry, type, datum, evt) {
var handlers = registry.handlers[type],
node = registry.nodes[type],
cs = changeset.create(null, true),
filtered = false,
val, i, n, h;
function invoke(f) {
return !f.fn(datum, evt, model.signalValues(f.globals));
}
for (i=0, n=handlers.length; i<n; ++i) {
h = handlers[i];
filtered = h.filters.some(invoke);
if (filtered) continue;
val = h.exp.fn(datum, evt, model.signalValues(h.exp.globals));
if (h.spec.scale) {
val = parseSignals.scale(model, h.spec, val, datum, evt);
}
if (val !== h.signal.value() || h.signal.verbose()) {
h.signal.value(val);
cs.signals[h.signal.name()] = 1;
}
}
model.propagate(cs, node);
}
function mergedStream(sig, selector, exp, spec) {
selector.forEach(function(s) {
if (s.event) domEvent(sig, s, exp, spec);
else if (s.signal) signal(sig, s, exp, spec);
else if (s.start) orderedStream(sig, s, exp, spec);
else if (s.stream) mergedStream(sig, s.stream, exp, spec);
});
}
function domEvent(sig, selector, exp, spec) {
var evt = selector.event,
name = selector.name,
mark = selector.mark,
target = selector.target,
filters = selector.filters || [],
registry = target ? external : internal,
type = target ? target+':'+evt : evt,
node = registry.nodes[type] || (registry.nodes[type] = new Node(model)),
handlers = registry.handlers[type] || (registry.handlers[type] = []);
if (name) {
filters.push('!!event.vg.name["' + name + '"]'); // Mimic event bubbling
} else if (mark) {
filters.push('event.vg.item.mark && event.vg.item.mark.marktype==='+util.str(mark));
}
handlers.push({
signal: sig,
exp: exp,
spec: spec,
filters: filters.map(function(f) { return expr(f); })
});
node.addListener(sig);
}
function signal(sig, selector, exp, spec) {
var n = new Node(model);
n.evaluate = function(input) {
if (!input.signals[selector.signal]) return model.doNotPropagate;
var val = exp.fn(null, null, model.signalValues(exp.globals));
if (spec.scale) {
val = parseSignals.scale(model, spec, val);
}
if (val !== sig.value() || sig.verbose()) {
sig.value(val);
input.signals[sig.name()] = 1;
input.reflow = true;
}
return input;
};
n.dependency(Deps.SIGNALS, selector.signal);
n.addListener(sig);
model.signal(selector.signal).addListener(n);
}
function orderedStream(sig, selector, exp, spec) {
var name = sig.name(),
trueFn = expr('true'),
falseFn = expr('false'),
middle = selector.middle,
filters = middle.filters || (middle.filters = []),
gatekeeper = model.signal(name + GATEKEEPER, false);
// Register an anonymous signal to act as a gatekeeper. Its value is
// true or false depending on whether the start or end streams occur.
// The middle signal then simply filters for the gatekeeper's value.
mergedStream(gatekeeper, [selector.start], trueFn, {});
mergedStream(gatekeeper, [selector.end], falseFn, {});
filters.push(gatekeeper.name());
mergedStream(sig, [selector.middle], exp, spec);
}
}
module.exports = parseStreams;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNyYy9wYXJzZS9zdHJlYW1zLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSIsImZpbGUiOiJnZW5lcmF0ZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlc0NvbnRlbnQiOlsidmFyIGQzID0gKHR5cGVvZiB3aW5kb3cgIT09IFwidW5kZWZpbmVkXCIgPyB3aW5kb3cuZDMgOiB0eXBlb2YgZ2xvYmFsICE9PSBcInVuZGVmaW5lZFwiID8gZ2xvYmFsLmQzIDogbnVsbCksXG4gICAgdXRpbCA9IHJlcXVpcmUoJ2RhdGFsaWIvc3JjL3V0aWwnKSxcbiAgICBjaGFuZ2VzZXQgPSByZXF1aXJlKCd2ZWdhLWRhdGFmbG93L3NyYy9DaGFuZ2VTZXQnKSxcbiAgICBOb2RlID0gcmVxdWlyZSgndmVnYS1kYXRhZmxvdy9zcmMvTm9kZScpLCAvLyBqc2hpbnQgaWdub3JlOmxpbmVcbiAgICBEZXBzID0gcmVxdWlyZSgndmVnYS1kYXRhZmxvdy9zcmMvRGVwZW5kZW5jaWVzJyksXG4gICAgcGFyc2VTaWduYWxzID0gcmVxdWlyZSgnLi9zaWduYWxzJyksXG4gICAgc2VsZWN0b3IgPSByZXF1aXJlKCcuL2V2ZW50cycpLFxuICAgIGV4cHIgPSByZXF1aXJlKCcuL2V4cHInKTtcblxudmFyIEdBVEVLRUVQRVIgPSAnX3ZnR0FURUtFRVBFUic7XG5cbnZhciB2Z0V2ZW50ID0ge1xuICBnZXRHcm91cDogZnVuY3Rpb24obmFtZSkgeyByZXR1cm4gbmFtZSA/IHRoaXMubmFtZVtuYW1lXSA6IHRoaXMuZ3JvdXA7IH0sXG4gIGdldFhZOiBmdW5jdGlvbihpdGVtKSB7XG4gICAgICB2YXIgcCA9IHt4OiB0aGlzLngsIHk6IHRoaXMueX07XG4gICAgICBpZiAodHlwZW9mIGl0ZW0gPT09ICdzdHJpbmcnKSB7XG4gICAgICAgIGl0ZW0gPSB0aGlzLm5hbWVbaXRlbV07XG4gICAgICB9XG4gICAgICBmb3IgKDsgaXRlbTsgaXRlbSA9IGl0ZW0ubWFyayAmJiBpdGVtLm1hcmsuZ3JvdXApIHtcbiAgICAgICAgcC54IC09IGl0ZW0ueCB8fCAwO1xuICAgICAgICBwLnkgLT0gaXRlbS55IHx8IDA7XG4gICAgICB9XG4gICAgICByZXR1cm4gcDtcbiAgICB9LFxuICBnZXRYOiBmdW5jdGlvbihpdGVtKSB7IHJldHVybiB0aGlzLmdldFhZKGl0ZW0pLng7IH0sXG4gIGdldFk6IGZ1bmN0aW9uKGl0ZW0pIHsgcmV0dXJuIHRoaXMuZ2V0WFkoaXRlbSkueTsgfVxufTtcblxuZnVuY3Rpb24gcGFyc2VTdHJlYW1zKHZpZXcpIHtcbiAgdmFyIG1vZGVsID0gdmlldy5tb2RlbCgpLFxuICAgICAgc3BlYyAgPSBtb2RlbC5kZWZzKCkuc2lnbmFscyxcbiAgICAgIHJlZ2lzdHJ5ID0ge2hhbmRsZXJzOiB7fSwgbm9kZXM6IHt9fSxcbiAgICAgIGludGVybmFsID0gdXRpbC5kdXBsaWNhdGUocmVnaXN0cnkpLCAgLy8gSW50ZXJuYWwgZXZlbnQgcHJvY2Vzc2luZ1xuICAgICAgZXh0ZXJuYWwgPSB1dGlsLmR1cGxpY2F0ZShyZWdpc3RyeSk7ICAvLyBFeHRlcm5hbCBldmVudCBwcm9jZXNzaW5nXG5cbiAgKHNwZWMgfHwgW10pLmZvckVhY2goZnVuY3Rpb24oc2lnKSB7XG4gICAgdmFyIHNpZ25hbCA9IG1vZGVsLnNpZ25hbChzaWcubmFtZSk7XG4gICAgaWYgKHNpZy5leHByKSByZXR1cm47ICAvLyBDYW5ub3QgaGF2ZSBhbiBleHByIGFuZCBzdHJlYW0gZGVmaW5pdGlvbi5cblxuICAgIChzaWcuc3RyZWFtcyB8fCBbXSkuZm9yRWFjaChmdW5jdGlvbihzdHJlYW0pIHtcbiAgICAgIHZhciBzZWwgPSBzZWxlY3Rvci5wYXJzZShzdHJlYW0udHlwZSksXG4gICAgICAgICAgZXhwID0gZXhwcihzdHJlYW0uZXhwcik7XG4gICAgICBtZXJnZWRTdHJlYW0oc2lnbmFsLCBzZWwsIGV4cCwgc3RyZWFtKTtcbiAgICB9KTtcbiAgfSk7XG5cbiAgLy8gV2UgcmVnaXN0ZXIgdGhlIGV2ZW50IGxpc3RlbmVycyBhbGwgdG9nZXRoZXIgc28gdGhhdCBpZiBtdWx0aXBsZVxuICAvLyBzaWduYWxzIGFyZSByZWdpc3RlcmVkIG9uIHRoZSBzYW1lIGV2ZW50LCB0aGV5IHdpbGwgcmVjZWl2ZSB0aGVcbiAgLy8gbmV3IHZhbHVlIG9uIHRoZSBzYW1lIHB1bHNlLiBcbiAgdXRpbC5rZXlzKGludGVybmFsLmhhbmRsZXJzKS5mb3JFYWNoKGZ1bmN0aW9uKHR5cGUpIHtcbiAgICB2aWV3Lm9uKHR5cGUsIGZ1bmN0aW9uKGV2dCwgaXRlbSkge1xuICAgICAgZXZ0LnByZXZlbnREZWZhdWx0KCk7IC8vIHN0b3AgdGV4dCBzZWxlY3Rpb25cbiAgICAgIGV4dGVuZEV2ZW50KGV2dCwgaXRlbSk7XG4gICAgICBmaXJlKGludGVybmFsLCB0eXBlLCAoaXRlbSAmJiBpdGVtLmRhdHVtKSB8fCB7fSwgZXZ0KTtcbiAgICB9KTtcbiAgfSk7XG5cbiAgLy8gYWRkIGV4dGVybmFsIGV2ZW50IGxpc3RlbmVyc1xuICB1dGlsLmtleXMoZXh0ZXJuYWwuaGFuZGxlcnMpLmZvckVhY2goZnVuY3Rpb24odHlwZSkge1xuICAgIGlmICh0eXBlb2Ygd2luZG93ID09PSAndW5kZWZpbmVkJykgcmV0dXJuOyAvLyBObyBleHRlcm5hbCBzdXBwb3J0XG5cbiAgICB2YXIgaCA9IGV4dGVybmFsLmhhbmRsZXJzW3R5cGVdLFxuICAgICAgICB0ID0gdHlwZS5zcGxpdCgnOicpLCAvLyAtLT4gbm8gZWxlbWVudCBwc2V1ZG8tc2VsZWN0b3JzXG4gICAgICAgIGVsdCA9ICh0WzBdID09PSAnd2luZG93JykgPyBbd2luZG93XSA6XG4gICAgICAgICAgICAgIHdpbmRvdy5kb2N1bWVudC5xdWVyeVNlbGVjdG9yQWxsKHRbMF0pO1xuXG4gICAgZnVuY3Rpb24gaGFuZGxlcihldnQpIHtcbiAgICAgIGV4dGVuZEV2ZW50KGV2dCk7XG4gICAgICBmaXJlKGV4dGVybmFsLCB0eXBlLCBkMy5zZWxlY3QodGhpcykuZGF0dW0oKSwgZXZ0KTtcbiAgICB9XG5cbiAgICBmb3IgKHZhciBpPTA7IGk8ZWx0Lmxlbmd0aDsgKytpKSB7XG4gICAgICBlbHRbaV0uYWRkRXZlbnRMaXN0ZW5lcih0WzFdLCBoYW5kbGVyKTtcbiAgICB9XG5cbiAgICBoLmVsZW1lbnRzID0gZWx0O1xuICAgIGgubGlzdGVuZXIgPSBoYW5kbGVyO1xuICB9KTtcblxuICAvLyByZW1vdmUgZXh0ZXJuYWwgZXZlbnQgbGlzdGVuZXJzXG4gIGV4dGVybmFsLmRldGFjaCA9IGZ1bmN0aW9uKCkge1xuICAgIHV0aWwua2V5cyhleHRlcm5hbC5oYW5kbGVycykuZm9yRWFjaChmdW5jdGlvbih0eXBlKSB7XG4gICAgICB2YXIgaCA9IGV4dGVybmFsLmhhbmRsZXJzW3R5cGVdLFxuICAgICAgICAgIHQgPSB0eXBlLnNwbGl0KCc6JyksXG4gICAgICAgICAgZWx0ID0gaC5lbGVtZW50cyB8fCBbXTtcblxuICAgICAgZm9yICh2YXIgaT0wOyBpPGVsdC5sZW5ndGg7ICsraSkge1xuICAgICAgICBlbHRbaV0ucmVtb3ZlRXZlbnRMaXN0ZW5lcih0WzFdLCBoLmxpc3RlbmVyKTtcbiAgICAgIH1cbiAgICB9KTtcbiAgfTtcblxuICAvLyBleHBvcnQgZGV0YWNoIG1ldGhvZFxuICByZXR1cm4gZXh0ZXJuYWwuZGV0YWNoO1xuXG4gIC8vIC0tIGhlbHBlciBmdW5jdGlvbnMgLS0tLS1cblxuICBmdW5jdGlvbiBleHRlbmRFdmVudChldnQsIGl0ZW0pIHtcbiAgICB2YXIgbW91c2UgPSBkMy5tb3VzZSgoZDMuZXZlbnQ9ZXZ0LCB2aWV3Ll9lbCkpLFxuICAgICAgICBwYWQgPSB2aWV3LnBhZGRpbmcoKSxcbiAgICAgICAgbmFtZXMgPSB7fSwgbWFyaywgZ3JvdXAsIGk7XG5cbiAgICBpZiAoaXRlbSkge1xuICAgICAgbWFyayA9IGl0ZW0ubWFyaztcbiAgICAgIGdyb3VwID0gbWFyay5tYXJrdHlwZSA9PT0gJ2dyb3VwJyA/IGl0ZW0gOiBtYXJrLmdyb3VwO1xuICAgICAgZm9yIChpPWl0ZW07IGkhPW51bGw7IGk9aS5tYXJrLmdyb3VwKSB7XG4gICAgICAgIGlmIChpLm1hcmsuZGVmLm5hbWUpIHtcbiAgICAgICAgICBuYW1lc1tpLm1hcmsuZGVmLm5hbWVdID0gaTtcbiAgICAgICAgfVxuICAgICAgfVxuICAgIH1cbiAgICBuYW1lcy5yb290ID0gdmlldy5tb2RlbCgpLnNjZW5lKCkuaXRlbXNbMF07XG5cbiAgICBldnQudmcgPSBPYmplY3QuY3JlYXRlKHZnRXZlbnQpO1xuICAgIGV2dC52Zy5ncm91cCA9IGdyb3VwO1xuICAgIGV2dC52Zy5pdGVtID0gaXRlbSB8fCB7fTtcbiAgICBldnQudmcubmFtZSA9IG5hbWVzO1xuICAgIGV2dC52Zy54ID0gbW91c2VbMF0gLSBwYWQubGVmdDtcbiAgICBldnQudmcueSA9IG1vdXNlWzFdIC0gcGFkLnRvcDtcbiAgfVxuXG4gIGZ1bmN0aW9uIGZpcmUocmVnaXN0cnksIHR5cGUsIGRhdHVtLCBldnQpIHtcbiAgICB2YXIgaGFuZGxlcnMgPSByZWdpc3RyeS5oYW5kbGVyc1t0eXBlXSxcbiAgICAgICAgbm9kZSA9IHJlZ2lzdHJ5Lm5vZGVzW3R5cGVdLFxuICAgICAgICBjcyA9IGNoYW5nZXNldC5jcmVhdGUobnVsbCwgdHJ1ZSksXG4gICAgICAgIGZpbHRlcmVkID0gZmFsc2UsXG4gICAgICAgIHZhbCwgaSwgbiwgaDtcblxuICAgIGZ1bmN0aW9uIGludm9rZShmKSB7XG4gICAgICByZXR1cm4gIWYuZm4oZGF0dW0sIGV2dCwgbW9kZWwuc2lnbmFsVmFsdWVzKGYuZ2xvYmFscykpO1xuICAgIH1cblxuICAgIGZvciAoaT0wLCBuPWhhbmRsZXJzLmxlbmd0aDsgaTxuOyArK2kpIHtcbiAgICAgIGggPSBoYW5kbGVyc1tpXTtcbiAgICAgIGZpbHRlcmVkID0gaC5maWx0ZXJzLnNvbWUoaW52b2tlKTtcbiAgICAgIGlmIChmaWx0ZXJlZCkgY29udGludWU7XG4gICAgICBcbiAgICAgIHZhbCA9IGguZXhwLmZuKGRhdHVtLCBldnQsIG1vZGVsLnNpZ25hbFZhbHVlcyhoLmV4cC5nbG9iYWxzKSk7XG4gICAgICBpZiAoaC5zcGVjLnNjYWxlKSB7XG4gICAgICAgIHZhbCA9IHBhcnNlU2lnbmFscy5zY2FsZShtb2RlbCwgaC5zcGVjLCB2YWwsIGRhdHVtLCBldnQpO1xuICAgICAgfVxuXG4gICAgICBpZiAodmFsICE9PSBoLnNpZ25hbC52YWx1ZSgpIHx8IGguc2lnbmFsLnZlcmJvc2UoKSkge1xuICAgICAgICBoLnNpZ25hbC52YWx1ZSh2YWwpO1xuICAgICAgICBjcy5zaWduYWxzW2guc2lnbmFsLm5hbWUoKV0gPSAxO1xuICAgICAgfVxuICAgIH1cblxuICAgIG1vZGVsLnByb3BhZ2F0ZShjcywgbm9kZSk7XG4gIH1cblxuICBmdW5jdGlvbiBtZXJnZWRTdHJlYW0oc2lnLCBzZWxlY3RvciwgZXhwLCBzcGVjKSB7XG4gICAgc2VsZWN0b3IuZm9yRWFjaChmdW5jdGlvbihzKSB7XG4gICAgICBpZiAocy5ldmVudCkgICAgICAgZG9tRXZlbnQoc2lnLCBzLCBleHAsIHNwZWMpO1xuICAgICAgZWxzZSBpZiAocy5zaWduYWwpIHNpZ25hbChzaWcsIHMsIGV4cCwgc3BlYyk7XG4gICAgICBlbHNlIGlmIChzLnN0YXJ0KSAgb3JkZXJlZFN0cmVhbShzaWcsIHMsIGV4cCwgc3BlYyk7XG4gICAgICBlbHNlIGlmIChzLnN0cmVhbSkgbWVyZ2VkU3RyZWFtKHNpZywgcy5zdHJlYW0sIGV4cCwgc3BlYyk7XG4gICAgfSk7XG4gIH1cblxuICBmdW5jdGlvbiBkb21FdmVudChzaWcsIHNlbGVjdG9yLCBleHAsIHNwZWMpIHtcbiAgICB2YXIgZXZ0ID0gc2VsZWN0b3IuZXZlbnQsXG4gICAgICAgIG5hbWUgPSBzZWxlY3Rvci5uYW1lLFxuICAgICAgICBtYXJrID0gc2VsZWN0b3IubWFyayxcbiAgICAgICAgdGFyZ2V0ICAgPSBzZWxlY3Rvci50YXJnZXQsXG4gICAgICAgIGZpbHRlcnMgID0gc2VsZWN0b3IuZmlsdGVycyB8fCBbXSxcbiAgICAgICAgcmVnaXN0cnkgPSB0YXJnZXQgPyBleHRlcm5hbCA6IGludGVybmFsLFxuICAgICAgICB0eXBlID0gdGFyZ2V0ID8gdGFyZ2V0Kyc6JytldnQgOiBldnQsXG4gICAgICAgIG5vZGUgPSByZWdpc3RyeS5ub2Rlc1t0eXBlXSB8fCAocmVnaXN0cnkubm9kZXNbdHlwZV0gPSBuZXcgTm9kZShtb2RlbCkpLFxuICAgICAgICBoYW5kbGVycyA9IHJlZ2lzdHJ5LmhhbmRsZXJzW3R5cGVdIHx8IChyZWdpc3RyeS5oYW5kbGVyc1t0eXBlXSA9IFtdKTtcblxuICAgIGlmIChuYW1lKSB7XG4gICAgICBmaWx0ZXJzLnB1c2goJyEhZXZlbnQudmcubmFtZVtcIicgKyBuYW1lICsgJ1wiXScpOyAvLyBNaW1pYyBldmVudCBidWJibGluZ1xuICAgIH0gZWxzZSBpZiAobWFyaykge1xuICAgICAgZmlsdGVycy5wdXNoKCdldmVudC52Zy5pdGVtLm1hcmsgJiYgZXZlbnQudmcuaXRlbS5tYXJrLm1hcmt0eXBlPT09Jyt1dGlsLnN0cihtYXJrKSk7XG4gICAgfVxuXG4gICAgaGFuZGxlcnMucHVzaCh7XG4gICAgICBzaWduYWw6IHNpZyxcbiAgICAgIGV4cDogZXhwLFxuICAgICAgc3BlYzogc3BlYyxcbiAgICAgIGZpbHRlcnM6IGZpbHRlcnMubWFwKGZ1bmN0aW9uKGYpIHsgcmV0dXJuIGV4cHIoZik7IH0pXG4gICAgfSk7XG5cbiAgICBub2RlLmFkZExpc3RlbmVyKHNpZyk7XG4gIH1cblxuICBmdW5jdGlvbiBzaWduYWwoc2lnLCBzZWxlY3RvciwgZXhwLCBzcGVjKSB7XG4gICAgdmFyIG4gPSBuZXcgTm9kZShtb2RlbCk7XG4gICAgbi5ldmFsdWF0ZSA9IGZ1bmN0aW9uKGlucHV0KSB7XG4gICAgICBpZiAoIWlucHV0LnNpZ25hbHNbc2VsZWN0b3Iuc2lnbmFsXSkgcmV0dXJuIG1vZGVsLmRvTm90UHJvcGFnYXRlO1xuICAgICAgdmFyIHZhbCA9IGV4cC5mbihudWxsLCBudWxsLCBtb2RlbC5zaWduYWxWYWx1ZXMoZXhwLmdsb2JhbHMpKTtcbiAgICAgIGlmIChzcGVjLnNjYWxlKSB7XG4gICAgICAgIHZhbCA9IHBhcnNlU2lnbmFscy5zY2FsZShtb2RlbCwgc3BlYywgdmFsKTtcbiAgICAgIH1cblxuICAgICAgaWYgKHZhbCAhPT0gc2lnLnZhbHVlKCkgfHwgc2lnLnZlcmJvc2UoKSkge1xuICAgICAgICBzaWcudmFsdWUodmFsKTtcbiAgICAgICAgaW5wdXQuc2lnbmFsc1tzaWcubmFtZSgpXSA9IDE7XG4gICAgICAgIGlucHV0LnJlZmxvdyA9IHRydWU7ICAgICAgICBcbiAgICAgIH1cblxuICAgICAgcmV0dXJuIGlucHV0OyAgXG4gICAgfTtcbiAgICBuLmRlcGVuZGVuY3koRGVwcy5TSUdOQUxTLCBzZWxlY3Rvci5zaWduYWwpO1xuICAgIG4uYWRkTGlzdGVuZXIoc2lnKTtcbiAgICBtb2RlbC5zaWduYWwoc2VsZWN0b3Iuc2lnbmFsKS5hZGRMaXN0ZW5lcihuKTtcbiAgfVxuXG4gIGZ1bmN0aW9uIG9yZGVyZWRTdHJlYW0oc2lnLCBzZWxlY3RvciwgZXhwLCBzcGVjKSB7XG4gICAgdmFyIG5hbWUgPSBzaWcubmFtZSgpLCBcbiAgICAgICAgdHJ1ZUZuICA9IGV4cHIoJ3RydWUnKSwgXG4gICAgICAgIGZhbHNlRm4gPSBleHByKCdmYWxzZScpLFxuICAgICAgICBtaWRkbGUgID0gc2VsZWN0b3IubWlkZGxlLFxuICAgICAgICBmaWx0ZXJzID0gbWlkZGxlLmZpbHRlcnMgfHwgKG1pZGRsZS5maWx0ZXJzID0gW10pLFxuICAgICAgICBnYXRla2VlcGVyID0gbW9kZWwuc2lnbmFsKG5hbWUgKyBHQVRFS0VFUEVSLCBmYWxzZSk7XG5cbiAgICAvLyBSZWdpc3RlciBhbiBhbm9ueW1vdXMgc2lnbmFsIHRvIGFjdCBhcyBhIGdhdGVrZWVwZXIuIEl0cyB2YWx1ZSBpc1xuICAgIC8vIHRydWUgb3IgZmFsc2UgZGVwZW5kaW5nIG9uIHdoZXRoZXIgdGhlIHN0YXJ0IG9yIGVuZCBzdHJlYW1zIG9jY3VyLiBcbiAgICAvLyBUaGUgbWlkZGxlIHNpZ25hbCB0aGVuIHNpbXBseSBmaWx0ZXJzIGZvciB0aGUgZ2F0ZWtlZXBlcidzIHZhbHVlLiBcbiAgICBtZXJnZWRTdHJlYW0oZ2F0ZWtlZXBlciwgW3NlbGVjdG9yLnN0YXJ0XSwgdHJ1ZUZuLCB7fSk7XG4gICAgbWVyZ2VkU3RyZWFtKGdhdGVrZWVwZXIsIFtzZWxlY3Rvci5lbmRdLCBmYWxzZUZuLCB7fSk7XG5cbiAgICBmaWx0ZXJzLnB1c2goZ2F0ZWtlZXBlci5uYW1lKCkpO1xuICAgIG1lcmdlZFN0cmVhbShzaWcsIFtzZWxlY3Rvci5taWRkbGVdLCBleHAsIHNwZWMpO1xuICB9XG59XG5cbm1vZHVsZS5leHBvcnRzID0gcGFyc2VTdHJlYW1zOyJdfQ==
},{"./events":87,"./expr":88,"./signals":97,"datalib/src/util":20,"vega-dataflow/src/ChangeSet":26,"vega-dataflow/src/Dependencies":29,"vega-dataflow/src/Node":31}],100:[function(require,module,exports){
var util = require('datalib/src/util'),
transforms = require('../transforms/index');
function parseTransforms(model, def) {
var tx = new transforms[def.type](model);
// We want to rename output fields before setting any other properties,
// as subsequent properties may require output to be set (e.g. group by).
if(def.output) tx.output(def.output);
util.keys(def).forEach(function(k) {
if(k === 'type' || k === 'output') return;
tx.param(k, def[k]);
});
return tx;
}
module.exports = parseTransforms;
},{"../transforms/index":130,"datalib/src/util":20}],101:[function(require,module,exports){
var util = require('datalib/src/util'),
bound = require('vega-scenegraph/src/util/bound'),
Node = require('vega-dataflow/src/Node'), // jshint ignore:line
ChangeSet = require('vega-dataflow/src/ChangeSet'),
log = require('vega-logging'),
Encoder = require('./Encoder');
function Bounder(graph, mark) {
this._mark = mark;
return Node.prototype.init.call(this, graph)
.router(true)
.reflows(true);
}
var proto = (Bounder.prototype = new Node());
proto.evaluate = function(input) {
log.debug(input, ["bounds", this._mark.marktype]);
var type = this._mark.marktype,
isGrp = type === "group",
items = this._mark.items,
hasLegends = util.array(this._mark.def.legends).length > 0,
i, ilen, j, jlen, group, legend;
if (input.add.length || input.rem.length || !items.length ||
input.mod.length === items.length ||
type === "area" || type === "line") {
bound.mark(this._mark, null, isGrp && !hasLegends);
} else {
input.mod.forEach(function(item) { bound.item(item); });
}
if (isGrp && hasLegends) {
for (i=0, ilen=items.length; i<ilen; ++i) {
group = items[i];
group._legendPositions = null;
for (j=0, jlen=group.legendItems.length; j<jlen; ++j) {
legend = group.legendItems[j];
Encoder.update(this._graph, input.trans, "vg_legendPosition", legend.items, input.dirty);
bound.mark(legend, null, false);
}
}
bound.mark(this._mark, null, true);
}
return ChangeSet.create(input, true);
};
module.exports = Bounder;
},{"./Encoder":103,"datalib/src/util":20,"vega-dataflow/src/ChangeSet":26,"vega-dataflow/src/Node":31,"vega-logging":41,"vega-scenegraph/src/util/bound":74}],102:[function(require,module,exports){
var util = require('datalib/src/util'),
Item = require('vega-scenegraph/src/util/Item'),
Tuple = require('vega-dataflow/src/Tuple'),
ChangeSet = require('vega-dataflow/src/ChangeSet'),
Node = require('vega-dataflow/src/Node'), // jshint ignore:line
Deps = require('vega-dataflow/src/Dependencies'),
Sentinel = require('vega-dataflow/src/Sentinel'),
log = require('vega-logging'),
Encoder = require('./Encoder'),
Bounder = require('./Bounder'),
parseData = require('../parse/data');
function Builder() {
return arguments.length ? this.init.apply(this, arguments) : this;
}
var Status = Builder.STATUS = {
ENTER: "enter",
UPDATE: "update",
EXIT: "exit"
};
var proto = (Builder.prototype = new Node());
proto.init = function(graph, def, mark, parent, parent_id, inheritFrom) {
Node.prototype.init.call(this, graph)
.router(true)
.collector(true);
this._def = def;
this._mark = mark;
this._from = (def.from ? def.from.data : null) || inheritFrom;
this._ds = util.isString(this._from) ? graph.data(this._from) : null;
this._map = {};
this._revises = false; // Should scenegraph items track _prev?
mark.def = def;
mark.marktype = def.type;
mark.interactive = (def.interactive !== false);
mark.items = [];
if (util.isValid(def.name)) mark.name = def.name;
this._parent = parent;
this._parent_id = parent_id;
if (def.from && (def.from.mark || def.from.transform || def.from.modify)) {
inlineDs.call(this);
}
// Non-group mark builders are super nodes. Encoder and Bounder remain
// separate operators but are embedded and called by Builder.evaluate.
this._isSuper = (this._def.type !== "group");
this._encoder = new Encoder(this._graph, this._mark);
this._bounder = new Bounder(this._graph, this._mark);
this._output = null; // Output changeset for reactive geom as Bounder reflows
if (this._ds) { this._encoder.dependency(Deps.DATA, this._from); }
// Since Builders are super nodes, copy over encoder dependencies
// (bounder has no registered dependencies).
this.dependency(Deps.DATA, this._encoder.dependency(Deps.DATA));
this.dependency(Deps.SCALES, this._encoder.dependency(Deps.SCALES));
this.dependency(Deps.SIGNALS, this._encoder.dependency(Deps.SIGNALS));
return this;
};
proto.revises = function(p) {
if (!arguments.length) return this._revises;
// If we've not needed prev in the past, but a new inline ds needs it now
// ensure existing items have prev set.
if (!this._revises && p) {
this._items.forEach(function(d) { if (d._prev === undefined) d._prev = Sentinel; });
}
this._revises = this._revises || p;
return this;
};
// Reactive geometry and mark-level transformations are handled here
// because they need their group's data-joined context.
function inlineDs() {
var from = this._def.from,
geom = from.mark,
src, name, spec, sibling, output, input;
if (geom) {
name = ["vg", this._parent_id, geom].join("_");
spec = {
name: name,
transform: from.transform,
modify: from.modify
};
} else {
src = this._graph.data(this._from);
name = ["vg", this._from, this._def.type, src.listeners(true).length].join("_");
spec = {
name: name,
source: this._from,
transform: from.transform,
modify: from.modify
};
}
this._from = name;
this._ds = parseData.datasource(this._graph, spec);
var revises = this._ds.revises(), node;
if (geom) {
sibling = this.sibling(geom).revises(revises);
// Bounder reflows, so we need an intermediary node to propagate
// the output constructed by the Builder.
node = new Node(this._graph).addListener(this._ds.listener());
node.evaluate = function() { return sibling._output; };
if (sibling._isSuper) {
sibling.addListener(node);
} else {
sibling._bounder.addListener(node);
}
} else {
// At this point, we have a new datasource but it is empty as
// the propagation cycle has already crossed the datasources.
// So, we repulse just this datasource. This should be safe
// as the ds isn't connected to the scenegraph yet.
output = this._ds.source().revises(revises).last();
input = ChangeSet.create(output);
input.add = output.add;
input.mod = output.mod;
input.rem = output.rem;
input.stamp = null;
this._graph.propagate(input, this._ds.listener(), output.stamp);
}
}
proto.pipeline = function() {
return [this];
};
proto.connect = function() {
var builder = this;
this._graph.connect(this.pipeline());
this._encoder._scales.forEach(function(s) {
if (!(s = builder._parent.scale(s))) return;
s.addListener(builder);
});
if (this._parent) {
if (this._isSuper) this.addListener(this._parent._collector);
else this._bounder.addListener(this._parent._collector);
}
return this;
};
proto.disconnect = function() {
var builder = this;
if (!this._listeners.length) return this;
Node.prototype.disconnect.call(this);
this._graph.disconnect(this.pipeline());
this._encoder._scales.forEach(function(s) {
if (!(s = builder._parent.scale(s))) return;
s.removeListener(builder);
});
return this;
};
proto.sibling = function(name) {
return this._parent.child(name, this._parent_id);
};
proto.evaluate = function(input) {
log.debug(input, ["building", (this._from || this._def.from), this._def.type]);
var output, fullUpdate, fcs, data, name;
if (this._ds) {
output = ChangeSet.create(input);
// We need to determine if any encoder dependencies have been updated.
// However, the encoder's data source will likely be updated, and shouldn't
// trigger all items to mod.
data = output.data[(name=this._ds.name())];
delete output.data[name];
fullUpdate = this._encoder.reevaluate(output);
output.data[name] = data;
// If a scale or signal in the update propset has been updated,
// send forward all items for reencoding if we do an early return.
if (fullUpdate) output.mod = this._mark.items.slice();
fcs = this._ds.last();
if (!fcs) throw Error('Builder evaluated before backing DataSource');
if (fcs.stamp > this._stamp) {
output = joinDatasource.call(this, fcs, this._ds.values(), fullUpdate);
}
} else {
data = util.isFunction(this._def.from) ? this._def.from() : [Sentinel];
output = joinValues.call(this, input, data);
}
// Stash output before Bounder for downstream reactive geometry.
this._output = output = this._graph.evaluate(output, this._encoder);
// Supernodes calculate bounds too, but only on items marked dirty.
if (this._isSuper) {
output.mod = output.mod.filter(function(x) { return x._dirty; });
output = this._graph.evaluate(output, this._bounder);
}
return output;
};
function newItem() {
var prev = this._revises ? null : undefined,
item = Tuple.ingest(new Item(this._mark), prev);
// For the root node's item
if (this._def.width) Tuple.set(item, "width", this._def.width);
if (this._def.height) Tuple.set(item, "height", this._def.height);
return item;
}
function join(data, keyf, next, output, prev, mod) {
var i, key, len, item, datum, enter;
for (i=0, len=data.length; i<len; ++i) {
datum = data[i];
item = keyf ? this._map[key = keyf(datum)] : prev[i];
enter = item ? false : (item = newItem.call(this), true);
item.status = enter ? Status.ENTER : Status.UPDATE;
item.datum = datum;
Tuple.set(item, "key", key);
this._map[key] = item;
next.push(item);
if (enter) {
output.add.push(item);
} else if (!mod || (mod && mod[datum._id])) {
output.mod.push(item);
}
}
}
function joinDatasource(input, data, fullUpdate) {
var output = ChangeSet.create(input),
keyf = keyFunction(this._def.key || "_id"),
mod = input.mod,
rem = input.rem,
next = [],
i, key, len, item;
// Build rems first, and put them at the head of the next items
// Then build the rest of the data values (which won't contain rem).
// This will preserve the sort order without needing anything extra.
for (i=0, len=rem.length; i<len; ++i) {
item = this._map[key = keyf(rem[i])];
item.status = Status.EXIT;
item._dirty = true;
input.dirty.push(item);
next.push(item);
output.rem.push(item);
this._map[key] = null;
}
join.call(this, data, keyf, next, output, null, Tuple.idMap(fullUpdate ? data : mod));
return (this._mark.items = next, output);
}
function joinValues(input, data) {
var output = ChangeSet.create(input),
keyf = keyFunction(this._def.key),
prev = this._mark.items || [],
next = [],
i, len, item;
for (i=0, len=prev.length; i<len; ++i) {
item = prev[i];
item.status = Status.EXIT;
if (keyf) this._map[item.key] = item;
}
join.call(this, data, keyf, next, output, prev, Tuple.idMap(data));
for (i=0, len=prev.length; i<len; ++i) {
item = prev[i];
if (item.status === Status.EXIT) {
Tuple.set(item, "key", keyf ? item.key : this._items.length);
item._dirty = true;
input.dirty.push(item);
next.splice(0, 0, item); // Keep item around for "exit" transition.
output.rem.push(item);
}
}
return (this._mark.items = next, output);
}
function keyFunction(key) {
if (key == null) return null;
var f = util.array(key).map(util.accessor);
return function(d) {
for (var s="", i=0, n=f.length; i<n; ++i) {
if (i>0) s += "|";
s += String(f[i](d));
}
return s;
};
}
module.exports = Builder;
},{"../parse/data":86,"./Bounder":101,"./Encoder":103,"datalib/src/util":20,"vega-dataflow/src/ChangeSet":26,"vega-dataflow/src/Dependencies":29,"vega-dataflow/src/Node":31,"vega-dataflow/src/Sentinel":32,"vega-dataflow/src/Tuple":34,"vega-logging":41,"vega-scenegraph/src/util/Item":73}],103:[function(require,module,exports){
var util = require('datalib/src/util'),
bound = require('vega-scenegraph/src/util/bound'),
Node = require('vega-dataflow/src/Node'), // jshint ignore:line
Deps = require('vega-dataflow/src/Dependencies'),
log = require('vega-logging');
var EMPTY = {};
function Encoder(graph, mark) {
var props = mark.def.properties || {},
enter = props.enter,
update = props.update,
exit = props.exit;
Node.prototype.init.call(this, graph);
this._mark = mark;
var s = this._scales = [];
// Only scales used in the "update" property set are set as
// encoder depedencies to have targeted reevaluations. However,
// we still want scales in "enter" and "exit" to be evaluated
// before the encoder.
if (enter) s.push.apply(s, enter.scales);
if (update) {
this.dependency(Deps.DATA, update.data);
this.dependency(Deps.SIGNALS, update.signals);
this.dependency(Deps.FIELDS, update.fields);
this.dependency(Deps.SCALES, update.scales);
s.push.apply(s, update.scales);
}
if (exit) s.push.apply(s, exit.scales);
return this;
}
var proto = (Encoder.prototype = new Node());
proto.evaluate = function(input) {
log.debug(input, ["encoding", this._mark.def.type]);
var graph = this._graph,
props = this._mark.def.properties || {},
enter = props.enter,
update = props.update,
exit = props.exit,
dirty = input.dirty,
preds = this._graph.predicates(),
sg = graph.signalValues(), // For expediency, get all signal values
db = graph.dataValues(),
req = input.request,
i, len, item, prop;
if (req) {
if ((prop = props[req])) {
for (i=0, len=input.mod.length; i<len; ++i) {
item = input.mod[i];
encode.call(this, prop, item, input.trans, db, sg, preds, dirty);
}
}
return input; // exit early if given request
}
// Items marked for removal are at the head of items. Process them first.
for (i=0, len=input.rem.length; i<len; ++i) {
item = input.rem[i];
if (exit) encode.call(this, exit, item, input.trans, db, sg, preds, dirty);
if (input.trans && !exit) input.trans.interpolate(item, EMPTY);
else if (!input.trans) item.remove();
}
for (i=0, len=input.add.length; i<len; ++i) {
item = input.add[i];
if (enter) encode.call(this, enter, item, input.trans, db, sg, preds, dirty);
if (update) encode.call(this, update, item, input.trans, db, sg, preds, dirty);
item.status = require('./Builder').STATUS.UPDATE;
}
if (update) {
for (i=0, len=input.mod.length; i<len; ++i) {
item = input.mod[i];
encode.call(this, update, item, input.trans, db, sg, preds, dirty);
}
}
return input;
};
function encode(prop, item, trans, db, sg, preds, dirty) {
var enc = prop.encode,
wasDirty = item._dirty,
isDirty = enc.call(enc, item, item.mark.group||item, trans, db, sg, preds);
item._dirty = isDirty || wasDirty;
if (isDirty && !wasDirty) dirty.push(item);
}
// If a specified property set called, or update property set
// uses nested fieldrefs, reevaluate all items.
proto.reevaluate = function(pulse) {
var def = this._mark.def,
props = def.properties || {},
update = props.update;
return util.isFunction(def.from) || def.orient || pulse.request ||
Node.prototype.reevaluate.call(this, pulse) ||
(update ? update.reflow : false);
};
// Short-circuit encoder if user specifies items
Encoder.update = function(graph, trans, request, items, dirty) {
items = util.array(items);
var preds = graph.predicates(),
db = graph.dataValues(),
sg = graph.signalValues(),
i, len, item, props, prop;
for (i=0, len=items.length; i<len; ++i) {
item = items[i];
props = item.mark.def.properties;
prop = props && props[request];
if (prop) {
encode.call(null, prop, item, trans, db, sg, preds, dirty);
bound.item(item);
}
}
};
module.exports = Encoder;
},{"./Builder":102,"datalib/src/util":20,"vega-dataflow/src/Dependencies":29,"vega-dataflow/src/Node":31,"vega-logging":41,"vega-scenegraph/src/util/bound":74}],104:[function(require,module,exports){
var util = require('datalib/src/util'),
Node = require('vega-dataflow/src/Node'), // jshint ignore:line
Collector = require('vega-dataflow/src/Collector'),
Deps = require('vega-dataflow/src/Dependencies'),
log = require('vega-logging'),
Builder = require('./Builder'),
Scale = require('./Scale'),
parseAxes = require('../parse/axes'),
parseLegends = require('../parse/legends');
function GroupBuilder() {
this._children = {};
this._scaler = null;
this._recursor = null;
this._scales = {};
this.scale = scale.bind(this);
return arguments.length ? this.init.apply(this, arguments) : this;
}
var Types = GroupBuilder.TYPES = {
GROUP: "group",
MARK: "mark",
AXIS: "axis",
LEGEND: "legend"
};
var proto = (GroupBuilder.prototype = new Builder());
proto.init = function(graph, def) {
var builder = this, name;
this._scaler = new Node(graph);
(def.scales||[]).forEach(function(s) {
s = builder.scale((name=s.name), new Scale(graph, s, builder));
builder.scale(name+":prev", s);
builder._scaler.addListener(s); // Scales should be computed after group is encoded
});
this._recursor = new Node(graph);
this._recursor.evaluate = recurse.bind(this);
var scales = (def.axes||[]).reduce(function(acc, x) {
return (acc[x.scale] = 1, acc);
}, {});
scales = (def.legends||[]).reduce(function(acc, x) {
return (acc[x.size || x.shape || x.fill || x.stroke], acc);
}, scales);
this._recursor.dependency(Deps.SCALES, util.keys(scales));
// We only need a collector for up-propagation of bounds calculation,
// so only GroupBuilders, and not regular Builders, have collectors.
this._collector = new Collector(graph);
return Builder.prototype.init.apply(this, arguments);
};
proto.evaluate = function() {
var output = Builder.prototype.evaluate.apply(this, arguments),
builder = this;
output.add.forEach(function(group) { buildGroup.call(builder, output, group); });
return output;
};
proto.pipeline = function() {
return [this, this._scaler, this._recursor, this._collector, this._bounder];
};
proto.disconnect = function() {
var builder = this;
util.keys(builder._children).forEach(function(group_id) {
builder._children[group_id].forEach(function(c) {
builder._recursor.removeListener(c.builder);
c.builder.disconnect();
});
});
builder._children = {};
return Builder.prototype.disconnect.call(this);
};
proto.child = function(name, group_id) {
var children = this._children[group_id],
i = 0, len = children.length,
child;
for (; i<len; ++i) {
child = children[i];
if (child.type == Types.MARK && child.builder._def.name == name) break;
}
return child.builder;
};
function recurse(input) {
var builder = this,
hasMarks = util.array(this._def.marks).length > 0,
hasAxes = util.array(this._def.axes).length > 0,
hasLegends = util.array(this._def.legends).length > 0,
i, j, c, len, group, pipeline, def, inline = false;
for (i=0, len=input.add.length; i<len; ++i) {
group = input.add[i];
if (hasMarks) buildMarks.call(this, input, group);
if (hasAxes) buildAxes.call(this, input, group);
if (hasLegends) buildLegends.call(this, input, group);
}
// Wire up new children builders in reverse to minimize graph rewrites.
for (i=input.add.length-1; i>=0; --i) {
group = input.add[i];
for (j=this._children[group._id].length-1; j>=0; --j) {
c = this._children[group._id][j];
c.builder.connect();
pipeline = c.builder.pipeline();
def = c.builder._def;
// This new child needs to be built during this propagation cycle.
// We could add its builder as a listener off the _recursor node,
// but try to inline it if we can to minimize graph dispatches.
inline = (def.type !== Types.GROUP);
inline = inline && (this._graph.data(c.from) !== undefined);
inline = inline && (pipeline[pipeline.length-1].listeners().length === 1); // Reactive geom source
inline = inline && (def.from && !def.from.mark); // Reactive geom target
c.inline = inline;
if (inline) this._graph.evaluate(input, c.builder);
else this._recursor.addListener(c.builder);
}
}
function removeTemp(c) {
if (c.type == Types.MARK && !c.inline &&
builder._graph.data(c.from) !== undefined) {
builder._recursor.removeListener(c.builder);
}
}
function updateAxis(a) {
var scale = a.scale();
if (!input.scales[scale.scaleName]) return;
a.reset().def();
}
function updateLegend(l) {
var scale = l.size() || l.shape() || l.fill() || l.stroke();
if (!input.scales[scale.scaleName]) return;
l.reset().def();
}
for (i=0, len=input.mod.length; i<len; ++i) {
group = input.mod[i];
// Remove temporary connection for marks that draw from a source
if (hasMarks) builder._children[group._id].forEach(removeTemp);
// Update axis data defs
if (hasAxes) group.axes.forEach(updateAxis);
// Update legend data defs
if (hasLegends) group.legends.forEach(updateLegend);
}
function disconnectChildren(c) {
builder._recursor.removeListener(c.builder);
c.builder.disconnect();
}
for (i=0, len=input.rem.length; i<len; ++i) {
group = input.rem[i];
// For deleted groups, disconnect their children
builder._children[group._id].forEach(disconnectChildren);
delete builder._children[group._id];
}
return input;
}
function scale(name, s) {
var group = this;
if (arguments.length === 2) return (group._scales[name] = s, s);
while (s == null) {
s = group._scales[name];
group = group.mark ? group.mark.group : group._parent;
if (!group) break;
}
return s;
}
function buildGroup(input, group) {
log.debug(input, ["building group", group._id]);
group._scales = group._scales || {};
group.scale = scale.bind(group);
group.items = group.items || [];
this._children[group._id] = this._children[group._id] || [];
group.axes = group.axes || [];
group.axisItems = group.axisItems || [];
group.legends = group.legends || [];
group.legendItems = group.legendItems || [];
}
function buildMarks(input, group) {
log.debug(input, ["building children marks #"+group._id]);
var marks = this._def.marks,
mark, from, inherit, i, len, b;
for (i=0, len=marks.length; i<len; ++i) {
mark = marks[i];
from = mark.from || {};
inherit = group.datum._facetID;
group.items[i] = {group: group};
b = (mark.type === Types.GROUP) ? new GroupBuilder() : new Builder();
b.init(this._graph, mark, group.items[i], this, group._id, inherit);
this._children[group._id].push({
builder: b,
from: from.data || (from.mark ? ("vg_" + group._id + "_" + from.mark) : inherit),
type: Types.MARK
});
}
}
function buildAxes(input, group) {
var axes = group.axes,
axisItems = group.axisItems,
builder = this;
parseAxes(this._graph, this._def.axes, axes, group);
axes.forEach(function(a, i) {
var scale = builder._def.axes[i].scale,
def = a.def(),
b = null;
axisItems[i] = {group: group, axisDef: def, layer: def.layer};
b = (def.type === Types.GROUP) ? new GroupBuilder() : new Builder();
b.init(builder._graph, def, axisItems[i], builder)
.dependency(Deps.SCALES, scale);
builder._children[group._id].push({ builder: b, type: Types.AXIS, scale: scale });
});
}
function buildLegends(input, group) {
var legends = group.legends,
legendItems = group.legendItems,
builder = this;
parseLegends(this._graph, this._def.legends, legends, group);
legends.forEach(function(l, i) {
var scale = l.size() || l.shape() || l.fill() || l.stroke(),
def = l.def(),
b = null;
legendItems[i] = {group: group, legendDef: def};
b = (def.type === Types.GROUP) ? new GroupBuilder() : new Builder();
b.init(builder._graph, def, legendItems[i], builder)
.dependency(Deps.SCALES, scale);
builder._children[group._id].push({ builder: b, type: Types.LEGEND, scale: scale });
});
}
module.exports = GroupBuilder;
},{"../parse/axes":84,"../parse/legends":90,"./Builder":102,"./Scale":105,"datalib/src/util":20,"vega-dataflow/src/Collector":27,"vega-dataflow/src/Dependencies":29,"vega-dataflow/src/Node":31,"vega-logging":41}],105:[function(require,module,exports){
(function (global){
var d3 = (typeof window !== "undefined" ? window.d3 : typeof global !== "undefined" ? global.d3 : null),
util = require('datalib/src/util'),
changeset = require('vega-dataflow/src/ChangeSet'),
Node = require('vega-dataflow/src/Node'), // jshint ignore:line
Deps = require('vega-dataflow/src/Dependencies'),
log = require('vega-logging'),
Aggregate = require('../transforms/Aggregate');
var Properties = {
width: 1,
height: 1
};
var Types = {
LINEAR: 'linear',
ORDINAL: 'ordinal',
LOG: 'log',
POWER: 'pow',
SQRT: 'sqrt',
TIME: 'time',
TIME_UTC: 'utc',
QUANTILE: 'quantile',
QUANTIZE: 'quantize',
THRESHOLD: 'threshold'
};
var DataRef = {
DOMAIN: 'domain',
RANGE: 'range',
COUNT: 'count',
GROUPBY: 'groupby',
MIN: 'min',
MAX: 'max',
VALUE: 'value',
ASC: 'asc',
DESC: 'desc'
};
function Scale(graph, def, parent) {
this._def = def;
this._parent = parent;
this._updated = false;
return Node.prototype.init.call(this, graph).reflows(true);
}
var proto = (Scale.prototype = new Node());
proto.evaluate = function(input) {
var self = this,
fn = function(group) { scale.call(self, group); };
this._updated = false;
input.add.forEach(fn);
input.mod.forEach(fn);
// Scales are at the end of an encoding pipeline, so they should forward a
// reflow pulse. Thus, if multiple scales update in the parent group, we don't
// reevaluate child marks multiple times.
if (this._updated) input.scales[this._def.name] = 1;
return changeset.create(input, true);
};
// All of a scale's dependencies are registered during propagation as we parse
// dataRefs. So a scale must be responsible for connecting itself to dependents.
proto.dependency = function(type, deps) {
if (arguments.length == 2) {
var method = (type === Deps.DATA ? 'data' : 'signal');
deps = util.array(deps);
for (var i=0, len=deps.length; i<len; ++i) {
this._graph[method](deps[i]).addListener(this._parent);
}
}
return Node.prototype.dependency.call(this, type, deps);
};
function scale(group) {
var name = this._def.name,
prev = name + ':prev',
s = instance.call(this, group.scale(name)),
m = s.type===Types.ORDINAL ? ordinal : quantitative,
rng = range.call(this, group);
m.call(this, s, rng, group);
group.scale(name, s);
group.scale(prev, group.scale(prev) || s);
return s;
}
function instance(scale) {
var config = this._graph.config(),
type = this._def.type || Types.LINEAR;
if (!scale || type !== scale.type) {
var ctor = config.scale[type] || d3.scale[type];
if (!ctor) util.error('Unrecognized scale type: ' + type);
(scale = ctor()).type = scale.type || type;
scale.scaleName = this._def.name;
scale._prev = {};
}
return scale;
}
function ordinal(scale, rng, group) {
var def = this._def,
prev = scale._prev,
dataDrivenRange = false,
pad = signal.call(this, def.padding) || 0,
outer = def.outerPadding == null ? pad : signal.call(this, def.outerPadding),
points = def.points && signal.call(this, def.points),
round = signal.call(this, def.round) || def.round == null,
domain, str;
// range pre-processing for data-driven ranges
if (util.isObject(def.range) && !util.isArray(def.range)) {
dataDrivenRange = true;
rng = dataRef.call(this, DataRef.RANGE, def.range, scale, group);
}
// domain
domain = dataRef.call(this, DataRef.DOMAIN, def.domain, scale, group);
if (domain && !util.equal(prev.domain, domain)) {
scale.domain(domain);
prev.domain = domain;
this._updated = true;
}
// range
if (util.equal(prev.range, rng)) return;
// width-defined range
if (def.bandWidth) {
var bw = signal.call(this, def.bandWidth),
len = domain.length,
space = def.points ? (pad*bw) : (pad*bw*(len-1) + 2*outer),
start;
if (rng[0] > rng[1]) {
start = rng[1] || 0;
rng = [start + (bw * len + space), start];
} else {
start = rng[0] || 0;
rng = [start, start + (bw * len + space)];
}
}
str = typeof rng[0] === 'string';
if (str || rng.length > 2 || rng.length===1 || dataDrivenRange) {
scale.range(rng); // color or shape values
} else if (points && round) {
scale.rangeRoundPoints(rng, pad);
} else if (points) {
scale.rangePoints(rng, pad);
} else if (round) {
scale.rangeRoundBands(rng, pad, outer);
} else {
scale.rangeBands(rng, pad, outer);
}
if (!scale.invert) {
scale.invert = function(x, y) {
if (arguments.length === 1) {
return scale.domain()[d3.bisect(scale.range(), x) - 1];
} else if (arguments.length === 2) { // Invert extents
if (!util.isNumber(x) || !util.isNumber(y)) {
throw new Error('Extents to ordinal invert are not numbers ('+x+', '+y+').');
}
var points = [],
rng = scale.range(),
i = 0, len = rng.length, r;
for(; i<len; ++i) {
r = rng[i];
if (x < y ? x <= r && r <= y : y <= r && r <= x) {
points.push(r);
}
}
return points.map(function(p) { return scale.invert(p); });
}
};
}
prev.range = rng;
this._updated = true;
}
function quantitative(scale, rng, group) {
var def = this._def,
prev = scale._prev,
round = signal.call(this, def.round),
exponent = signal.call(this, def.exponent),
clamp = signal.call(this, def.clamp),
nice = signal.call(this, def.nice),
domain, interval;
// domain
domain = (def.type === Types.QUANTILE) ?
dataRef.call(this, DataRef.DOMAIN, def.domain, scale, group) :
domainMinMax.call(this, scale, group);
if (domain && !util.equal(prev.domain, domain)) {
scale.domain(domain);
prev.domain = domain;
this._updated = true;
}
// range
// vertical scales should flip by default, so use XOR here
if (signal.call(this, def.range) === 'height') rng = rng.reverse();
if (util.equal(prev.range, rng)) return;
scale[round && scale.rangeRound ? 'rangeRound' : 'range'](rng);
prev.range = rng;
this._updated = true;
// TODO: Support signals for these properties. Until then, only eval
// them once.
if (this._stamp > 0) return;
if (exponent && def.type===Types.POWER) scale.exponent(exponent);
if (clamp) scale.clamp(true);
if (nice) {
if (def.type === Types.TIME) {
interval = d3.time[nice];
if (!interval) log.error('Unrecognized interval: ' + interval);
scale.nice(interval);
} else {
scale.nice();
}
}
}
function isUniques(scale) {
return scale.type === Types.ORDINAL || scale.type === Types.QUANTILE;
}
function getRefs(def) {
return def.fields || util.array(def);
}
function getFields(ref, group) {
return util.array(ref.field).map(function(f) {
return f.parent ?
util.accessor(f.parent)(group.datum) :
f; // String or {'signal'}
});
}
// Scale datarefs can be computed over multiple schema types.
// This function determines the type of aggregator created, and
// what data is sent to it: values, tuples, or multi-tuples that must
// be standardized into a consistent schema.
function aggrType(def, scale) {
var refs = getRefs(def);
// If we're operating over only a single domain, send full tuples
// through for efficiency (fewer accessor creations/calls)
if (refs.length == 1 && util.array(refs[0].field).length == 1) {
return Aggregate.TYPES.TUPLE;
}
// With quantitative scales, we only care about min/max.
if (!isUniques(scale)) return Aggregate.TYPES.VALUE;
// If we don't sort, then we can send values directly to aggrs as well
if (!def.sort) return Aggregate.TYPES.VALUE;
return Aggregate.TYPES.MULTI;
}
function getCache(which, def, scale, group) {
var refs = getRefs(def),
atype = aggrType(def, scale),
uniques = isUniques(scale),
sort = def.sort,
ck = '_'+which,
fields = getFields(refs[0], group),
ref;
if (scale[ck]) return scale[ck];
var cache = scale[ck] = new Aggregate(this._graph).type(atype),
groupby, summarize;
if (uniques) {
if (atype === Aggregate.TYPES.VALUE) {
groupby = [{ name: DataRef.GROUPBY, get: util.identity }];
summarize = {'*': DataRef.COUNT};
} else if (atype === Aggregate.TYPES.TUPLE) {
groupby = [{ name: DataRef.GROUPBY, get: util.$(fields[0]) }];
summarize = sort ? [{
field: DataRef.VALUE,
get: util.$(ref.sort || sort.field),
ops: [sort.op]
}] : {'*': DataRef.COUNT};
} else { // atype === Aggregate.TYPES.MULTI
groupby = DataRef.GROUPBY;
summarize = [{ field: DataRef.VALUE, ops: [sort.op] }];
}
} else {
groupby = [];
summarize = [{
field: DataRef.VALUE,
get: (atype == Aggregate.TYPES.TUPLE) ? util.$(fields[0]) : util.identity,
ops: [DataRef.MIN, DataRef.MAX],
as: [DataRef.MIN, DataRef.MAX]
}];
}
cache.param('groupby', groupby)
.param('summarize', summarize);
return cache;
}
function dataRef(which, def, scale, group) {
if (def == null) { return []; }
if (util.isArray(def)) return def.map(signal.bind(this));
var self = this, graph = this._graph,
refs = getRefs(def),
atype = aggrType(def, scale),
cache = getCache.apply(this, arguments),
sort = def.sort,
uniques = isUniques(scale),
i, rlen, j, flen, ref, fields, field, data, from;
function addDep(s) {
self.dependency(Deps.SIGNALS, s);
}
for (i=0, rlen=refs.length; i<rlen; ++i) {
ref = refs[i];
from = ref.data || group.datum._facetID;
data = graph.data(from)
.revises(true)
.last();
if (data.stamp <= this._stamp) continue;
fields = getFields(ref, group);
for (j=0, flen=fields.length; j<flen; ++j) {
field = fields[j];
if (atype === Aggregate.TYPES.VALUE) {
cache.accessors(null, field);
} else if (atype === Aggregate.TYPES.MULTI) {
cache.accessors(field, ref.sort || sort.field);
} // Else (Tuple-case) is handled by the aggregator accessors by default
cache.evaluate(data);
}
this.dependency(Deps.DATA, from);
cache.dependency(Deps.SIGNALS).forEach(addDep);
}
data = cache.aggr().result();
if (uniques) {
if (sort) {
sort = sort.order.signal ? graph.signalRef(sort.order.signal) : sort.order;
sort = (sort == DataRef.DESC ? '-' : '+') + DataRef.VALUE;
sort = util.comparator(sort);
data = data.sort(sort);
// } else { // 'First seen' order
// sort = util.comparator('tpl._id');
}
return data.map(function(d) { return d[DataRef.GROUPBY]; });
} else {
data = data[0];
return !util.isValid(data) ? [] : [data[DataRef.MIN], data[DataRef.MAX]];
}
}
function signal(v) {
if (!v || !v.signal) return v;
var s = v.signal, ref;
this.dependency(Deps.SIGNALS, (ref = util.field(s))[0]);
return this._graph.signalRef(ref);
}
function domainMinMax(scale, group) {
var def = this._def,
domain = [null, null], z;
if (def.domain !== undefined) {
domain = (!util.isObject(def.domain)) ? domain :
dataRef.call(this, DataRef.DOMAIN, def.domain, scale, group);
}
z = domain.length - 1;
if (def.domainMin !== undefined) {
if (util.isObject(def.domainMin)) {
if (def.domainMin.signal) {
domain[0] = signal.call(this, def.domainMin);
} else {
domain[0] = dataRef.call(this, DataRef.DOMAIN+DataRef.MIN, def.domainMin, scale, group)[0];
}
} else {
domain[0] = def.domainMin;
}
}
if (def.domainMax !== undefined) {
if (util.isObject(def.domainMax)) {
if (def.domainMax.signal) {
domain[z] = signal.call(this, def.domainMax);
} else {
domain[z] = dataRef.call(this, DataRef.DOMAIN+DataRef.MAX, def.domainMax, scale, group)[1];
}
} else {
domain[z] = def.domainMax;
}
}
if (def.type !== Types.LOG && def.type !== Types.TIME && (def.zero || def.zero===undefined)) {
domain[0] = Math.min(0, domain[0]);
domain[z] = Math.max(0, domain[z]);
}
return domain;
}
function range(group) {
var def = this._def,
config = this._graph.config(),
rangeVal = signal.call(this, def.range),
rng = [null, null];
if (rangeVal !== undefined) {
if (typeof rangeVal === 'string') {
if (Properties[rangeVal]) {
rng = [0, group[rangeVal]];
} else if (config.range[rangeVal]) {
rng = config.range[rangeVal];
} else {
log.error('Unrecogized range: ' + rangeVal);
return rng;
}
} else if (util.isArray(rangeVal)) {
rng = util.duplicate(rangeVal).map(signal.bind(this));
} else if (util.isObject(rangeVal)) {
return null; // early exit
} else {
rng = [0, rangeVal];
}
}
if (def.rangeMin !== undefined) {
rng[0] = def.rangeMin.signal ?
signal.call(this, def.rangeMin) :
def.rangeMin;
}
if (def.rangeMax !== undefined) {
rng[rng.length-1] = def.rangeMax.signal ?
signal.call(this, def.rangeMax) :
def.rangeMax;
}
if (def.reverse !== undefined) {
var rev = signal.call(this, def.reverse);
if (util.isObject(rev)) {
rev = util.accessor(rev.field)(group.datum);
}
if (rev) rng = rng.reverse();
}
return rng;
}
module.exports = Scale;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNyYy9zY2VuZS9TY2FsZS5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EiLCJmaWxlIjoiZ2VuZXJhdGVkLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXNDb250ZW50IjpbInZhciBkMyA9ICh0eXBlb2Ygd2luZG93ICE9PSBcInVuZGVmaW5lZFwiID8gd2luZG93LmQzIDogdHlwZW9mIGdsb2JhbCAhPT0gXCJ1bmRlZmluZWRcIiA/IGdsb2JhbC5kMyA6IG51bGwpLFxuICAgIHV0aWwgPSByZXF1aXJlKCdkYXRhbGliL3NyYy91dGlsJyksXG4gICAgY2hhbmdlc2V0ID0gcmVxdWlyZSgndmVnYS1kYXRhZmxvdy9zcmMvQ2hhbmdlU2V0JyksXG4gICAgTm9kZSA9IHJlcXVpcmUoJ3ZlZ2EtZGF0YWZsb3cvc3JjL05vZGUnKSwgLy8ganNoaW50IGlnbm9yZTpsaW5lXG4gICAgRGVwcyA9IHJlcXVpcmUoJ3ZlZ2EtZGF0YWZsb3cvc3JjL0RlcGVuZGVuY2llcycpLFxuICAgIGxvZyA9IHJlcXVpcmUoJ3ZlZ2EtbG9nZ2luZycpLFxuICAgIEFnZ3JlZ2F0ZSA9IHJlcXVpcmUoJy4uL3RyYW5zZm9ybXMvQWdncmVnYXRlJyk7XG5cbnZhciBQcm9wZXJ0aWVzID0ge1xuICB3aWR0aDogMSxcbiAgaGVpZ2h0OiAxXG59O1xuXG52YXIgVHlwZXMgPSB7XG4gIExJTkVBUjogJ2xpbmVhcicsXG4gIE9SRElOQUw6ICdvcmRpbmFsJyxcbiAgTE9HOiAnbG9nJyxcbiAgUE9XRVI6ICdwb3cnLFxuICBTUVJUOiAnc3FydCcsXG4gIFRJTUU6ICd0aW1lJyxcbiAgVElNRV9VVEM6ICd1dGMnLFxuICBRVUFOVElMRTogJ3F1YW50aWxlJyxcbiAgUVVBTlRJWkU6ICdxdWFudGl6ZScsXG4gIFRIUkVTSE9MRDogJ3RocmVzaG9sZCdcbn07XG5cbnZhciBEYXRhUmVmID0ge1xuICBET01BSU46ICdkb21haW4nLFxuICBSQU5HRTogJ3JhbmdlJyxcblxuICBDT1VOVDogJ2NvdW50JyxcbiAgR1JPVVBCWTogJ2dyb3VwYnknLFxuICBNSU46ICdtaW4nLFxuICBNQVg6ICdtYXgnLFxuICBWQUxVRTogJ3ZhbHVlJyxcblxuICBBU0M6ICdhc2MnLFxuICBERVNDOiAnZGVzYydcbn07XG5cbmZ1bmN0aW9uIFNjYWxlKGdyYXBoLCBkZWYsIHBhcmVudCkge1xuICB0aGlzLl9kZWYgICAgID0gZGVmO1xuICB0aGlzLl9wYXJlbnQgID0gcGFyZW50O1xuICB0aGlzLl91cGRhdGVkID0gZmFsc2U7XG4gIHJldHVybiBOb2RlLnByb3RvdHlwZS5pbml0LmNhbGwodGhpcywgZ3JhcGgpLnJlZmxvd3ModHJ1ZSk7XG59XG5cbnZhciBwcm90byA9IChTY2FsZS5wcm90b3R5cGUgPSBuZXcgTm9kZSgpKTtcblxucHJvdG8uZXZhbHVhdGUgPSBmdW5jdGlvbihpbnB1dCkge1xuICB2YXIgc2VsZiA9IHRoaXMsXG4gICAgICBmbiA9IGZ1bmN0aW9uKGdyb3VwKSB7IHNjYWxlLmNhbGwoc2VsZiwgZ3JvdXApOyB9O1xuXG4gIHRoaXMuX3VwZGF0ZWQgPSBmYWxzZTtcbiAgaW5wdXQuYWRkLmZvckVhY2goZm4pO1xuICBpbnB1dC5tb2QuZm9yRWFjaChmbik7XG5cbiAgLy8gU2NhbGVzIGFyZSBhdCB0aGUgZW5kIG9mIGFuIGVuY29kaW5nIHBpcGVsaW5lLCBzbyB0aGV5IHNob3VsZCBmb3J3YXJkIGFcbiAgLy8gcmVmbG93IHB1bHNlLiBUaHVzLCBpZiBtdWx0aXBsZSBzY2FsZXMgdXBkYXRlIGluIHRoZSBwYXJlbnQgZ3JvdXAsIHdlIGRvbid0XG4gIC8vIHJlZXZhbHVhdGUgY2hpbGQgbWFya3MgbXVsdGlwbGUgdGltZXMuIFxuICBpZiAodGhpcy5fdXBkYXRlZCkgaW5wdXQuc2NhbGVzW3RoaXMuX2RlZi5uYW1lXSA9IDE7XG4gIHJldHVybiBjaGFuZ2VzZXQuY3JlYXRlKGlucHV0LCB0cnVlKTtcbn07XG5cbi8vIEFsbCBvZiBhIHNjYWxlJ3MgZGVwZW5kZW5jaWVzIGFyZSByZWdpc3RlcmVkIGR1cmluZyBwcm9wYWdhdGlvbiBhcyB3ZSBwYXJzZVxuLy8gZGF0YVJlZnMuIFNvIGEgc2NhbGUgbXVzdCBiZSByZXNwb25zaWJsZSBmb3IgY29ubmVjdGluZyBpdHNlbGYgdG8gZGVwZW5kZW50cy5cbnByb3RvLmRlcGVuZGVuY3kgPSBmdW5jdGlvbih0eXBlLCBkZXBzKSB7XG4gIGlmIChhcmd1bWVudHMubGVuZ3RoID09IDIpIHtcbiAgICB2YXIgbWV0aG9kID0gKHR5cGUgPT09IERlcHMuREFUQSA/ICdkYXRhJyA6ICdzaWduYWwnKTtcbiAgICBkZXBzID0gdXRpbC5hcnJheShkZXBzKTtcbiAgICBmb3IgKHZhciBpPTAsIGxlbj1kZXBzLmxlbmd0aDsgaTxsZW47ICsraSkge1xuICAgICAgdGhpcy5fZ3JhcGhbbWV0aG9kXShkZXBzW2ldKS5hZGRMaXN0ZW5lcih0aGlzLl9wYXJlbnQpO1xuICAgIH1cbiAgfVxuXG4gIHJldHVybiBOb2RlLnByb3RvdHlwZS5kZXBlbmRlbmN5LmNhbGwodGhpcywgdHlwZSwgZGVwcyk7XG59O1xuXG5mdW5jdGlvbiBzY2FsZShncm91cCkge1xuICB2YXIgbmFtZSA9IHRoaXMuX2RlZi5uYW1lLFxuICAgICAgcHJldiA9IG5hbWUgKyAnOnByZXYnLFxuICAgICAgcyA9IGluc3RhbmNlLmNhbGwodGhpcywgZ3JvdXAuc2NhbGUobmFtZSkpLFxuICAgICAgbSA9IHMudHlwZT09PVR5cGVzLk9SRElOQUwgPyBvcmRpbmFsIDogcXVhbnRpdGF0aXZlLFxuICAgICAgcm5nID0gcmFuZ2UuY2FsbCh0aGlzLCBncm91cCk7XG5cbiAgbS5jYWxsKHRoaXMsIHMsIHJuZywgZ3JvdXApO1xuXG4gIGdyb3VwLnNjYWxlKG5hbWUsIHMpO1xuICBncm91cC5zY2FsZShwcmV2LCBncm91cC5zY2FsZShwcmV2KSB8fCBzKTtcblxuICByZXR1cm4gcztcbn1cblxuZnVuY3Rpb24gaW5zdGFuY2Uoc2NhbGUpIHtcbiAgdmFyIGNvbmZpZyA9IHRoaXMuX2dyYXBoLmNvbmZpZygpLFxuICAgICAgdHlwZSA9IHRoaXMuX2RlZi50eXBlIHx8IFR5cGVzLkxJTkVBUjtcbiAgaWYgKCFzY2FsZSB8fCB0eXBlICE9PSBzY2FsZS50eXBlKSB7XG4gICAgdmFyIGN0b3IgPSBjb25maWcuc2NhbGVbdHlwZV0gfHwgZDMuc2NhbGVbdHlwZV07XG4gICAgaWYgKCFjdG9yKSB1dGlsLmVycm9yKCdVbnJlY29nbml6ZWQgc2NhbGUgdHlwZTogJyArIHR5cGUpO1xuICAgIChzY2FsZSA9IGN0b3IoKSkudHlwZSA9IHNjYWxlLnR5cGUgfHwgdHlwZTtcbiAgICBzY2FsZS5zY2FsZU5hbWUgPSB0aGlzLl9kZWYubmFtZTtcbiAgICBzY2FsZS5fcHJldiA9IHt9O1xuICB9XG4gIHJldHVybiBzY2FsZTtcbn1cblxuZnVuY3Rpb24gb3JkaW5hbChzY2FsZSwgcm5nLCBncm91cCkge1xuICB2YXIgZGVmID0gdGhpcy5fZGVmLFxuICAgICAgcHJldiA9IHNjYWxlLl9wcmV2LFxuICAgICAgZGF0YURyaXZlblJhbmdlID0gZmFsc2UsXG4gICAgICBwYWQgPSBzaWduYWwuY2FsbCh0aGlzLCBkZWYucGFkZGluZykgfHwgMCxcbiAgICAgIG91dGVyID0gZGVmLm91dGVyUGFkZGluZyA9PSBudWxsID8gcGFkIDogc2lnbmFsLmNhbGwodGhpcywgZGVmLm91dGVyUGFkZGluZyksXG4gICAgICBwb2ludHMgPSBkZWYucG9pbnRzICYmIHNpZ25hbC5jYWxsKHRoaXMsIGRlZi5wb2ludHMpLFxuICAgICAgcm91bmQgPSBzaWduYWwuY2FsbCh0aGlzLCBkZWYucm91bmQpIHx8IGRlZi5yb3VuZCA9PSBudWxsLFxuICAgICAgZG9tYWluLCBzdHI7XG4gIFxuICAvLyByYW5nZSBwcmUtcHJvY2Vzc2luZyBmb3IgZGF0YS1kcml2ZW4gcmFuZ2VzXG4gIGlmICh1dGlsLmlzT2JqZWN0KGRlZi5yYW5nZSkgJiYgIXV0aWwuaXNBcnJheShkZWYucmFuZ2UpKSB7XG4gICAgZGF0YURyaXZlblJhbmdlID0gdHJ1ZTtcbiAgICBybmcgPSBkYXRhUmVmLmNhbGwodGhpcywgRGF0YVJlZi5SQU5HRSwgZGVmLnJhbmdlLCBzY2FsZSwgZ3JvdXApO1xuICB9XG4gIFxuICAvLyBkb21haW5cbiAgZG9tYWluID0gZGF0YVJlZi5jYWxsKHRoaXMsIERhdGFSZWYuRE9NQUlOLCBkZWYuZG9tYWluLCBzY2FsZSwgZ3JvdXApO1xuICBpZiAoZG9tYWluICYmICF1dGlsLmVxdWFsKHByZXYuZG9tYWluLCBkb21haW4pKSB7XG4gICAgc2NhbGUuZG9tYWluKGRvbWFpbik7XG4gICAgcHJldi5kb21haW4gPSBkb21haW47XG4gICAgdGhpcy5fdXBkYXRlZCA9IHRydWU7XG4gIH0gXG5cbiAgLy8gcmFuZ2VcbiAgaWYgKHV0aWwuZXF1YWwocHJldi5yYW5nZSwgcm5nKSkgcmV0dXJuO1xuXG4gIC8vIHdpZHRoLWRlZmluZWQgcmFuZ2VcbiAgaWYgKGRlZi5iYW5kV2lkdGgpIHtcbiAgICB2YXIgYncgPSBzaWduYWwuY2FsbCh0aGlzLCBkZWYuYmFuZFdpZHRoKSxcbiAgICAgICAgbGVuID0gZG9tYWluLmxlbmd0aCxcbiAgICAgICAgc3BhY2UgPSBkZWYucG9pbnRzID8gKHBhZCpidykgOiAocGFkKmJ3KihsZW4tMSkgKyAyKm91dGVyKSxcbiAgICAgICAgc3RhcnQ7XG4gICAgaWYgKHJuZ1swXSA+IHJuZ1sxXSkge1xuICAgICAgc3RhcnQgPSBybmdbMV0gfHwgMDtcbiAgICAgIHJuZyA9IFtzdGFydCArIChidyAqIGxlbiArIHNwYWNlKSwgc3RhcnRdO1xuICAgIH0gZWxzZSB7XG4gICAgICBzdGFydCA9IHJuZ1swXSB8fCAwO1xuICAgICAgcm5nID0gW3N0YXJ0LCBzdGFydCArIChidyAqIGxlbiArIHNwYWNlKV07XG4gICAgfVxuICB9XG5cbiAgc3RyID0gdHlwZW9mIHJuZ1swXSA9PT0gJ3N0cmluZyc7XG4gIGlmIChzdHIgfHwgcm5nLmxlbmd0aCA+IDIgfHwgcm5nLmxlbmd0aD09PTEgfHwgZGF0YURyaXZlblJhbmdlKSB7XG4gICAgc2NhbGUucmFuZ2Uocm5nKTsgLy8gY29sb3Igb3Igc2hhcGUgdmFsdWVzXG4gIH0gZWxzZSBpZiAocG9pbnRzICYmIHJvdW5kKSB7XG4gICAgc2NhbGUucmFuZ2VSb3VuZFBvaW50cyhybmcsIHBhZCk7XG4gIH0gZWxzZSBpZiAocG9pbnRzKSB7XG4gICAgc2NhbGUucmFuZ2VQb2ludHMocm5nLCBwYWQpO1xuICB9IGVsc2UgaWYgKHJvdW5kKSB7XG4gICAgc2NhbGUucmFuZ2VSb3VuZEJhbmRzKHJuZywgcGFkLCBvdXRlcik7XG4gIH0gZWxzZSB7XG4gICAgc2NhbGUucmFuZ2VCYW5kcyhybmcsIHBhZCwgb3V0ZXIpO1xuICB9XG5cbiAgaWYgKCFzY2FsZS5pbnZlcnQpIHtcbiAgICBzY2FsZS5pbnZlcnQgPSBmdW5jdGlvbih4LCB5KSB7XG4gICAgICBpZiAoYXJndW1lbnRzLmxlbmd0aCA9PT0gMSkge1xuICAgICAgICByZXR1cm4gc2NhbGUuZG9tYWluKClbZDMuYmlzZWN0KHNjYWxlLnJhbmdlKCksIHgpIC0gMV07XG4gICAgICB9IGVsc2UgaWYgKGFyZ3VtZW50cy5sZW5ndGggPT09IDIpIHsgIC8vIEludmVydCBleHRlbnRzXG4gICAgICAgIGlmICghdXRpbC5pc051bWJlcih4KSB8fCAhdXRpbC5pc051bWJlcih5KSkge1xuICAgICAgICAgIHRocm93IG5ldyBFcnJvcignRXh0ZW50cyB0byBvcmRpbmFsIGludmVydCBhcmUgbm90IG51bWJlcnMgKCcreCsnLCAnK3krJykuJyk7XG4gICAgICAgIH1cblxuICAgICAgICB2YXIgcG9pbnRzID0gW10sXG4gICAgICAgICAgICBybmcgPSBzY2FsZS5yYW5nZSgpLFxuICAgICAgICAgICAgaSA9IDAsIGxlbiA9IHJuZy5sZW5ndGgsIHI7XG5cbiAgICAgICAgZm9yKDsgaTxsZW47ICsraSkge1xuICAgICAgICAgIHIgPSBybmdbaV07XG4gICAgICAgICAgaWYgKHggPCB5ID8geCA8PSByICYmIHIgPD0geSA6IHkgPD0gciAmJiByIDw9IHgpIHtcbiAgICAgICAgICAgIHBvaW50cy5wdXNoKHIpO1xuICAgICAgICAgIH1cbiAgICAgICAgfVxuXG4gICAgICAgIHJldHVybiBwb2ludHMubWFwKGZ1bmN0aW9uKHApIHsgcmV0dXJuIHNjYWxlLmludmVydChwKTsgfSk7XG4gICAgICB9XG4gICAgfTtcbiAgfVxuXG4gIHByZXYucmFuZ2UgPSBybmc7XG4gIHRoaXMuX3VwZGF0ZWQgPSB0cnVlO1xufVxuXG5mdW5jdGlvbiBxdWFudGl0YXRpdmUoc2NhbGUsIHJuZywgZ3JvdXApIHtcbiAgdmFyIGRlZiA9IHRoaXMuX2RlZixcbiAgICAgIHByZXYgPSBzY2FsZS5fcHJldixcbiAgICAgIHJvdW5kID0gc2lnbmFsLmNhbGwodGhpcywgZGVmLnJvdW5kKSxcbiAgICAgIGV4cG9uZW50ID0gc2lnbmFsLmNhbGwodGhpcywgZGVmLmV4cG9uZW50KSxcbiAgICAgIGNsYW1wID0gc2lnbmFsLmNhbGwodGhpcywgZGVmLmNsYW1wKSxcbiAgICAgIG5pY2UgPSBzaWduYWwuY2FsbCh0aGlzLCBkZWYubmljZSksXG4gICAgICBkb21haW4sIGludGVydmFsO1xuXG4gIC8vIGRvbWFpblxuICBkb21haW4gPSAoZGVmLnR5cGUgPT09IFR5cGVzLlFVQU5USUxFKSA/XG4gICAgZGF0YVJlZi5jYWxsKHRoaXMsIERhdGFSZWYuRE9NQUlOLCBkZWYuZG9tYWluLCBzY2FsZSwgZ3JvdXApIDpcbiAgICBkb21haW5NaW5NYXguY2FsbCh0aGlzLCBzY2FsZSwgZ3JvdXApO1xuICBpZiAoZG9tYWluICYmICF1dGlsLmVxdWFsKHByZXYuZG9tYWluLCBkb21haW4pKSB7XG4gICAgc2NhbGUuZG9tYWluKGRvbWFpbik7XG4gICAgcHJldi5kb21haW4gPSBkb21haW47XG4gICAgdGhpcy5fdXBkYXRlZCA9IHRydWU7XG4gIH0gXG5cbiAgLy8gcmFuZ2VcbiAgLy8gdmVydGljYWwgc2NhbGVzIHNob3VsZCBmbGlwIGJ5IGRlZmF1bHQsIHNvIHVzZSBYT1IgaGVyZVxuICBpZiAoc2lnbmFsLmNhbGwodGhpcywgZGVmLnJhbmdlKSA9PT0gJ2hlaWdodCcpIHJuZyA9IHJuZy5yZXZlcnNlKCk7XG4gIGlmICh1dGlsLmVxdWFsKHByZXYucmFuZ2UsIHJuZykpIHJldHVybjtcbiAgc2NhbGVbcm91bmQgJiYgc2NhbGUucmFuZ2VSb3VuZCA/ICdyYW5nZVJvdW5kJyA6ICdyYW5nZSddKHJuZyk7XG4gIHByZXYucmFuZ2UgPSBybmc7XG4gIHRoaXMuX3VwZGF0ZWQgPSB0cnVlO1xuXG4gIC8vIFRPRE86IFN1cHBvcnQgc2lnbmFscyBmb3IgdGhlc2UgcHJvcGVydGllcy4gVW50aWwgdGhlbiwgb25seSBldmFsXG4gIC8vIHRoZW0gb25jZS5cbiAgaWYgKHRoaXMuX3N0YW1wID4gMCkgcmV0dXJuO1xuICBpZiAoZXhwb25lbnQgJiYgZGVmLnR5cGU9PT1UeXBlcy5QT1dFUikgc2NhbGUuZXhwb25lbnQoZXhwb25lbnQpO1xuICBpZiAoY2xhbXApIHNjYWxlLmNsYW1wKHRydWUpO1xuICBpZiAobmljZSkge1xuICAgIGlmIChkZWYudHlwZSA9PT0gVHlwZXMuVElNRSkge1xuICAgICAgaW50ZXJ2YWwgPSBkMy50aW1lW25pY2VdO1xuICAgICAgaWYgKCFpbnRlcnZhbCkgbG9nLmVycm9yKCdVbnJlY29nbml6ZWQgaW50ZXJ2YWw6ICcgKyBpbnRlcnZhbCk7XG4gICAgICBzY2FsZS5uaWNlKGludGVydmFsKTtcbiAgICB9IGVsc2Uge1xuICAgICAgc2NhbGUubmljZSgpO1xuICAgIH1cbiAgfVxufVxuXG5mdW5jdGlvbiBpc1VuaXF1ZXMoc2NhbGUpIHsgXG4gIHJldHVybiBzY2FsZS50eXBlID09PSBUeXBlcy5PUkRJTkFMIHx8IHNjYWxlLnR5cGUgPT09IFR5cGVzLlFVQU5USUxFOyBcbn1cblxuZnVuY3Rpb24gZ2V0UmVmcyhkZWYpIHsgXG4gIHJldHVybiBkZWYuZmllbGRzIHx8IHV0aWwuYXJyYXkoZGVmKTtcbn1cblxuZnVuY3Rpb24gZ2V0RmllbGRzKHJlZiwgZ3JvdXApIHtcbiAgcmV0dXJuIHV0aWwuYXJyYXkocmVmLmZpZWxkKS5tYXAoZnVuY3Rpb24oZikge1xuICAgIHJldHVybiBmLnBhcmVudCA/XG4gICAgICB1dGlsLmFjY2Vzc29yKGYucGFyZW50KShncm91cC5kYXR1bSkgOlxuICAgICAgZjsgLy8gU3RyaW5nIG9yIHsnc2lnbmFsJ31cbiAgfSk7XG59XG5cbi8vIFNjYWxlIGRhdGFyZWZzIGNhbiBiZSBjb21wdXRlZCBvdmVyIG11bHRpcGxlIHNjaGVtYSB0eXBlcy4gXG4vLyBUaGlzIGZ1bmN0aW9uIGRldGVybWluZXMgdGhlIHR5cGUgb2YgYWdncmVnYXRvciBjcmVhdGVkLCBhbmRcbi8vIHdoYXQgZGF0YSBpcyBzZW50IHRvIGl0OiB2YWx1ZXMsIHR1cGxlcywgb3IgbXVsdGktdHVwbGVzIHRoYXQgbXVzdFxuLy8gYmUgc3RhbmRhcmRpemVkIGludG8gYSBjb25zaXN0ZW50IHNjaGVtYS4gXG5mdW5jdGlvbiBhZ2dyVHlwZShkZWYsIHNjYWxlKSB7XG4gIHZhciByZWZzID0gZ2V0UmVmcyhkZWYpO1xuXG4gIC8vIElmIHdlJ3JlIG9wZXJhdGluZyBvdmVyIG9ubHkgYSBzaW5nbGUgZG9tYWluLCBzZW5kIGZ1bGwgdHVwbGVzXG4gIC8vIHRocm91Z2ggZm9yIGVmZmljaWVuY3kgKGZld2VyIGFjY2Vzc29yIGNyZWF0aW9ucy9jYWxscylcbiAgaWYgKHJlZnMubGVuZ3RoID09IDEgJiYgdXRpbC5hcnJheShyZWZzWzBdLmZpZWxkKS5sZW5ndGggPT0gMSkge1xuICAgIHJldHVybiBBZ2dyZWdhdGUuVFlQRVMuVFVQTEU7XG4gIH1cblxuICAvLyBXaXRoIHF1YW50aXRhdGl2ZSBzY2FsZXMsIHdlIG9ubHkgY2FyZSBhYm91dCBtaW4vbWF4LlxuICBpZiAoIWlzVW5pcXVlcyhzY2FsZSkpIHJldHVybiBBZ2dyZWdhdGUuVFlQRVMuVkFMVUU7XG5cbiAgLy8gSWYgd2UgZG9uJ3Qgc29ydCwgdGhlbiB3ZSBjYW4gc2VuZCB2YWx1ZXMgZGlyZWN0bHkgdG8gYWdncnMgYXMgd2VsbFxuICBpZiAoIWRlZi5zb3J0KSByZXR1cm4gQWdncmVnYXRlLlRZUEVTLlZBTFVFO1xuXG4gIHJldHVybiBBZ2dyZWdhdGUuVFlQRVMuTVVMVEk7XG59XG5cbmZ1bmN0aW9uIGdldENhY2hlKHdoaWNoLCBkZWYsIHNjYWxlLCBncm91cCkge1xuICB2YXIgcmVmcyA9IGdldFJlZnMoZGVmKSxcbiAgICAgIGF0eXBlID0gYWdnclR5cGUoZGVmLCBzY2FsZSksXG4gICAgICB1bmlxdWVzID0gaXNVbmlxdWVzKHNjYWxlKSxcbiAgICAgIHNvcnQgPSBkZWYuc29ydCxcbiAgICAgIGNrID0gJ18nK3doaWNoLFxuICAgICAgZmllbGRzID0gZ2V0RmllbGRzKHJlZnNbMF0sIGdyb3VwKSxcbiAgICAgIHJlZjtcblxuICBpZiAoc2NhbGVbY2tdKSByZXR1cm4gc2NhbGVbY2tdO1xuXG4gIHZhciBjYWNoZSA9IHNjYWxlW2NrXSA9IG5ldyBBZ2dyZWdhdGUodGhpcy5fZ3JhcGgpLnR5cGUoYXR5cGUpLFxuICAgICAgZ3JvdXBieSwgc3VtbWFyaXplO1xuXG4gIGlmICh1bmlxdWVzKSB7XG4gICAgaWYgKGF0eXBlID09PSBBZ2dyZWdhdGUuVFlQRVMuVkFMVUUpIHtcbiAgICAgIGdyb3VwYnkgPSBbeyBuYW1lOiBEYXRhUmVmLkdST1VQQlksIGdldDogdXRpbC5pZGVudGl0eSB9XTtcbiAgICAgIHN1bW1hcml6ZSA9IHsnKic6IERhdGFSZWYuQ09VTlR9O1xuICAgIH0gZWxzZSBpZiAoYXR5cGUgPT09IEFnZ3JlZ2F0ZS5UWVBFUy5UVVBMRSkge1xuICAgICAgZ3JvdXBieSA9IFt7IG5hbWU6IERhdGFSZWYuR1JPVVBCWSwgZ2V0OiB1dGlsLiQoZmllbGRzWzBdKSB9XTtcbiAgICAgIHN1bW1hcml6ZSA9IHNvcnQgPyBbe1xuICAgICAgICBmaWVsZDogRGF0YVJlZi5WQUxVRSxcbiAgICAgICAgZ2V0OiAgdXRpbC4kKHJlZi5zb3J0IHx8IHNvcnQuZmllbGQpLFxuICAgICAgICBvcHM6IFtzb3J0Lm9wXVxuICAgICAgfV0gOiB7JyonOiBEYXRhUmVmLkNPVU5UfTtcbiAgICB9IGVsc2UgeyAgLy8gYXR5cGUgPT09IEFnZ3JlZ2F0ZS5UWVBFUy5NVUxUSVxuICAgICAgZ3JvdXBieSAgID0gRGF0YVJlZi5HUk9VUEJZO1xuICAgICAgc3VtbWFyaXplID0gW3sgZmllbGQ6IERhdGFSZWYuVkFMVUUsIG9wczogW3NvcnQub3BdIH1dOyBcbiAgICB9XG4gIH0gZWxzZSB7XG4gICAgZ3JvdXBieSA9IFtdO1xuICAgIHN1bW1hcml6ZSA9IFt7XG4gICAgICBmaWVsZDogRGF0YVJlZi5WQUxVRSxcbiAgICAgIGdldDogKGF0eXBlID09IEFnZ3JlZ2F0ZS5UWVBFUy5UVVBMRSkgPyB1dGlsLiQoZmllbGRzWzBdKSA6IHV0aWwuaWRlbnRpdHksXG4gICAgICBvcHM6IFtEYXRhUmVmLk1JTiwgRGF0YVJlZi5NQVhdLFxuICAgICAgYXM6ICBbRGF0YVJlZi5NSU4sIERhdGFSZWYuTUFYXVxuICAgIH1dO1xuICB9XG5cbiAgY2FjaGUucGFyYW0oJ2dyb3VwYnknLCBncm91cGJ5KVxuICAgIC5wYXJhbSgnc3VtbWFyaXplJywgc3VtbWFyaXplKTtcblxuICByZXR1cm4gY2FjaGU7XG59XG5cbmZ1bmN0aW9uIGRhdGFSZWYod2hpY2gsIGRlZiwgc2NhbGUsIGdyb3VwKSB7XG4gIGlmIChkZWYgPT0gbnVsbCkgeyByZXR1cm4gW107IH1cbiAgaWYgKHV0aWwuaXNBcnJheShkZWYpKSByZXR1cm4gZGVmLm1hcChzaWduYWwuYmluZCh0aGlzKSk7XG5cbiAgdmFyIHNlbGYgPSB0aGlzLCBncmFwaCA9IHRoaXMuX2dyYXBoLFxuICAgICAgcmVmcyA9IGdldFJlZnMoZGVmKSxcbiAgICAgIGF0eXBlID0gYWdnclR5cGUoZGVmLCBzY2FsZSksXG4gICAgICBjYWNoZSA9IGdldENhY2hlLmFwcGx5KHRoaXMsIGFyZ3VtZW50cyksXG4gICAgICBzb3J0ICA9IGRlZi5zb3J0LFxuICAgICAgdW5pcXVlcyA9IGlzVW5pcXVlcyhzY2FsZSksXG4gICAgICBpLCBybGVuLCBqLCBmbGVuLCByZWYsIGZpZWxkcywgZmllbGQsIGRhdGEsIGZyb207XG5cbiAgZnVuY3Rpb24gYWRkRGVwKHMpIHtcbiAgICBzZWxmLmRlcGVuZGVuY3koRGVwcy5TSUdOQUxTLCBzKTtcbiAgfVxuXG4gIGZvciAoaT0wLCBybGVuPXJlZnMubGVuZ3RoOyBpPHJsZW47ICsraSkge1xuICAgIHJlZiA9IHJlZnNbaV07XG4gICAgZnJvbSA9IHJlZi5kYXRhIHx8IGdyb3VwLmRhdHVtLl9mYWNldElEO1xuICAgIGRhdGEgPSBncmFwaC5kYXRhKGZyb20pXG4gICAgICAucmV2aXNlcyh0cnVlKVxuICAgICAgLmxhc3QoKTtcblxuICAgIGlmIChkYXRhLnN0YW1wIDw9IHRoaXMuX3N0YW1wKSBjb250aW51ZTtcblxuICAgIGZpZWxkcyA9IGdldEZpZWxkcyhyZWYsIGdyb3VwKTtcbiAgICBmb3IgKGo9MCwgZmxlbj1maWVsZHMubGVuZ3RoOyBqPGZsZW47ICsraikge1xuICAgICAgZmllbGQgPSBmaWVsZHNbal07XG5cbiAgICAgIGlmIChhdHlwZSA9PT0gQWdncmVnYXRlLlRZUEVTLlZBTFVFKSB7XG4gICAgICAgIGNhY2hlLmFjY2Vzc29ycyhudWxsLCBmaWVsZCk7XG4gICAgICB9IGVsc2UgaWYgKGF0eXBlID09PSBBZ2dyZWdhdGUuVFlQRVMuTVVMVEkpIHtcbiAgICAgICAgY2FjaGUuYWNjZXNzb3JzKGZpZWxkLCByZWYuc29ydCB8fCBzb3J0LmZpZWxkKTtcbiAgICAgIH0gLy8gRWxzZSAoVHVwbGUtY2FzZSkgaXMgaGFuZGxlZCBieSB0aGUgYWdncmVnYXRvciBhY2Nlc3NvcnMgYnkgZGVmYXVsdFxuXG4gICAgICBjYWNoZS5ldmFsdWF0ZShkYXRhKTtcbiAgICB9XG5cbiAgICB0aGlzLmRlcGVuZGVuY3koRGVwcy5EQVRBLCBmcm9tKTtcbiAgICBjYWNoZS5kZXBlbmRlbmN5KERlcHMuU0lHTkFMUykuZm9yRWFjaChhZGREZXApO1xuICB9XG5cbiAgZGF0YSA9IGNhY2hlLmFnZ3IoKS5yZXN1bHQoKTtcbiAgaWYgKHVuaXF1ZXMpIHtcbiAgICBpZiAoc29ydCkge1xuICAgICAgc29ydCA9IHNvcnQub3JkZXIuc2lnbmFsID8gZ3JhcGguc2lnbmFsUmVmKHNvcnQub3JkZXIuc2lnbmFsKSA6IHNvcnQub3JkZXI7XG4gICAgICBzb3J0ID0gKHNvcnQgPT0gRGF0YVJlZi5ERVNDID8gJy0nIDogJysnKSArIERhdGFSZWYuVkFMVUU7XG4gICAgICBzb3J0ID0gdXRpbC5jb21wYXJhdG9yKHNvcnQpO1xuICAgICAgZGF0YSA9IGRhdGEuc29ydChzb3J0KTtcbiAgICAvLyB9IGVsc2UgeyAgLy8gJ0ZpcnN0IHNlZW4nIG9yZGVyXG4gICAgLy8gICBzb3J0ID0gdXRpbC5jb21wYXJhdG9yKCd0cGwuX2lkJyk7XG4gICAgfVxuXG4gICAgcmV0dXJuIGRhdGEubWFwKGZ1bmN0aW9uKGQpIHsgcmV0dXJuIGRbRGF0YVJlZi5HUk9VUEJZXTsgfSk7XG4gIH0gZWxzZSB7XG4gICAgZGF0YSA9IGRhdGFbMF07XG4gICAgcmV0dXJuICF1dGlsLmlzVmFsaWQoZGF0YSkgPyBbXSA6IFtkYXRhW0RhdGFSZWYuTUlOXSwgZGF0YVtEYXRhUmVmLk1BWF1dO1xuICB9XG59XG5cbmZ1bmN0aW9uIHNpZ25hbCh2KSB7XG4gIGlmICghdiB8fCAhdi5zaWduYWwpIHJldHVybiB2O1xuICB2YXIgcyA9IHYuc2lnbmFsLCByZWY7XG4gIHRoaXMuZGVwZW5kZW5jeShEZXBzLlNJR05BTFMsIChyZWYgPSB1dGlsLmZpZWxkKHMpKVswXSk7XG4gIHJldHVybiB0aGlzLl9ncmFwaC5zaWduYWxSZWYocmVmKTtcbn1cblxuZnVuY3Rpb24gZG9tYWluTWluTWF4KHNjYWxlLCBncm91cCkge1xuICB2YXIgZGVmID0gdGhpcy5fZGVmLFxuICAgICAgZG9tYWluID0gW251bGwsIG51bGxdLCB6O1xuXG4gIGlmIChkZWYuZG9tYWluICE9PSB1bmRlZmluZWQpIHtcbiAgICBkb21haW4gPSAoIXV0aWwuaXNPYmplY3QoZGVmLmRvbWFpbikpID8gZG9tYWluIDpcbiAgICAgIGRhdGFSZWYuY2FsbCh0aGlzLCBEYXRhUmVmLkRPTUFJTiwgZGVmLmRvbWFpbiwgc2NhbGUsIGdyb3VwKTtcbiAgfVxuXG4gIHogPSBkb21haW4ubGVuZ3RoIC0gMTtcbiAgaWYgKGRlZi5kb21haW5NaW4gIT09IHVuZGVmaW5lZCkge1xuICAgIGlmICh1dGlsLmlzT2JqZWN0KGRlZi5kb21haW5NaW4pKSB7XG4gICAgICBpZiAoZGVmLmRvbWFpbk1pbi5zaWduYWwpIHtcbiAgICAgICAgZG9tYWluWzBdID0gc2lnbmFsLmNhbGwodGhpcywgZGVmLmRvbWFpbk1pbik7XG4gICAgICB9IGVsc2Uge1xuICAgICAgICBkb21haW5bMF0gPSBkYXRhUmVmLmNhbGwodGhpcywgRGF0YVJlZi5ET01BSU4rRGF0YVJlZi5NSU4sIGRlZi5kb21haW5NaW4sIHNjYWxlLCBncm91cClbMF07XG4gICAgICB9XG4gICAgfSBlbHNlIHtcbiAgICAgIGRvbWFpblswXSA9IGRlZi5kb21haW5NaW47XG4gICAgfVxuICB9XG4gIGlmIChkZWYuZG9tYWluTWF4ICE9PSB1bmRlZmluZWQpIHtcbiAgICBpZiAodXRpbC5pc09iamVjdChkZWYuZG9tYWluTWF4KSkge1xuICAgICAgaWYgKGRlZi5kb21haW5NYXguc2lnbmFsKSB7XG4gICAgICAgIGRvbWFpblt6XSA9IHNpZ25hbC5jYWxsKHRoaXMsIGRlZi5kb21haW5NYXgpO1xuICAgICAgfSBlbHNlIHtcbiAgICAgICAgZG9tYWluW3pdID0gZGF0YVJlZi5jYWxsKHRoaXMsIERhdGFSZWYuRE9NQUlOK0RhdGFSZWYuTUFYLCBkZWYuZG9tYWluTWF4LCBzY2FsZSwgZ3JvdXApWzFdO1xuICAgICAgfVxuICAgIH0gZWxzZSB7XG4gICAgICBkb21haW5bel0gPSBkZWYuZG9tYWluTWF4O1xuICAgIH1cbiAgfVxuICBpZiAoZGVmLnR5cGUgIT09IFR5cGVzLkxPRyAmJiBkZWYudHlwZSAhPT0gVHlwZXMuVElNRSAmJiAoZGVmLnplcm8gfHwgZGVmLnplcm89PT11bmRlZmluZWQpKSB7XG4gICAgZG9tYWluWzBdID0gTWF0aC5taW4oMCwgZG9tYWluWzBdKTtcbiAgICBkb21haW5bel0gPSBNYXRoLm1heCgwLCBkb21haW5bel0pO1xuICB9XG4gIHJldHVybiBkb21haW47XG59XG5cbmZ1bmN0aW9uIHJhbmdlKGdyb3VwKSB7XG4gIHZhciBkZWYgPSB0aGlzLl9kZWYsXG4gICAgICBjb25maWcgPSB0aGlzLl9ncmFwaC5jb25maWcoKSxcbiAgICAgIHJhbmdlVmFsID0gc2lnbmFsLmNhbGwodGhpcywgZGVmLnJhbmdlKSxcbiAgICAgIHJuZyA9IFtudWxsLCBudWxsXTtcblxuICBpZiAocmFuZ2VWYWwgIT09IHVuZGVmaW5lZCkge1xuICAgIGlmICh0eXBlb2YgcmFuZ2VWYWwgPT09ICdzdHJpbmcnKSB7XG4gICAgICBpZiAoUHJvcGVydGllc1tyYW5nZVZhbF0pIHtcbiAgICAgICAgcm5nID0gWzAsIGdyb3VwW3JhbmdlVmFsXV07XG4gICAgICB9IGVsc2UgaWYgKGNvbmZpZy5yYW5nZVtyYW5nZVZhbF0pIHtcbiAgICAgICAgcm5nID0gY29uZmlnLnJhbmdlW3JhbmdlVmFsXTtcbiAgICAgIH0gZWxzZSB7XG4gICAgICAgIGxvZy5lcnJvcignVW5yZWNvZ2l6ZWQgcmFuZ2U6ICcgKyByYW5nZVZhbCk7XG4gICAgICAgIHJldHVybiBybmc7XG4gICAgICB9XG4gICAgfSBlbHNlIGlmICh1dGlsLmlzQXJyYXkocmFuZ2VWYWwpKSB7XG4gICAgICBybmcgPSB1dGlsLmR1cGxpY2F0ZShyYW5nZVZhbCkubWFwKHNpZ25hbC5iaW5kKHRoaXMpKTtcbiAgICB9IGVsc2UgaWYgKHV0aWwuaXNPYmplY3QocmFuZ2VWYWwpKSB7XG4gICAgICByZXR1cm4gbnVsbDsgLy8gZWFybHkgZXhpdFxuICAgIH0gZWxzZSB7XG4gICAgICBybmcgPSBbMCwgcmFuZ2VWYWxdO1xuICAgIH1cbiAgfVxuICBpZiAoZGVmLnJhbmdlTWluICE9PSB1bmRlZmluZWQpIHtcbiAgICBybmdbMF0gPSBkZWYucmFuZ2VNaW4uc2lnbmFsID9cbiAgICAgIHNpZ25hbC5jYWxsKHRoaXMsIGRlZi5yYW5nZU1pbikgOlxuICAgICAgZGVmLnJhbmdlTWluO1xuICB9XG4gIGlmIChkZWYucmFuZ2VNYXggIT09IHVuZGVmaW5lZCkge1xuICAgIHJuZ1tybmcubGVuZ3RoLTFdID0gZGVmLnJhbmdlTWF4LnNpZ25hbCA/XG4gICAgICBzaWduYWwuY2FsbCh0aGlzLCBkZWYucmFuZ2VNYXgpIDpcbiAgICAgIGRlZi5yYW5nZU1heDtcbiAgfVxuICBcbiAgaWYgKGRlZi5yZXZlcnNlICE9PSB1bmRlZmluZWQpIHtcbiAgICB2YXIgcmV2ID0gc2lnbmFsLmNhbGwodGhpcywgZGVmLnJldmVyc2UpO1xuICAgIGlmICh1dGlsLmlzT2JqZWN0KHJldikpIHtcbiAgICAgIHJldiA9IHV0aWwuYWNjZXNzb3IocmV2LmZpZWxkKShncm91cC5kYXR1bSk7XG4gICAgfVxuICAgIGlmIChyZXYpIHJuZyA9IHJuZy5yZXZlcnNlKCk7XG4gIH1cbiAgXG4gIHJldHVybiBybmc7XG59XG5cbm1vZHVsZS5leHBvcnRzID0gU2NhbGU7Il19
},{"../transforms/Aggregate":110,"datalib/src/util":20,"vega-dataflow/src/ChangeSet":26,"vega-dataflow/src/Dependencies":29,"vega-dataflow/src/Node":31,"vega-logging":41}],106:[function(require,module,exports){
(function (global){
var d3 = (typeof window !== "undefined" ? window.d3 : typeof global !== "undefined" ? global.d3 : null),
bound = require('vega-scenegraph/src/util/bound'),
tuple = require('vega-dataflow/src/Tuple'),
Status = require('./Builder').STATUS;
function Transition(duration, ease) {
this.duration = duration || 500;
this.ease = ease && d3.ease(ease) || d3.ease("cubic-in-out");
this.updates = {next: null};
}
var prototype = Transition.prototype;
var skip = {
"text": 1,
"url": 1
};
prototype.interpolate = function(item, values) {
var key, curr, next, interp, list = null;
for (key in values) {
curr = item[key];
next = values[key];
if (curr !== next) {
if (skip[key] || curr === undefined) {
// skip interpolation for specific keys or undefined start values
tuple.set(item, key, next);
} else if (typeof curr === "number" && !isFinite(curr)) {
// for NaN or infinite numeric values, skip to final value
tuple.set(item, key, next);
} else {
// otherwise lookup interpolator
interp = d3.interpolate(curr, next);
interp.property = key;
(list || (list=[])).push(interp);
}
}
}
if (list === null && item.status === Status.EXIT) {
list = []; // ensure exiting items are included
}
if (list != null) {
list.item = item;
list.ease = item.mark.ease || this.ease;
list.next = this.updates.next;
this.updates.next = list;
}
return this;
};
prototype.start = function(callback) {
var t = this, prev = t.updates, curr = prev.next;
for (; curr!=null; prev=curr, curr=prev.next) {
if (curr.item.status === Status.EXIT) {
// Only mark item as exited when it is removed.
curr.item.status = Status.UPDATE;
curr.remove = true;
}
}
t.callback = callback;
d3.timer(function(elapsed) { return step.call(t, elapsed); });
};
function step(elapsed) {
var list = this.updates, prev = list, curr = prev.next,
duration = this.duration,
item, delay, f, e, i, n, stop = true;
for (; curr!=null; prev=curr, curr=prev.next) {
item = curr.item;
delay = item.delay || 0;
f = (elapsed - delay) / duration;
if (f < 0) { stop = false; continue; }
if (f > 1) f = 1;
e = curr.ease(f);
for (i=0, n=curr.length; i<n; ++i) {
item[curr[i].property] = curr[i](e);
}
item.touch();
bound.item(item);
if (f === 1) {
if (curr.remove) {
item.status = Status.EXIT;
item.remove();
}
prev.next = curr.next;
curr = prev;
} else {
stop = false;
}
}
this.callback();
return stop;
}
module.exports = Transition;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNyYy9zY2VuZS9UcmFuc2l0aW9uLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSIsImZpbGUiOiJnZW5lcmF0ZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlc0NvbnRlbnQiOlsidmFyIGQzID0gKHR5cGVvZiB3aW5kb3cgIT09IFwidW5kZWZpbmVkXCIgPyB3aW5kb3cuZDMgOiB0eXBlb2YgZ2xvYmFsICE9PSBcInVuZGVmaW5lZFwiID8gZ2xvYmFsLmQzIDogbnVsbCksXG4gICAgYm91bmQgPSByZXF1aXJlKCd2ZWdhLXNjZW5lZ3JhcGgvc3JjL3V0aWwvYm91bmQnKSxcbiAgICB0dXBsZSA9IHJlcXVpcmUoJ3ZlZ2EtZGF0YWZsb3cvc3JjL1R1cGxlJyksXG4gICAgU3RhdHVzID0gcmVxdWlyZSgnLi9CdWlsZGVyJykuU1RBVFVTO1xuXG5mdW5jdGlvbiBUcmFuc2l0aW9uKGR1cmF0aW9uLCBlYXNlKSB7XG4gIHRoaXMuZHVyYXRpb24gPSBkdXJhdGlvbiB8fCA1MDA7XG4gIHRoaXMuZWFzZSA9IGVhc2UgJiYgZDMuZWFzZShlYXNlKSB8fCBkMy5lYXNlKFwiY3ViaWMtaW4tb3V0XCIpO1xuICB0aGlzLnVwZGF0ZXMgPSB7bmV4dDogbnVsbH07XG59XG5cbnZhciBwcm90b3R5cGUgPSBUcmFuc2l0aW9uLnByb3RvdHlwZTtcblxudmFyIHNraXAgPSB7XG4gIFwidGV4dFwiOiAxLFxuICBcInVybFwiOiAgMVxufTtcblxucHJvdG90eXBlLmludGVycG9sYXRlID0gZnVuY3Rpb24oaXRlbSwgdmFsdWVzKSB7XG4gIHZhciBrZXksIGN1cnIsIG5leHQsIGludGVycCwgbGlzdCA9IG51bGw7XG5cbiAgZm9yIChrZXkgaW4gdmFsdWVzKSB7XG4gICAgY3VyciA9IGl0ZW1ba2V5XTtcbiAgICBuZXh0ID0gdmFsdWVzW2tleV07ICAgICAgXG4gICAgaWYgKGN1cnIgIT09IG5leHQpIHtcbiAgICAgIGlmIChza2lwW2tleV0gfHwgY3VyciA9PT0gdW5kZWZpbmVkKSB7XG4gICAgICAgIC8vIHNraXAgaW50ZXJwb2xhdGlvbiBmb3Igc3BlY2lmaWMga2V5cyBvciB1bmRlZmluZWQgc3RhcnQgdmFsdWVzXG4gICAgICAgIHR1cGxlLnNldChpdGVtLCBrZXksIG5leHQpO1xuICAgICAgfSBlbHNlIGlmICh0eXBlb2YgY3VyciA9PT0gXCJudW1iZXJcIiAmJiAhaXNGaW5pdGUoY3VycikpIHtcbiAgICAgICAgLy8gZm9yIE5hTiBvciBpbmZpbml0ZSBudW1lcmljIHZhbHVlcywgc2tpcCB0byBmaW5hbCB2YWx1ZVxuICAgICAgICB0dXBsZS5zZXQoaXRlbSwga2V5LCBuZXh0KTtcbiAgICAgIH0gZWxzZSB7XG4gICAgICAgIC8vIG90aGVyd2lzZSBsb29rdXAgaW50ZXJwb2xhdG9yXG4gICAgICAgIGludGVycCA9IGQzLmludGVycG9sYXRlKGN1cnIsIG5leHQpO1xuICAgICAgICBpbnRlcnAucHJvcGVydHkgPSBrZXk7XG4gICAgICAgIChsaXN0IHx8IChsaXN0PVtdKSkucHVzaChpbnRlcnApO1xuICAgICAgfVxuICAgIH1cbiAgfVxuXG4gIGlmIChsaXN0ID09PSBudWxsICYmIGl0ZW0uc3RhdHVzID09PSBTdGF0dXMuRVhJVCkge1xuICAgIGxpc3QgPSBbXTsgLy8gZW5zdXJlIGV4aXRpbmcgaXRlbXMgYXJlIGluY2x1ZGVkXG4gIH1cblxuICBpZiAobGlzdCAhPSBudWxsKSB7XG4gICAgbGlzdC5pdGVtID0gaXRlbTtcbiAgICBsaXN0LmVhc2UgPSBpdGVtLm1hcmsuZWFzZSB8fCB0aGlzLmVhc2U7XG4gICAgbGlzdC5uZXh0ID0gdGhpcy51cGRhdGVzLm5leHQ7XG4gICAgdGhpcy51cGRhdGVzLm5leHQgPSBsaXN0O1xuICB9XG4gIHJldHVybiB0aGlzO1xufTtcblxucHJvdG90eXBlLnN0YXJ0ID0gZnVuY3Rpb24oY2FsbGJhY2spIHtcbiAgdmFyIHQgPSB0aGlzLCBwcmV2ID0gdC51cGRhdGVzLCBjdXJyID0gcHJldi5uZXh0O1xuICBmb3IgKDsgY3VyciE9bnVsbDsgcHJldj1jdXJyLCBjdXJyPXByZXYubmV4dCkge1xuICAgIGlmIChjdXJyLml0ZW0uc3RhdHVzID09PSBTdGF0dXMuRVhJVCkge1xuICAgICAgLy8gT25seSBtYXJrIGl0ZW0gYXMgZXhpdGVkIHdoZW4gaXQgaXMgcmVtb3ZlZC5cbiAgICAgIGN1cnIuaXRlbS5zdGF0dXMgPSBTdGF0dXMuVVBEQVRFO1xuICAgICAgY3Vyci5yZW1vdmUgPSB0cnVlO1xuICAgIH1cbiAgfVxuICB0LmNhbGxiYWNrID0gY2FsbGJhY2s7XG4gIGQzLnRpbWVyKGZ1bmN0aW9uKGVsYXBzZWQpIHsgcmV0dXJuIHN0ZXAuY2FsbCh0LCBlbGFwc2VkKTsgfSk7XG59O1xuXG5mdW5jdGlvbiBzdGVwKGVsYXBzZWQpIHtcbiAgdmFyIGxpc3QgPSB0aGlzLnVwZGF0ZXMsIHByZXYgPSBsaXN0LCBjdXJyID0gcHJldi5uZXh0LFxuICAgICAgZHVyYXRpb24gPSB0aGlzLmR1cmF0aW9uLFxuICAgICAgaXRlbSwgZGVsYXksIGYsIGUsIGksIG4sIHN0b3AgPSB0cnVlO1xuXG4gIGZvciAoOyBjdXJyIT1udWxsOyBwcmV2PWN1cnIsIGN1cnI9cHJldi5uZXh0KSB7XG4gICAgaXRlbSA9IGN1cnIuaXRlbTtcbiAgICBkZWxheSA9IGl0ZW0uZGVsYXkgfHwgMDtcblxuICAgIGYgPSAoZWxhcHNlZCAtIGRlbGF5KSAvIGR1cmF0aW9uO1xuICAgIGlmIChmIDwgMCkgeyBzdG9wID0gZmFsc2U7IGNvbnRpbnVlOyB9XG4gICAgaWYgKGYgPiAxKSBmID0gMTtcbiAgICBlID0gY3Vyci5lYXNlKGYpO1xuXG4gICAgZm9yIChpPTAsIG49Y3Vyci5sZW5ndGg7IGk8bjsgKytpKSB7XG4gICAgICBpdGVtW2N1cnJbaV0ucHJvcGVydHldID0gY3VycltpXShlKTtcbiAgICB9XG4gICAgaXRlbS50b3VjaCgpO1xuICAgIGJvdW5kLml0ZW0oaXRlbSk7XG5cbiAgICBpZiAoZiA9PT0gMSkge1xuICAgICAgaWYgKGN1cnIucmVtb3ZlKSB7XG4gICAgICAgIGl0ZW0uc3RhdHVzID0gU3RhdHVzLkVYSVQ7XG4gICAgICAgIGl0ZW0ucmVtb3ZlKCk7XG4gICAgICB9XG4gICAgICBwcmV2Lm5leHQgPSBjdXJyLm5leHQ7XG4gICAgICBjdXJyID0gcHJldjtcbiAgICB9IGVsc2Uge1xuICAgICAgc3RvcCA9IGZhbHNlO1xuICAgIH1cbiAgfVxuXG4gIHRoaXMuY2FsbGJhY2soKTtcbiAgcmV0dXJuIHN0b3A7XG59XG5cbm1vZHVsZS5leHBvcnRzID0gVHJhbnNpdGlvbjsiXX0=
},{"./Builder":102,"vega-dataflow/src/Tuple":34,"vega-scenegraph/src/util/bound":74}],107:[function(require,module,exports){
(function (global){
var d3 = (typeof window !== "undefined" ? window.d3 : typeof global !== "undefined" ? global.d3 : null),
util = require('datalib/src/util'),
tpl = require('vega-dataflow/src/Tuple'),
parseMark = require('../parse/mark');
function axs(model) {
var scale,
config = model.config(),
orient = config.axis.orient,
offset = 0,
titleOffset = config.axis.titleOffset,
axisDef = {},
layer = "front",
grid = false,
title = null,
tickMajorSize = config.axis.tickSize,
tickMinorSize = config.axis.tickSize,
tickEndSize = config.axis.tickSize,
tickPadding = config.axis.padding,
tickValues = null,
tickFormatString = null,
tickSubdivide = 0,
tickCount = config.axis.ticks,
gridLineStyle = {},
tickLabelStyle = {},
majorTickStyle = {},
minorTickStyle = {},
titleStyle = {},
domainStyle = {},
m = { // Axis marks as references for updates
gridLines: {},
majorTicks: {},
minorTicks: {},
tickLabels: {},
domain: {},
title: {}
};
var axis = {};
function reset() {
axisDef.type = null;
}
function ingest(d) {
return {data: d};
}
function getTickFormatString() {
return tickFormatString || (scale.type === 'log' ? ".1s" : null);
}
function getTickFormatFn(fmtStr) {
return (!fmtStr && String) || ((scale.type === 'time') ?
d3.time.format(fmtStr) : d3.format(fmtStr));
}
function buildTickFormat() {
var fmtStr = getTickFormatString();
// D3 v3 has an inconsistent tickFormat API for time scales.
if (scale.tickFormat) {
return fmtStr ?
(scale.tickFormat.length === 2 ?
scale.tickFormat(tickCount, fmtStr) : getTickFormatFn(fmtStr)) :
scale.tickFormat(tickCount);
}
return getTickFormatFn(fmtStr);
}
function buildTicks(fmt) {
var ticks = {
major: tickValues,
minor: null
};
if (ticks.major == null) {
ticks.major = scale.ticks ?
scale.ticks(tickCount) : scale.domain();
}
ticks.minor = vg_axisSubdivide(scale, ticks.major, tickSubdivide)
.map(ingest);
ticks.major = ticks.major.map(function(d) {
return (d = ingest(d), d.label = fmt(d.data), d);
});
return ticks;
}
axis.def = function() {
if(!axisDef.type) axis_def(scale);
var fmt = buildTickFormat();
var ticks = buildTicks(fmt);
var tdata = title ? [title].map(ingest) : [];
axisDef.marks[0].from = function() { return grid ? ticks.major : []; };
axisDef.marks[1].from = function() { return ticks.major; };
axisDef.marks[2].from = function() { return ticks.minor; };
axisDef.marks[3].from = axisDef.marks[1].from;
axisDef.marks[4].from = function() { return [1]; };
axisDef.marks[5].from = function() { return tdata; };
axisDef.offset = offset;
axisDef.orient = orient;
axisDef.layer = layer;
return axisDef;
};
function axis_def(scale) {
// setup scale mapping
var newScale, oldScale, range;
if (scale.type === "ordinal") {
newScale = {scale: scale.scaleName, offset: 0.5 + scale.rangeBand()/2};
oldScale = newScale;
} else {
newScale = {scale: scale.scaleName, offset: 0.5};
oldScale = {scale: scale.scaleName+":prev", offset: 0.5};
}
range = vg_axisScaleRange(scale);
// setup axis marks
util.extend(m.gridLines, vg_axisTicks(config));
util.extend(m.majorTicks, vg_axisTicks(config));
util.extend(m.minorTicks, vg_axisTicks(config));
util.extend(m.tickLabels, vg_axisTickLabels(config));
util.extend(m.domain, vg_axisDomain(config));
util.extend(m.title, vg_axisTitle(config));
m.gridLines.properties.enter.stroke = {value: config.axis.gridColor};
m.gridLines.properties.enter.strokeOpacity = {value: config.axis.gridOpacity};
// extend axis marks based on axis orientation
vg_axisTicksExtend(orient, m.gridLines, oldScale, newScale, Infinity);
vg_axisTicksExtend(orient, m.majorTicks, oldScale, newScale, tickMajorSize);
vg_axisTicksExtend(orient, m.minorTicks, oldScale, newScale, tickMinorSize);
vg_axisLabelExtend(orient, m.tickLabels, oldScale, newScale, tickMajorSize, tickPadding);
vg_axisDomainExtend(orient, m.domain, range, tickEndSize);
vg_axisTitleExtend(orient, m.title, range, titleOffset); // TODO get offset
// add / override custom style properties
util.extend(m.gridLines.properties.update, gridLineStyle);
util.extend(m.majorTicks.properties.update, majorTickStyle);
util.extend(m.minorTicks.properties.update, minorTickStyle);
util.extend(m.tickLabels.properties.update, tickLabelStyle);
util.extend(m.domain.properties.update, domainStyle);
util.extend(m.title.properties.update, titleStyle);
var marks = [m.gridLines, m.majorTicks, m.minorTicks, m.tickLabels, m.domain, m.title];
util.extend(axisDef, {
type: "group",
interactive: false,
properties: {
enter: {
encode: vg_axisUpdate,
scales: [scale.scaleName],
signals: [], data: []
},
update: {
encode: vg_axisUpdate,
scales: [scale.scaleName],
signals: [], data: []
}
}
});
axisDef.marks = marks.map(function(m) { return parseMark(model, m); });
}
axis.scale = function(x) {
if (!arguments.length) return scale;
if (scale !== x) { scale = x; reset(); }
return axis;
};
axis.orient = function(x) {
if (!arguments.length) return orient;
if (orient !== x) {
orient = x in vg_axisOrients ? x + "" : config.axis.orient;
reset();
}
return axis;
};
axis.title = function(x) {
if (!arguments.length) return title;
if (title !== x) { title = x; reset(); }
return axis;
};
axis.tickCount = function(x) {
if (!arguments.length) return tickCount;
tickCount = x;
return axis;
};
axis.tickValues = function(x) {
if (!arguments.length) return tickValues;
tickValues = x;
return axis;
};
axis.tickFormat = function(x) {
if (!arguments.length) return tickFormatString;
if (tickFormatString !== x) {
tickFormatString = x;
reset();
}
return axis;
};
axis.tickSize = function(x, y) {
if (!arguments.length) return tickMajorSize;
var n = arguments.length - 1,
major = +x,
minor = n > 1 ? +y : tickMajorSize,
end = n > 0 ? +arguments[n] : tickMajorSize;
if (tickMajorSize !== major ||
tickMinorSize !== minor ||
tickEndSize !== end) {
reset();
}
tickMajorSize = major;
tickMinorSize = minor;
tickEndSize = end;
return axis;
};
axis.tickSubdivide = function(x) {
if (!arguments.length) return tickSubdivide;
tickSubdivide = +x;
return axis;
};
axis.offset = function(x) {
if (!arguments.length) return offset;
offset = util.isObject(x) ? x : +x;
return axis;
};
axis.tickPadding = function(x) {
if (!arguments.length) return tickPadding;
if (tickPadding !== +x) { tickPadding = +x; reset(); }
return axis;
};
axis.titleOffset = function(x) {
if (!arguments.length) return titleOffset;
if (titleOffset !== +x) { titleOffset = +x; reset(); }
return axis;
};
axis.layer = function(x) {
if (!arguments.length) return layer;
if (layer !== x) { layer = x; reset(); }
return axis;
};
axis.grid = function(x) {
if (!arguments.length) return grid;
if (grid !== x) { grid = x; reset(); }
return axis;
};
axis.gridLineProperties = function(x) {
if (!arguments.length) return gridLineStyle;
if (gridLineStyle !== x) { gridLineStyle = x; }
return axis;
};
axis.majorTickProperties = function(x) {
if (!arguments.length) return majorTickStyle;
if (majorTickStyle !== x) { majorTickStyle = x; }
return axis;
};
axis.minorTickProperties = function(x) {
if (!arguments.length) return minorTickStyle;
if (minorTickStyle !== x) { minorTickStyle = x; }
return axis;
};
axis.tickLabelProperties = function(x) {
if (!arguments.length) return tickLabelStyle;
if (tickLabelStyle !== x) { tickLabelStyle = x; }
return axis;
};
axis.titleProperties = function(x) {
if (!arguments.length) return titleStyle;
if (titleStyle !== x) { titleStyle = x; }
return axis;
};
axis.domainProperties = function(x) {
if (!arguments.length) return domainStyle;
if (domainStyle !== x) { domainStyle = x; }
return axis;
};
axis.reset = function() {
reset();
return axis;
};
return axis;
}
var vg_axisOrients = {top: 1, right: 1, bottom: 1, left: 1};
function vg_axisSubdivide(scale, ticks, m) {
var subticks = [];
if (m && ticks.length > 1) {
var extent = vg_axisScaleExtent(scale.domain()),
i = -1,
n = ticks.length,
d = (ticks[1] - ticks[0]) / ++m,
j,
v;
while (++i < n) {
for (j = m; --j > 0;) {
if ((v = +ticks[i] - j * d) >= extent[0]) {
subticks.push(v);
}
}
}
for (--i, j = 0; ++j < m && (v = +ticks[i] + j * d) < extent[1];) {
subticks.push(v);
}
}
return subticks;
}
function vg_axisScaleExtent(domain) {
var start = domain[0], stop = domain[domain.length - 1];
return start < stop ? [start, stop] : [stop, start];
}
function vg_axisScaleRange(scale) {
return scale.rangeExtent ?
scale.rangeExtent() :
vg_axisScaleExtent(scale.range());
}
var vg_axisAlign = {
bottom: "center",
top: "center",
left: "right",
right: "left"
};
var vg_axisBaseline = {
bottom: "top",
top: "bottom",
left: "middle",
right: "middle"
};
function vg_axisLabelExtend(orient, labels, oldScale, newScale, size, pad) {
size = Math.max(size, 0) + pad;
if (orient === "left" || orient === "top") {
size *= -1;
}
if (orient === "top" || orient === "bottom") {
util.extend(labels.properties.enter, {
x: oldScale,
y: {value: size},
});
util.extend(labels.properties.update, {
x: newScale,
y: {value: size},
align: {value: "center"},
baseline: {value: vg_axisBaseline[orient]}
});
} else {
util.extend(labels.properties.enter, {
x: {value: size},
y: oldScale,
});
util.extend(labels.properties.update, {
x: {value: size},
y: newScale,
align: {value: vg_axisAlign[orient]},
baseline: {value: "middle"}
});
}
}
function vg_axisTicksExtend(orient, ticks, oldScale, newScale, size) {
var sign = (orient === "left" || orient === "top") ? -1 : 1;
if (size === Infinity) {
size = (orient === "top" || orient === "bottom") ?
{field: {group: "height", level: 2}, mult: -sign} :
{field: {group: "width", level: 2}, mult: -sign};
} else {
size = {value: sign * size};
}
if (orient === "top" || orient === "bottom") {
util.extend(ticks.properties.enter, {
x: oldScale,
y: {value: 0},
y2: size
});
util.extend(ticks.properties.update, {
x: newScale,
y: {value: 0},
y2: size
});
util.extend(ticks.properties.exit, {
x: newScale,
});
} else {
util.extend(ticks.properties.enter, {
x: {value: 0},
x2: size,
y: oldScale
});
util.extend(ticks.properties.update, {
x: {value: 0},
x2: size,
y: newScale
});
util.extend(ticks.properties.exit, {
y: newScale,
});
}
}
function vg_axisTitleExtend(orient, title, range, offset) {
var mid = ~~((range[0] + range[1]) / 2),
sign = (orient === "top" || orient === "left") ? -1 : 1;
if (orient === "bottom" || orient === "top") {
util.extend(title.properties.update, {
x: {value: mid},
y: {value: sign*offset},
angle: {value: 0}
});
} else {
util.extend(title.properties.update, {
x: {value: sign*offset},
y: {value: mid},
angle: {value: orient === "left" ? -90 : 90}
});
}
}
function vg_axisDomainExtend(orient, domain, range, size) {
var path;
if (orient === "top" || orient === "left") {
size = -1 * size;
}
if (orient === "bottom" || orient === "top") {
path = "M" + range[0] + "," + size + "V0H" + range[1] + "V" + size;
} else {
path = "M" + size + "," + range[0] + "H0V" + range[1] + "H" + size;
}
domain.properties.update.path = {value: path};
}
function vg_axisUpdate(item, group, trans) {
var o = trans ? {} : item,
offset = item.mark.def.offset,
orient = item.mark.def.orient,
width = group.width,
height = group.height; // TODO fallback to global w,h?
if (util.isArray(offset)) {
var ofx = offset[0],
ofy = offset[1];
switch (orient) {
case "left": { tpl.set(o, 'x', -ofx); tpl.set(o, 'y', ofy); break; }
case "right": { tpl.set(o, 'x', width + ofx); tpl.set(o, 'y', ofy); break; }
case "bottom": { tpl.set(o, 'x', ofx); tpl.set(o, 'y', height + ofy); break; }
case "top": { tpl.set(o, 'x', ofx); tpl.set(o, 'y', -ofy); break; }
default: { tpl.set(o, 'x', ofx); tpl.set(o, 'y', ofy); }
}
} else {
if (util.isObject(offset)) {
offset = -group.scale(offset.scale)(offset.value);
}
switch (orient) {
case "left": { tpl.set(o, 'x', -offset); tpl.set(o, 'y', 0); break; }
case "right": { tpl.set(o, 'x', width + offset); tpl.set(o, 'y', 0); break; }
case "bottom": { tpl.set(o, 'x', 0); tpl.set(o, 'y', height + offset); break; }
case "top": { tpl.set(o, 'x', 0); tpl.set(o, 'y', -offset); break; }
default: { tpl.set(o, 'x', 0); tpl.set(o, 'y', 0); }
}
}
if (trans) trans.interpolate(item, o);
return true;
}
function vg_axisTicks(config) {
return {
type: "rule",
interactive: false,
key: "data",
properties: {
enter: {
stroke: {value: config.axis.tickColor},
strokeWidth: {value: config.axis.tickWidth},
opacity: {value: 1e-6}
},
exit: { opacity: {value: 1e-6} },
update: { opacity: {value: 1} }
}
};
}
function vg_axisTickLabels(config) {
return {
type: "text",
interactive: true,
key: "data",
properties: {
enter: {
fill: {value: config.axis.tickLabelColor},
font: {value: config.axis.tickLabelFont},
fontSize: {value: config.axis.tickLabelFontSize},
opacity: {value: 1e-6},
text: {field: "label"}
},
exit: { opacity: {value: 1e-6} },
update: { opacity: {value: 1} }
}
};
}
function vg_axisTitle(config) {
return {
type: "text",
interactive: true,
properties: {
enter: {
font: {value: config.axis.titleFont},
fontSize: {value: config.axis.titleFontSize},
fontWeight: {value: config.axis.titleFontWeight},
fill: {value: config.axis.titleColor},
align: {value: "center"},
baseline: {value: "middle"},
text: {field: "data"}
},
update: {}
}
};
}
function vg_axisDomain(config) {
return {
type: "path",
interactive: false,
properties: {
enter: {
x: {value: 0.5},
y: {value: 0.5},
stroke: {value: config.axis.axisColor},
strokeWidth: {value: config.axis.axisWidth}
},
update: {}
}
};
}
module.exports = axs;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNyYy9zY2VuZS9heGlzLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwiZmlsZSI6ImdlbmVyYXRlZC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgZDMgPSAodHlwZW9mIHdpbmRvdyAhPT0gXCJ1bmRlZmluZWRcIiA/IHdpbmRvdy5kMyA6IHR5cGVvZiBnbG9iYWwgIT09IFwidW5kZWZpbmVkXCIgPyBnbG9iYWwuZDMgOiBudWxsKSxcbiAgICB1dGlsID0gcmVxdWlyZSgnZGF0YWxpYi9zcmMvdXRpbCcpLFxuICAgIHRwbCA9IHJlcXVpcmUoJ3ZlZ2EtZGF0YWZsb3cvc3JjL1R1cGxlJyksXG4gICAgcGFyc2VNYXJrID0gcmVxdWlyZSgnLi4vcGFyc2UvbWFyaycpO1xuXG5mdW5jdGlvbiBheHMobW9kZWwpIHtcbiAgdmFyIHNjYWxlLFxuICAgICAgY29uZmlnID0gbW9kZWwuY29uZmlnKCksXG4gICAgICBvcmllbnQgPSBjb25maWcuYXhpcy5vcmllbnQsXG4gICAgICBvZmZzZXQgPSAwLFxuICAgICAgdGl0bGVPZmZzZXQgPSBjb25maWcuYXhpcy50aXRsZU9mZnNldCxcbiAgICAgIGF4aXNEZWYgPSB7fSxcbiAgICAgIGxheWVyID0gXCJmcm9udFwiLFxuICAgICAgZ3JpZCA9IGZhbHNlLFxuICAgICAgdGl0bGUgPSBudWxsLFxuICAgICAgdGlja01ham9yU2l6ZSA9IGNvbmZpZy5heGlzLnRpY2tTaXplLFxuICAgICAgdGlja01pbm9yU2l6ZSA9IGNvbmZpZy5heGlzLnRpY2tTaXplLFxuICAgICAgdGlja0VuZFNpemUgPSBjb25maWcuYXhpcy50aWNrU2l6ZSxcbiAgICAgIHRpY2tQYWRkaW5nID0gY29uZmlnLmF4aXMucGFkZGluZyxcbiAgICAgIHRpY2tWYWx1ZXMgPSBudWxsLFxuICAgICAgdGlja0Zvcm1hdFN0cmluZyA9IG51bGwsXG4gICAgICB0aWNrU3ViZGl2aWRlID0gMCxcbiAgICAgIHRpY2tDb3VudCA9IGNvbmZpZy5heGlzLnRpY2tzLFxuICAgICAgZ3JpZExpbmVTdHlsZSA9IHt9LFxuICAgICAgdGlja0xhYmVsU3R5bGUgPSB7fSxcbiAgICAgIG1ham9yVGlja1N0eWxlID0ge30sXG4gICAgICBtaW5vclRpY2tTdHlsZSA9IHt9LFxuICAgICAgdGl0bGVTdHlsZSA9IHt9LFxuICAgICAgZG9tYWluU3R5bGUgPSB7fSxcbiAgICAgIG0gPSB7IC8vIEF4aXMgbWFya3MgYXMgcmVmZXJlbmNlcyBmb3IgdXBkYXRlc1xuICAgICAgICBncmlkTGluZXM6ICB7fSxcbiAgICAgICAgbWFqb3JUaWNrczoge30sXG4gICAgICAgIG1pbm9yVGlja3M6IHt9LFxuICAgICAgICB0aWNrTGFiZWxzOiB7fSxcbiAgICAgICAgZG9tYWluOiB7fSxcbiAgICAgICAgdGl0bGU6ICB7fVxuICAgICAgfTtcblxuICB2YXIgYXhpcyA9IHt9O1xuXG4gIGZ1bmN0aW9uIHJlc2V0KCkge1xuICAgIGF4aXNEZWYudHlwZSA9IG51bGw7XG4gIH1cblxuICBmdW5jdGlvbiBpbmdlc3QoZCkge1xuICAgIHJldHVybiB7ZGF0YTogZH07XG4gIH1cblxuICBmdW5jdGlvbiBnZXRUaWNrRm9ybWF0U3RyaW5nKCkge1xuICAgIHJldHVybiB0aWNrRm9ybWF0U3RyaW5nIHx8IChzY2FsZS50eXBlID09PSAnbG9nJyA/IFwiLjFzXCIgOiBudWxsKTtcbiAgfVxuXG4gIGZ1bmN0aW9uIGdldFRpY2tGb3JtYXRGbihmbXRTdHIpIHtcbiAgICByZXR1cm4gKCFmbXRTdHIgJiYgU3RyaW5nKSB8fCAoKHNjYWxlLnR5cGUgPT09ICd0aW1lJykgP1xuICAgICAgZDMudGltZS5mb3JtYXQoZm10U3RyKSA6IGQzLmZvcm1hdChmbXRTdHIpKTtcbiAgfVxuICBcbiAgZnVuY3Rpb24gYnVpbGRUaWNrRm9ybWF0KCkge1xuICAgIHZhciBmbXRTdHIgPSBnZXRUaWNrRm9ybWF0U3RyaW5nKCk7XG4gICAgXG4gICAgLy8gRDMgdjMgaGFzIGFuIGluY29uc2lzdGVudCB0aWNrRm9ybWF0IEFQSSBmb3IgdGltZSBzY2FsZXMuXG4gICAgaWYgKHNjYWxlLnRpY2tGb3JtYXQpIHtcbiAgICAgIHJldHVybiBmbXRTdHIgP1xuICAgICAgICAoc2NhbGUudGlja0Zvcm1hdC5sZW5ndGggPT09IDIgP1xuICAgICAgICAgIHNjYWxlLnRpY2tGb3JtYXQodGlja0NvdW50LCBmbXRTdHIpIDogZ2V0VGlja0Zvcm1hdEZuKGZtdFN0cikpIDpcbiAgICAgICAgc2NhbGUudGlja0Zvcm1hdCh0aWNrQ291bnQpO1xuICAgIH1cblxuICAgIHJldHVybiBnZXRUaWNrRm9ybWF0Rm4oZm10U3RyKTtcbiAgfVxuICBcbiAgZnVuY3Rpb24gYnVpbGRUaWNrcyhmbXQpIHtcbiAgICB2YXIgdGlja3MgPSB7XG4gICAgICBtYWpvcjogdGlja1ZhbHVlcyxcbiAgICAgIG1pbm9yOiBudWxsXG4gICAgfTtcbiAgICBcbiAgICBpZiAodGlja3MubWFqb3IgPT0gbnVsbCkge1xuICAgICAgdGlja3MubWFqb3IgPSBzY2FsZS50aWNrcyA/XG4gICAgICAgIHNjYWxlLnRpY2tzKHRpY2tDb3VudCkgOiBzY2FsZS5kb21haW4oKTtcbiAgICB9XG4gIFxuICAgIHRpY2tzLm1pbm9yID0gdmdfYXhpc1N1YmRpdmlkZShzY2FsZSwgdGlja3MubWFqb3IsIHRpY2tTdWJkaXZpZGUpXG4gICAgICAubWFwKGluZ2VzdCk7XG4gIFxuICAgIHRpY2tzLm1ham9yID0gdGlja3MubWFqb3IubWFwKGZ1bmN0aW9uKGQpIHtcbiAgICAgIHJldHVybiAoZCA9IGluZ2VzdChkKSwgZC5sYWJlbCA9IGZtdChkLmRhdGEpLCBkKTtcbiAgICB9KTtcbiAgICBcbiAgICByZXR1cm4gdGlja3M7XG4gIH1cblxuICBheGlzLmRlZiA9IGZ1bmN0aW9uKCkge1xuICAgIGlmKCFheGlzRGVmLnR5cGUpIGF4aXNfZGVmKHNjYWxlKTtcblxuICAgIHZhciBmbXQgPSBidWlsZFRpY2tGb3JtYXQoKTtcbiAgICB2YXIgdGlja3MgPSBidWlsZFRpY2tzKGZtdCk7XG4gICAgdmFyIHRkYXRhID0gdGl0bGUgPyBbdGl0bGVdLm1hcChpbmdlc3QpIDogW107XG5cbiAgICBheGlzRGVmLm1hcmtzWzBdLmZyb20gPSBmdW5jdGlvbigpIHsgcmV0dXJuIGdyaWQgPyB0aWNrcy5tYWpvciA6IFtdOyB9O1xuICAgIGF4aXNEZWYubWFya3NbMV0uZnJvbSA9IGZ1bmN0aW9uKCkgeyByZXR1cm4gdGlja3MubWFqb3I7IH07XG4gICAgYXhpc0RlZi5tYXJrc1syXS5mcm9tID0gZnVuY3Rpb24oKSB7IHJldHVybiB0aWNrcy5taW5vcjsgfTtcbiAgICBheGlzRGVmLm1hcmtzWzNdLmZyb20gPSBheGlzRGVmLm1hcmtzWzFdLmZyb207XG4gICAgYXhpc0RlZi5tYXJrc1s0XS5mcm9tID0gZnVuY3Rpb24oKSB7IHJldHVybiBbMV07IH07XG4gICAgYXhpc0RlZi5tYXJrc1s1XS5mcm9tID0gZnVuY3Rpb24oKSB7IHJldHVybiB0ZGF0YTsgfTtcbiAgICBheGlzRGVmLm9mZnNldCA9IG9mZnNldDtcbiAgICBheGlzRGVmLm9yaWVudCA9IG9yaWVudDtcbiAgICBheGlzRGVmLmxheWVyID0gbGF5ZXI7XG4gICAgcmV0dXJuIGF4aXNEZWY7XG4gIH07XG5cbiAgZnVuY3Rpb24gYXhpc19kZWYoc2NhbGUpIHtcbiAgICAvLyBzZXR1cCBzY2FsZSBtYXBwaW5nXG4gICAgdmFyIG5ld1NjYWxlLCBvbGRTY2FsZSwgcmFuZ2U7XG4gICAgaWYgKHNjYWxlLnR5cGUgPT09IFwib3JkaW5hbFwiKSB7XG4gICAgICBuZXdTY2FsZSA9IHtzY2FsZTogc2NhbGUuc2NhbGVOYW1lLCBvZmZzZXQ6IDAuNSArIHNjYWxlLnJhbmdlQmFuZCgpLzJ9O1xuICAgICAgb2xkU2NhbGUgPSBuZXdTY2FsZTtcbiAgICB9IGVsc2Uge1xuICAgICAgbmV3U2NhbGUgPSB7c2NhbGU6IHNjYWxlLnNjYWxlTmFtZSwgb2Zmc2V0OiAwLjV9O1xuICAgICAgb2xkU2NhbGUgPSB7c2NhbGU6IHNjYWxlLnNjYWxlTmFtZStcIjpwcmV2XCIsIG9mZnNldDogMC41fTtcbiAgICB9XG4gICAgcmFuZ2UgPSB2Z19heGlzU2NhbGVSYW5nZShzY2FsZSk7XG5cbiAgICAvLyBzZXR1cCBheGlzIG1hcmtzXG4gICAgdXRpbC5leHRlbmQobS5ncmlkTGluZXMsIHZnX2F4aXNUaWNrcyhjb25maWcpKTtcbiAgICB1dGlsLmV4dGVuZChtLm1ham9yVGlja3MsIHZnX2F4aXNUaWNrcyhjb25maWcpKTtcbiAgICB1dGlsLmV4dGVuZChtLm1pbm9yVGlja3MsIHZnX2F4aXNUaWNrcyhjb25maWcpKTtcbiAgICB1dGlsLmV4dGVuZChtLnRpY2tMYWJlbHMsIHZnX2F4aXNUaWNrTGFiZWxzKGNvbmZpZykpO1xuICAgIHV0aWwuZXh0ZW5kKG0uZG9tYWluLCB2Z19heGlzRG9tYWluKGNvbmZpZykpO1xuICAgIHV0aWwuZXh0ZW5kKG0udGl0bGUsIHZnX2F4aXNUaXRsZShjb25maWcpKTtcbiAgICBtLmdyaWRMaW5lcy5wcm9wZXJ0aWVzLmVudGVyLnN0cm9rZSA9IHt2YWx1ZTogY29uZmlnLmF4aXMuZ3JpZENvbG9yfTtcbiAgICBtLmdyaWRMaW5lcy5wcm9wZXJ0aWVzLmVudGVyLnN0cm9rZU9wYWNpdHkgPSB7dmFsdWU6IGNvbmZpZy5heGlzLmdyaWRPcGFjaXR5fTtcblxuICAgIC8vIGV4dGVuZCBheGlzIG1hcmtzIGJhc2VkIG9uIGF4aXMgb3JpZW50YXRpb25cbiAgICB2Z19heGlzVGlja3NFeHRlbmQob3JpZW50LCBtLmdyaWRMaW5lcywgb2xkU2NhbGUsIG5ld1NjYWxlLCBJbmZpbml0eSk7XG4gICAgdmdfYXhpc1RpY2tzRXh0ZW5kKG9yaWVudCwgbS5tYWpvclRpY2tzLCBvbGRTY2FsZSwgbmV3U2NhbGUsIHRpY2tNYWpvclNpemUpO1xuICAgIHZnX2F4aXNUaWNrc0V4dGVuZChvcmllbnQsIG0ubWlub3JUaWNrcywgb2xkU2NhbGUsIG5ld1NjYWxlLCB0aWNrTWlub3JTaXplKTtcbiAgICB2Z19heGlzTGFiZWxFeHRlbmQob3JpZW50LCBtLnRpY2tMYWJlbHMsIG9sZFNjYWxlLCBuZXdTY2FsZSwgdGlja01ham9yU2l6ZSwgdGlja1BhZGRpbmcpO1xuXG4gICAgdmdfYXhpc0RvbWFpbkV4dGVuZChvcmllbnQsIG0uZG9tYWluLCByYW5nZSwgdGlja0VuZFNpemUpO1xuICAgIHZnX2F4aXNUaXRsZUV4dGVuZChvcmllbnQsIG0udGl0bGUsIHJhbmdlLCB0aXRsZU9mZnNldCk7IC8vIFRPRE8gZ2V0IG9mZnNldFxuICAgIFxuICAgIC8vIGFkZCAvIG92ZXJyaWRlIGN1c3RvbSBzdHlsZSBwcm9wZXJ0aWVzXG4gICAgdXRpbC5leHRlbmQobS5ncmlkTGluZXMucHJvcGVydGllcy51cGRhdGUsIGdyaWRMaW5lU3R5bGUpO1xuICAgIHV0aWwuZXh0ZW5kKG0ubWFqb3JUaWNrcy5wcm9wZXJ0aWVzLnVwZGF0ZSwgbWFqb3JUaWNrU3R5bGUpO1xuICAgIHV0aWwuZXh0ZW5kKG0ubWlub3JUaWNrcy5wcm9wZXJ0aWVzLnVwZGF0ZSwgbWlub3JUaWNrU3R5bGUpO1xuICAgIHV0aWwuZXh0ZW5kKG0udGlja0xhYmVscy5wcm9wZXJ0aWVzLnVwZGF0ZSwgdGlja0xhYmVsU3R5bGUpO1xuICAgIHV0aWwuZXh0ZW5kKG0uZG9tYWluLnByb3BlcnRpZXMudXBkYXRlLCBkb21haW5TdHlsZSk7XG4gICAgdXRpbC5leHRlbmQobS50aXRsZS5wcm9wZXJ0aWVzLnVwZGF0ZSwgdGl0bGVTdHlsZSk7XG5cbiAgICB2YXIgbWFya3MgPSBbbS5ncmlkTGluZXMsIG0ubWFqb3JUaWNrcywgbS5taW5vclRpY2tzLCBtLnRpY2tMYWJlbHMsIG0uZG9tYWluLCBtLnRpdGxlXTtcbiAgICB1dGlsLmV4dGVuZChheGlzRGVmLCB7XG4gICAgICB0eXBlOiBcImdyb3VwXCIsXG4gICAgICBpbnRlcmFjdGl2ZTogZmFsc2UsXG4gICAgICBwcm9wZXJ0aWVzOiB7IFxuICAgICAgICBlbnRlcjoge1xuICAgICAgICAgIGVuY29kZTogdmdfYXhpc1VwZGF0ZSxcbiAgICAgICAgICBzY2FsZXM6IFtzY2FsZS5zY2FsZU5hbWVdLFxuICAgICAgICAgIHNpZ25hbHM6IFtdLCBkYXRhOiBbXVxuICAgICAgICB9LFxuICAgICAgICB1cGRhdGU6IHtcbiAgICAgICAgICBlbmNvZGU6IHZnX2F4aXNVcGRhdGUsXG4gICAgICAgICAgc2NhbGVzOiBbc2NhbGUuc2NhbGVOYW1lXSxcbiAgICAgICAgICBzaWduYWxzOiBbXSwgZGF0YTogW11cbiAgICAgICAgfVxuICAgICAgfVxuICAgIH0pO1xuXG4gICAgYXhpc0RlZi5tYXJrcyA9IG1hcmtzLm1hcChmdW5jdGlvbihtKSB7IHJldHVybiBwYXJzZU1hcmsobW9kZWwsIG0pOyB9KTtcbiAgfVxuXG4gIGF4aXMuc2NhbGUgPSBmdW5jdGlvbih4KSB7XG4gICAgaWYgKCFhcmd1bWVudHMubGVuZ3RoKSByZXR1cm4gc2NhbGU7XG4gICAgaWYgKHNjYWxlICE9PSB4KSB7IHNjYWxlID0geDsgcmVzZXQoKTsgfVxuICAgIHJldHVybiBheGlzO1xuICB9O1xuXG4gIGF4aXMub3JpZW50ID0gZnVuY3Rpb24oeCkge1xuICAgIGlmICghYXJndW1lbnRzLmxlbmd0aCkgcmV0dXJuIG9yaWVudDtcbiAgICBpZiAob3JpZW50ICE9PSB4KSB7XG4gICAgICBvcmllbnQgPSB4IGluIHZnX2F4aXNPcmllbnRzID8geCArIFwiXCIgOiBjb25maWcuYXhpcy5vcmllbnQ7XG4gICAgICByZXNldCgpO1xuICAgIH1cbiAgICByZXR1cm4gYXhpcztcbiAgfTtcblxuICBheGlzLnRpdGxlID0gZnVuY3Rpb24oeCkge1xuICAgIGlmICghYXJndW1lbnRzLmxlbmd0aCkgcmV0dXJuIHRpdGxlO1xuICAgIGlmICh0aXRsZSAhPT0geCkgeyB0aXRsZSA9IHg7IHJlc2V0KCk7IH1cbiAgICByZXR1cm4gYXhpcztcbiAgfTtcblxuICBheGlzLnRpY2tDb3VudCA9IGZ1bmN0aW9uKHgpIHtcbiAgICBpZiAoIWFyZ3VtZW50cy5sZW5ndGgpIHJldHVybiB0aWNrQ291bnQ7XG4gICAgdGlja0NvdW50ID0geDtcbiAgICByZXR1cm4gYXhpcztcbiAgfTtcblxuICBheGlzLnRpY2tWYWx1ZXMgPSBmdW5jdGlvbih4KSB7XG4gICAgaWYgKCFhcmd1bWVudHMubGVuZ3RoKSByZXR1cm4gdGlja1ZhbHVlcztcbiAgICB0aWNrVmFsdWVzID0geDtcbiAgICByZXR1cm4gYXhpcztcbiAgfTtcblxuICBheGlzLnRpY2tGb3JtYXQgPSBmdW5jdGlvbih4KSB7XG4gICAgaWYgKCFhcmd1bWVudHMubGVuZ3RoKSByZXR1cm4gdGlja0Zvcm1hdFN0cmluZztcbiAgICBpZiAodGlja0Zvcm1hdFN0cmluZyAhPT0geCkge1xuICAgICAgdGlja0Zvcm1hdFN0cmluZyA9IHg7XG4gICAgICByZXNldCgpO1xuICAgIH1cbiAgICByZXR1cm4gYXhpcztcbiAgfTtcbiAgXG4gIGF4aXMudGlja1NpemUgPSBmdW5jdGlvbih4LCB5KSB7XG4gICAgaWYgKCFhcmd1bWVudHMubGVuZ3RoKSByZXR1cm4gdGlja01ham9yU2l6ZTtcbiAgICB2YXIgbiA9IGFyZ3VtZW50cy5sZW5ndGggLSAxLFxuICAgICAgICBtYWpvciA9ICt4LFxuICAgICAgICBtaW5vciA9IG4gPiAxID8gK3kgOiB0aWNrTWFqb3JTaXplLFxuICAgICAgICBlbmQgICA9IG4gPiAwID8gK2FyZ3VtZW50c1tuXSA6IHRpY2tNYWpvclNpemU7XG5cbiAgICBpZiAodGlja01ham9yU2l6ZSAhPT0gbWFqb3IgfHxcbiAgICAgICAgdGlja01pbm9yU2l6ZSAhPT0gbWlub3IgfHxcbiAgICAgICAgdGlja0VuZFNpemUgIT09IGVuZCkge1xuICAgICAgcmVzZXQoKTtcbiAgICB9XG5cbiAgICB0aWNrTWFqb3JTaXplID0gbWFqb3I7XG4gICAgdGlja01pbm9yU2l6ZSA9IG1pbm9yO1xuICAgIHRpY2tFbmRTaXplID0gZW5kO1xuICAgIHJldHVybiBheGlzO1xuICB9O1xuXG4gIGF4aXMudGlja1N1YmRpdmlkZSA9IGZ1bmN0aW9uKHgpIHtcbiAgICBpZiAoIWFyZ3VtZW50cy5sZW5ndGgpIHJldHVybiB0aWNrU3ViZGl2aWRlO1xuICAgIHRpY2tTdWJkaXZpZGUgPSAreDtcbiAgICByZXR1cm4gYXhpcztcbiAgfTtcbiAgXG4gIGF4aXMub2Zmc2V0ID0gZnVuY3Rpb24oeCkge1xuICAgIGlmICghYXJndW1lbnRzLmxlbmd0aCkgcmV0dXJuIG9mZnNldDtcbiAgICBvZmZzZXQgPSB1dGlsLmlzT2JqZWN0KHgpID8geCA6ICt4O1xuICAgIHJldHVybiBheGlzO1xuICB9O1xuXG4gIGF4aXMudGlja1BhZGRpbmcgPSBmdW5jdGlvbih4KSB7XG4gICAgaWYgKCFhcmd1bWVudHMubGVuZ3RoKSByZXR1cm4gdGlja1BhZGRpbmc7XG4gICAgaWYgKHRpY2tQYWRkaW5nICE9PSAreCkgeyB0aWNrUGFkZGluZyA9ICt4OyByZXNldCgpOyB9XG4gICAgcmV0dXJuIGF4aXM7XG4gIH07XG5cbiAgYXhpcy50aXRsZU9mZnNldCA9IGZ1bmN0aW9uKHgpIHtcbiAgICBpZiAoIWFyZ3VtZW50cy5sZW5ndGgpIHJldHVybiB0aXRsZU9mZnNldDtcbiAgICBpZiAodGl0bGVPZmZzZXQgIT09ICt4KSB7IHRpdGxlT2Zmc2V0ID0gK3g7IHJlc2V0KCk7IH1cbiAgICByZXR1cm4gYXhpcztcbiAgfTtcblxuICBheGlzLmxheWVyID0gZnVuY3Rpb24oeCkge1xuICAgIGlmICghYXJndW1lbnRzLmxlbmd0aCkgcmV0dXJuIGxheWVyO1xuICAgIGlmIChsYXllciAhPT0geCkgeyBsYXllciA9IHg7IHJlc2V0KCk7IH1cbiAgICByZXR1cm4gYXhpcztcbiAgfTtcblxuICBheGlzLmdyaWQgPSBmdW5jdGlvbih4KSB7XG4gICAgaWYgKCFhcmd1bWVudHMubGVuZ3RoKSByZXR1cm4gZ3JpZDtcbiAgICBpZiAoZ3JpZCAhPT0geCkgeyBncmlkID0geDsgcmVzZXQoKTsgfVxuICAgIHJldHVybiBheGlzO1xuICB9O1xuXG4gIGF4aXMuZ3JpZExpbmVQcm9wZXJ0aWVzID0gZnVuY3Rpb24oeCkge1xuICAgIGlmICghYXJndW1lbnRzLmxlbmd0aCkgcmV0dXJuIGdyaWRMaW5lU3R5bGU7XG4gICAgaWYgKGdyaWRMaW5lU3R5bGUgIT09IHgpIHsgZ3JpZExpbmVTdHlsZSA9IHg7IH1cbiAgICByZXR1cm4gYXhpcztcbiAgfTtcblxuICBheGlzLm1ham9yVGlja1Byb3BlcnRpZXMgPSBmdW5jdGlvbih4KSB7XG4gICAgaWYgKCFhcmd1bWVudHMubGVuZ3RoKSByZXR1cm4gbWFqb3JUaWNrU3R5bGU7XG4gICAgaWYgKG1ham9yVGlja1N0eWxlICE9PSB4KSB7IG1ham9yVGlja1N0eWxlID0geDsgfVxuICAgIHJldHVybiBheGlzO1xuICB9O1xuXG4gIGF4aXMubWlub3JUaWNrUHJvcGVydGllcyA9IGZ1bmN0aW9uKHgpIHtcbiAgICBpZiAoIWFyZ3VtZW50cy5sZW5ndGgpIHJldHVybiBtaW5vclRpY2tTdHlsZTtcbiAgICBpZiAobWlub3JUaWNrU3R5bGUgIT09IHgpIHsgbWlub3JUaWNrU3R5bGUgPSB4OyB9XG4gICAgcmV0dXJuIGF4aXM7XG4gIH07XG5cbiAgYXhpcy50aWNrTGFiZWxQcm9wZXJ0aWVzID0gZnVuY3Rpb24oeCkge1xuICAgIGlmICghYXJndW1lbnRzLmxlbmd0aCkgcmV0dXJuIHRpY2tMYWJlbFN0eWxlO1xuICAgIGlmICh0aWNrTGFiZWxTdHlsZSAhPT0geCkgeyB0aWNrTGFiZWxTdHlsZSA9IHg7IH1cbiAgICByZXR1cm4gYXhpcztcbiAgfTtcblxuICBheGlzLnRpdGxlUHJvcGVydGllcyA9IGZ1bmN0aW9uKHgpIHtcbiAgICBpZiAoIWFyZ3VtZW50cy5sZW5ndGgpIHJldHVybiB0aXRsZVN0eWxlO1xuICAgIGlmICh0aXRsZVN0eWxlICE9PSB4KSB7IHRpdGxlU3R5bGUgPSB4OyB9XG4gICAgcmV0dXJuIGF4aXM7XG4gIH07XG5cbiAgYXhpcy5kb21haW5Qcm9wZXJ0aWVzID0gZnVuY3Rpb24oeCkge1xuICAgIGlmICghYXJndW1lbnRzLmxlbmd0aCkgcmV0dXJuIGRvbWFpblN0eWxlO1xuICAgIGlmIChkb21haW5TdHlsZSAhPT0geCkgeyBkb21haW5TdHlsZSA9IHg7IH1cbiAgICByZXR1cm4gYXhpcztcbiAgfTtcbiAgXG4gIGF4aXMucmVzZXQgPSBmdW5jdGlvbigpIHsgXG4gICAgcmVzZXQoKTsgXG4gICAgcmV0dXJuIGF4aXM7IFxuICB9O1xuXG4gIHJldHVybiBheGlzO1xufVxuXG52YXIgdmdfYXhpc09yaWVudHMgPSB7dG9wOiAxLCByaWdodDogMSwgYm90dG9tOiAxLCBsZWZ0OiAxfTtcblxuZnVuY3Rpb24gdmdfYXhpc1N1YmRpdmlkZShzY2FsZSwgdGlja3MsIG0pIHtcbiAgdmFyIHN1YnRpY2tzID0gW107XG4gIGlmIChtICYmIHRpY2tzLmxlbmd0aCA+IDEpIHtcbiAgICB2YXIgZXh0ZW50ID0gdmdfYXhpc1NjYWxlRXh0ZW50KHNjYWxlLmRvbWFpbigpKSxcbiAgICAgICAgaSA9IC0xLFxuICAgICAgICBuID0gdGlja3MubGVuZ3RoLFxuICAgICAgICBkID0gKHRpY2tzWzFdIC0gdGlja3NbMF0pIC8gKyttLFxuICAgICAgICBqLFxuICAgICAgICB2O1xuICAgIHdoaWxlICgrK2kgPCBuKSB7XG4gICAgICBmb3IgKGogPSBtOyAtLWogPiAwOykge1xuICAgICAgICBpZiAoKHYgPSArdGlja3NbaV0gLSBqICogZCkgPj0gZXh0ZW50WzBdKSB7XG4gICAgICAgICAgc3VidGlja3MucHVzaCh2KTtcbiAgICAgICAgfVxuICAgICAgfVxuICAgIH1cbiAgICBmb3IgKC0taSwgaiA9IDA7ICsraiA8IG0gJiYgKHYgPSArdGlja3NbaV0gKyBqICogZCkgPCBleHRlbnRbMV07KSB7XG4gICAgICBzdWJ0aWNrcy5wdXNoKHYpO1xuICAgIH1cbiAgfVxuICByZXR1cm4gc3VidGlja3M7XG59XG5cbmZ1bmN0aW9uIHZnX2F4aXNTY2FsZUV4dGVudChkb21haW4pIHtcbiAgdmFyIHN0YXJ0ID0gZG9tYWluWzBdLCBzdG9wID0gZG9tYWluW2RvbWFpbi5sZW5ndGggLSAxXTtcbiAgcmV0dXJuIHN0YXJ0IDwgc3RvcCA/IFtzdGFydCwgc3RvcF0gOiBbc3RvcCwgc3RhcnRdO1xufVxuXG5mdW5jdGlvbiB2Z19heGlzU2NhbGVSYW5nZShzY2FsZSkge1xuICByZXR1cm4gc2NhbGUucmFuZ2VFeHRlbnQgP1xuICAgIHNjYWxlLnJhbmdlRXh0ZW50KCkgOlxuICAgIHZnX2F4aXNTY2FsZUV4dGVudChzY2FsZS5yYW5nZSgpKTtcbn1cblxudmFyIHZnX2F4aXNBbGlnbiA9IHtcbiAgYm90dG9tOiBcImNlbnRlclwiLFxuICB0b3A6IFwiY2VudGVyXCIsXG4gIGxlZnQ6IFwicmlnaHRcIixcbiAgcmlnaHQ6IFwibGVmdFwiXG59O1xuXG52YXIgdmdfYXhpc0Jhc2VsaW5lID0ge1xuICBib3R0b206IFwidG9wXCIsXG4gIHRvcDogXCJib3R0b21cIixcbiAgbGVmdDogXCJtaWRkbGVcIixcbiAgcmlnaHQ6IFwibWlkZGxlXCJcbn07XG5cbmZ1bmN0aW9uIHZnX2F4aXNMYWJlbEV4dGVuZChvcmllbnQsIGxhYmVscywgb2xkU2NhbGUsIG5ld1NjYWxlLCBzaXplLCBwYWQpIHtcbiAgc2l6ZSA9IE1hdGgubWF4KHNpemUsIDApICsgcGFkO1xuICBpZiAob3JpZW50ID09PSBcImxlZnRcIiB8fCBvcmllbnQgPT09IFwidG9wXCIpIHtcbiAgICBzaXplICo9IC0xO1xuICB9ICBcbiAgaWYgKG9yaWVudCA9PT0gXCJ0b3BcIiB8fCBvcmllbnQgPT09IFwiYm90dG9tXCIpIHtcbiAgICB1dGlsLmV4dGVuZChsYWJlbHMucHJvcGVydGllcy5lbnRlciwge1xuICAgICAgeDogb2xkU2NhbGUsXG4gICAgICB5OiB7dmFsdWU6IHNpemV9LFxuICAgIH0pO1xuICAgIHV0aWwuZXh0ZW5kKGxhYmVscy5wcm9wZXJ0aWVzLnVwZGF0ZSwge1xuICAgICAgeDogbmV3U2NhbGUsXG4gICAgICB5OiB7dmFsdWU6IHNpemV9LFxuICAgICAgYWxpZ246IHt2YWx1ZTogXCJjZW50ZXJcIn0sXG4gICAgICBiYXNlbGluZToge3ZhbHVlOiB2Z19heGlzQmFzZWxpbmVbb3JpZW50XX1cbiAgICB9KTtcbiAgfSBlbHNlIHtcbiAgICB1dGlsLmV4dGVuZChsYWJlbHMucHJvcGVydGllcy5lbnRlciwge1xuICAgICAgeDoge3ZhbHVlOiBzaXplfSxcbiAgICAgIHk6IG9sZFNjYWxlLFxuICAgIH0pO1xuICAgIHV0aWwuZXh0ZW5kKGxhYmVscy5wcm9wZXJ0aWVzLnVwZGF0ZSwge1xuICAgICAgeDoge3ZhbHVlOiBzaXplfSxcbiAgICAgIHk6IG5ld1NjYWxlLFxuICAgICAgYWxpZ246IHt2YWx1ZTogdmdfYXhpc0FsaWduW29yaWVudF19LFxuICAgICAgYmFzZWxpbmU6IHt2YWx1ZTogXCJtaWRkbGVcIn1cbiAgICB9KTtcbiAgfVxufVxuXG5mdW5jdGlvbiB2Z19heGlzVGlja3NFeHRlbmQob3JpZW50LCB0aWNrcywgb2xkU2NhbGUsIG5ld1NjYWxlLCBzaXplKSB7XG4gIHZhciBzaWduID0gKG9yaWVudCA9PT0gXCJsZWZ0XCIgfHwgb3JpZW50ID09PSBcInRvcFwiKSA/IC0xIDogMTtcbiAgaWYgKHNpemUgPT09IEluZmluaXR5KSB7XG4gICAgc2l6ZSA9IChvcmllbnQgPT09IFwidG9wXCIgfHwgb3JpZW50ID09PSBcImJvdHRvbVwiKSA/XG4gICAgICB7ZmllbGQ6IHtncm91cDogXCJoZWlnaHRcIiwgbGV2ZWw6IDJ9LCBtdWx0OiAtc2lnbn0gOlxuICAgICAge2ZpZWxkOiB7Z3JvdXA6IFwid2lkdGhcIiwgIGxldmVsOiAyfSwgbXVsdDogLXNpZ259O1xuICB9IGVsc2Uge1xuICAgIHNpemUgPSB7dmFsdWU6IHNpZ24gKiBzaXplfTtcbiAgfVxuICBpZiAob3JpZW50ID09PSBcInRvcFwiIHx8IG9yaWVudCA9PT0gXCJib3R0b21cIikge1xuICAgIHV0aWwuZXh0ZW5kKHRpY2tzLnByb3BlcnRpZXMuZW50ZXIsIHtcbiAgICAgIHg6ICBvbGRTY2FsZSxcbiAgICAgIHk6ICB7dmFsdWU6IDB9LFxuICAgICAgeTI6IHNpemVcbiAgICB9KTtcbiAgICB1dGlsLmV4dGVuZCh0aWNrcy5wcm9wZXJ0aWVzLnVwZGF0ZSwge1xuICAgICAgeDogIG5ld1NjYWxlLFxuICAgICAgeTogIHt2YWx1ZTogMH0sXG4gICAgICB5Mjogc2l6ZVxuICAgIH0pO1xuICAgIHV0aWwuZXh0ZW5kKHRpY2tzLnByb3BlcnRpZXMuZXhpdCwge1xuICAgICAgeDogIG5ld1NjYWxlLFxuICAgIH0pOyAgICAgICAgXG4gIH0gZWxzZSB7XG4gICAgdXRpbC5leHRlbmQodGlja3MucHJvcGVydGllcy5lbnRlciwge1xuICAgICAgeDogIHt2YWx1ZTogMH0sXG4gICAgICB4Mjogc2l6ZSxcbiAgICAgIHk6ICBvbGRTY2FsZVxuICAgIH0pO1xuICAgIHV0aWwuZXh0ZW5kKHRpY2tzLnByb3BlcnRpZXMudXBkYXRlLCB7XG4gICAgICB4OiAge3ZhbHVlOiAwfSxcbiAgICAgIHgyOiBzaXplLFxuICAgICAgeTogIG5ld1NjYWxlXG4gICAgfSk7XG4gICAgdXRpbC5leHRlbmQodGlja3MucHJvcGVydGllcy5leGl0LCB7XG4gICAgICB5OiAgbmV3U2NhbGUsXG4gICAgfSk7XG4gIH1cbn1cblxuZnVuY3Rpb24gdmdfYXhpc1RpdGxlRXh0ZW5kKG9yaWVudCwgdGl0bGUsIHJhbmdlLCBvZmZzZXQpIHtcbiAgdmFyIG1pZCA9IH5+KChyYW5nZVswXSArIHJhbmdlWzFdKSAvIDIpLFxuICAgICAgc2lnbiA9IChvcmllbnQgPT09IFwidG9wXCIgfHwgb3JpZW50ID09PSBcImxlZnRcIikgPyAtMSA6IDE7XG4gIFxuICBpZiAob3JpZW50ID09PSBcImJvdHRvbVwiIHx8IG9yaWVudCA9PT0gXCJ0b3BcIikge1xuICAgIHV0aWwuZXh0ZW5kKHRpdGxlLnByb3BlcnRpZXMudXBkYXRlLCB7XG4gICAgICB4OiB7dmFsdWU6IG1pZH0sXG4gICAgICB5OiB7dmFsdWU6IHNpZ24qb2Zmc2V0fSxcbiAgICAgIGFuZ2xlOiB7dmFsdWU6IDB9XG4gICAgfSk7XG4gIH0gZWxzZSB7XG4gICAgdXRpbC5leHRlbmQodGl0bGUucHJvcGVydGllcy51cGRhdGUsIHtcbiAgICAgIHg6IHt2YWx1ZTogc2lnbipvZmZzZXR9LFxuICAgICAgeToge3ZhbHVlOiBtaWR9LFxuICAgICAgYW5nbGU6IHt2YWx1ZTogb3JpZW50ID09PSBcImxlZnRcIiA/IC05MCA6IDkwfVxuICAgIH0pO1xuICB9XG59XG5cbmZ1bmN0aW9uIHZnX2F4aXNEb21haW5FeHRlbmQob3JpZW50LCBkb21haW4sIHJhbmdlLCBzaXplKSB7XG4gIHZhciBwYXRoO1xuICBpZiAob3JpZW50ID09PSBcInRvcFwiIHx8IG9yaWVudCA9PT0gXCJsZWZ0XCIpIHtcbiAgICBzaXplID0gLTEgKiBzaXplO1xuICB9XG4gIGlmIChvcmllbnQgPT09IFwiYm90dG9tXCIgfHwgb3JpZW50ID09PSBcInRvcFwiKSB7XG4gICAgcGF0aCA9IFwiTVwiICsgcmFuZ2VbMF0gKyBcIixcIiArIHNpemUgKyBcIlYwSFwiICsgcmFuZ2VbMV0gKyBcIlZcIiArIHNpemU7XG4gIH0gZWxzZSB7XG4gICAgcGF0aCA9IFwiTVwiICsgc2l6ZSArIFwiLFwiICsgcmFuZ2VbMF0gKyBcIkgwVlwiICsgcmFuZ2VbMV0gKyBcIkhcIiArIHNpemU7XG4gIH1cbiAgZG9tYWluLnByb3BlcnRpZXMudXBkYXRlLnBhdGggPSB7dmFsdWU6IHBhdGh9O1xufVxuXG5mdW5jdGlvbiB2Z19heGlzVXBkYXRlKGl0ZW0sIGdyb3VwLCB0cmFucykge1xuICB2YXIgbyA9IHRyYW5zID8ge30gOiBpdGVtLFxuICAgICAgb2Zmc2V0ID0gaXRlbS5tYXJrLmRlZi5vZmZzZXQsXG4gICAgICBvcmllbnQgPSBpdGVtLm1hcmsuZGVmLm9yaWVudCxcbiAgICAgIHdpZHRoICA9IGdyb3VwLndpZHRoLFxuICAgICAgaGVpZ2h0ID0gZ3JvdXAuaGVpZ2h0OyAvLyBUT0RPIGZhbGxiYWNrIHRvIGdsb2JhbCB3LGg/XG5cbiAgaWYgKHV0aWwuaXNBcnJheShvZmZzZXQpKSB7XG4gICAgdmFyIG9meCA9IG9mZnNldFswXSxcbiAgICAgICAgb2Z5ID0gb2Zmc2V0WzFdO1xuXG4gICAgc3dpdGNoIChvcmllbnQpIHtcbiAgICAgIGNhc2UgXCJsZWZ0XCI6ICAgeyB0cGwuc2V0KG8sICd4JywgLW9meCk7IHRwbC5zZXQobywgJ3knLCBvZnkpOyBicmVhazsgfVxuICAgICAgY2FzZSBcInJpZ2h0XCI6ICB7IHRwbC5zZXQobywgJ3gnLCB3aWR0aCArIG9meCk7IHRwbC5zZXQobywgJ3knLCBvZnkpOyBicmVhazsgfVxuICAgICAgY2FzZSBcImJvdHRvbVwiOiB7IHRwbC5zZXQobywgJ3gnLCBvZngpOyB0cGwuc2V0KG8sICd5JywgaGVpZ2h0ICsgb2Z5KTsgYnJlYWs7IH1cbiAgICAgIGNhc2UgXCJ0b3BcIjogICAgeyB0cGwuc2V0KG8sICd4Jywgb2Z4KTsgdHBsLnNldChvLCAneScsIC1vZnkpOyBicmVhazsgfVxuICAgICAgZGVmYXVsdDogICAgICAgeyB0cGwuc2V0KG8sICd4Jywgb2Z4KTsgdHBsLnNldChvLCAneScsIG9meSk7IH1cbiAgICB9XG4gIH0gZWxzZSB7XG4gICAgaWYgKHV0aWwuaXNPYmplY3Qob2Zmc2V0KSkge1xuICAgICAgb2Zmc2V0ID0gLWdyb3VwLnNjYWxlKG9mZnNldC5zY2FsZSkob2Zmc2V0LnZhbHVlKTtcbiAgICB9XG5cbiAgICBzd2l0Y2ggKG9yaWVudCkge1xuICAgICAgY2FzZSBcImxlZnRcIjogICB7IHRwbC5zZXQobywgJ3gnLCAtb2Zmc2V0KTsgdHBsLnNldChvLCAneScsIDApOyBicmVhazsgfVxuICAgICAgY2FzZSBcInJpZ2h0XCI6ICB7IHRwbC5zZXQobywgJ3gnLCB3aWR0aCArIG9mZnNldCk7IHRwbC5zZXQobywgJ3knLCAwKTsgYnJlYWs7IH1cbiAgICAgIGNhc2UgXCJib3R0b21cIjogeyB0cGwuc2V0KG8sICd4JywgMCk7IHRwbC5zZXQobywgJ3knLCBoZWlnaHQgKyBvZmZzZXQpOyBicmVhazsgfVxuICAgICAgY2FzZSBcInRvcFwiOiAgICB7IHRwbC5zZXQobywgJ3gnLCAwKTsgdHBsLnNldChvLCAneScsIC1vZmZzZXQpOyBicmVhazsgfVxuICAgICAgZGVmYXVsdDogICAgICAgeyB0cGwuc2V0KG8sICd4JywgMCk7IHRwbC5zZXQobywgJ3knLCAwKTsgfVxuICAgIH1cbiAgfVxuXG4gIGlmICh0cmFucykgdHJhbnMuaW50ZXJwb2xhdGUoaXRlbSwgbyk7XG4gIHJldHVybiB0cnVlO1xufVxuXG5mdW5jdGlvbiB2Z19heGlzVGlja3MoY29uZmlnKSB7XG4gIHJldHVybiB7XG4gICAgdHlwZTogXCJydWxlXCIsXG4gICAgaW50ZXJhY3RpdmU6IGZhbHNlLFxuICAgIGtleTogXCJkYXRhXCIsXG4gICAgcHJvcGVydGllczoge1xuICAgICAgZW50ZXI6IHtcbiAgICAgICAgc3Ryb2tlOiB7dmFsdWU6IGNvbmZpZy5heGlzLnRpY2tDb2xvcn0sXG4gICAgICAgIHN0cm9rZVdpZHRoOiB7dmFsdWU6IGNvbmZpZy5heGlzLnRpY2tXaWR0aH0sXG4gICAgICAgIG9wYWNpdHk6IHt2YWx1ZTogMWUtNn1cbiAgICAgIH0sXG4gICAgICBleGl0OiB7IG9wYWNpdHk6IHt2YWx1ZTogMWUtNn0gfSxcbiAgICAgIHVwZGF0ZTogeyBvcGFjaXR5OiB7dmFsdWU6IDF9IH1cbiAgICB9XG4gIH07XG59XG5cbmZ1bmN0aW9uIHZnX2F4aXNUaWNrTGFiZWxzKGNvbmZpZykge1xuICByZXR1cm4ge1xuICAgIHR5cGU6IFwidGV4dFwiLFxuICAgIGludGVyYWN0aXZlOiB0cnVlLFxuICAgIGtleTogXCJkYXRhXCIsXG4gICAgcHJvcGVydGllczoge1xuICAgICAgZW50ZXI6IHtcbiAgICAgICAgZmlsbDoge3ZhbHVlOiBjb25maWcuYXhpcy50aWNrTGFiZWxDb2xvcn0sXG4gICAgICAgIGZvbnQ6IHt2YWx1ZTogY29uZmlnLmF4aXMudGlja0xhYmVsRm9udH0sXG4gICAgICAgIGZvbnRTaXplOiB7dmFsdWU6IGNvbmZpZy5heGlzLnRpY2tMYWJlbEZvbnRTaXplfSxcbiAgICAgICAgb3BhY2l0eToge3ZhbHVlOiAxZS02fSxcbiAgICAgICAgdGV4dDoge2ZpZWxkOiBcImxhYmVsXCJ9XG4gICAgICB9LFxuICAgICAgZXhpdDogeyBvcGFjaXR5OiB7dmFsdWU6IDFlLTZ9IH0sXG4gICAgICB1cGRhdGU6IHsgb3BhY2l0eToge3ZhbHVlOiAxfSB9XG4gICAgfVxuICB9O1xufVxuXG5mdW5jdGlvbiB2Z19heGlzVGl0bGUoY29uZmlnKSB7XG4gIHJldHVybiB7XG4gICAgdHlwZTogXCJ0ZXh0XCIsXG4gICAgaW50ZXJhY3RpdmU6IHRydWUsXG4gICAgcHJvcGVydGllczoge1xuICAgICAgZW50ZXI6IHtcbiAgICAgICAgZm9udDoge3ZhbHVlOiBjb25maWcuYXhpcy50aXRsZUZvbnR9LFxuICAgICAgICBmb250U2l6ZToge3ZhbHVlOiBjb25maWcuYXhpcy50aXRsZUZvbnRTaXplfSxcbiAgICAgICAgZm9udFdlaWdodDoge3ZhbHVlOiBjb25maWcuYXhpcy50aXRsZUZvbnRXZWlnaHR9LFxuICAgICAgICBmaWxsOiB7dmFsdWU6IGNvbmZpZy5heGlzLnRpdGxlQ29sb3J9LFxuICAgICAgICBhbGlnbjoge3ZhbHVlOiBcImNlbnRlclwifSxcbiAgICAgICAgYmFzZWxpbmU6IHt2YWx1ZTogXCJtaWRkbGVcIn0sXG4gICAgICAgIHRleHQ6IHtmaWVsZDogXCJkYXRhXCJ9XG4gICAgICB9LFxuICAgICAgdXBkYXRlOiB7fVxuICAgIH1cbiAgfTtcbn1cblxuZnVuY3Rpb24gdmdfYXhpc0RvbWFpbihjb25maWcpIHtcbiAgcmV0dXJuIHtcbiAgICB0eXBlOiBcInBhdGhcIixcbiAgICBpbnRlcmFjdGl2ZTogZmFsc2UsXG4gICAgcHJvcGVydGllczoge1xuICAgICAgZW50ZXI6IHtcbiAgICAgICAgeDoge3ZhbHVlOiAwLjV9LFxuICAgICAgICB5OiB7dmFsdWU6IDAuNX0sXG4gICAgICAgIHN0cm9rZToge3ZhbHVlOiBjb25maWcuYXhpcy5heGlzQ29sb3J9LFxuICAgICAgICBzdHJva2VXaWR0aDoge3ZhbHVlOiBjb25maWcuYXhpcy5heGlzV2lkdGh9XG4gICAgICB9LFxuICAgICAgdXBkYXRlOiB7fVxuICAgIH1cbiAgfTtcbn1cblxubW9kdWxlLmV4cG9ydHMgPSBheHM7Il19
},{"../parse/mark":91,"datalib/src/util":20,"vega-dataflow/src/Tuple":34}],108:[function(require,module,exports){
(function (global){
var d3 = (typeof window !== "undefined" ? window.d3 : typeof global !== "undefined" ? global.d3 : null),
util = require('datalib/src/util'),
Gradient = require('vega-scenegraph/src/util/Gradient'),
parseProperties = require('../parse/properties'),
parseMark = require('../parse/mark');
function lgnd(model) {
var size = null,
shape = null,
fill = null,
stroke = null,
spacing = null,
values = null,
format = null,
formatString = null,
config = model.config(),
title,
orient = "right",
offset = config.legend.offset,
padding = config.legend.padding,
tickArguments = [5],
legendStyle = {},
symbolStyle = {},
gradientStyle = {},
titleStyle = {},
labelStyle = {},
m = { // Legend marks as references for updates
titles: {},
symbols: {},
labels: {},
gradient: {}
};
var legend = {},
legendDef = {};
function reset() { legendDef.type = null; }
function ingest(d, i) { return {data: d, index: i}; }
legend.def = function() {
var scale = size || shape || fill || stroke;
format = !formatString ? null : ((scale.type === 'time') ?
d3.time.format(formatString) : d3.format(formatString));
if (!legendDef.type) {
legendDef = (scale===fill || scale===stroke) && !discrete(scale.type) ?
quantDef(scale) : ordinalDef(scale);
}
legendDef.orient = orient;
legendDef.offset = offset;
legendDef.padding = padding;
return legendDef;
};
function discrete(type) {
return type==="ordinal" || type==="quantize" ||
type==="quantile" || type==="threshold";
}
function ordinalDef(scale) {
var def = o_legend_def(size, shape, fill, stroke);
// generate data
var data = (values == null ?
(scale.ticks ? scale.ticks.apply(scale, tickArguments) : scale.domain()) :
values).map(ingest);
var fmt = format==null ? (scale.tickFormat ? scale.tickFormat.apply(scale, tickArguments) : String) : format;
// determine spacing between legend entries
var fs, range, offset, pad=5, domain = d3.range(data.length);
if (size) {
range = data.map(function(x) { return Math.sqrt(size(x.data)); });
offset = d3.max(range);
range = range.reduce(function(a,b,i,z) {
if (i > 0) a[i] = a[i-1] + z[i-1]/2 + pad;
return (a[i] += b/2, a); }, [0]).map(Math.round);
} else {
offset = Math.round(Math.sqrt(config.legend.symbolSize));
range = spacing ||
(fs = labelStyle.fontSize) && (fs.value + pad) ||
(config.legend.labelFontSize + pad);
range = domain.map(function(d,i) {
return Math.round(offset/2 + i*range);
});
}
// account for padding and title size
var sz = padding, ts;
if (title) {
ts = titleStyle.fontSize;
sz += 5 + ((ts && ts.value) || config.legend.titleFontSize);
}
for (var i=0, n=range.length; i<n; ++i) range[i] += sz;
// build scale for label layout
var scaleSpec = {
name: "legend",
type: "ordinal",
points: true,
domain: domain,
range: range
};
// update legend def
var tdata = (title ? [title] : []).map(ingest);
data.forEach(function(d) {
d.label = fmt(d.data);
d.offset = offset;
});
def.scales = [ scaleSpec ];
def.marks[0].from = function() { return tdata; };
def.marks[1].from = function() { return data; };
def.marks[2].from = def.marks[1].from;
return def;
}
function o_legend_def(size, shape, fill, stroke) {
// setup legend marks
var titles = util.extend(m.titles, vg_legendTitle(config)),
symbols = util.extend(m.symbols, vg_legendSymbols(config)),
labels = util.extend(m.labels, vg_vLegendLabels(config));
// extend legend marks
vg_legendSymbolExtend(symbols, size, shape, fill, stroke);
// add / override custom style properties
util.extend(titles.properties.update, titleStyle);
util.extend(symbols.properties.update, symbolStyle);
util.extend(labels.properties.update, labelStyle);
// padding from legend border
titles.properties.enter.x.value += padding;
titles.properties.enter.y.value += padding;
labels.properties.enter.x.offset += padding + 1;
symbols.properties.enter.x.offset = padding + 1;
labels.properties.update.x.offset += padding + 1;
symbols.properties.update.x.offset = padding + 1;
util.extend(legendDef, {
type: "group",
interactive: false,
properties: {
enter: parseProperties(model, "group", legendStyle),
vg_legendPosition: {
encode: vg_legendPosition,
signals: [], scales:[], data: [], fields: []
}
}
});
legendDef.marks = [titles, symbols, labels].map(function(m) { return parseMark(model, m); });
return legendDef;
}
function quantDef(scale) {
var def = q_legend_def(scale),
dom = scale.domain(),
data = (values == null ?
(scale.ticks ? scale.ticks.apply(scale, tickArguments) : scale.domain()) :
values).map(ingest),
width = (gradientStyle.width && gradientStyle.width.value) || config.legend.gradientWidth,
fmt = format==null ? (scale.tickFormat ? scale.tickFormat.apply(scale, tickArguments) : String) : format;
// build scale for label layout
var layoutSpec = {
name: "legend",
type: scale.type,
round: true,
zero: false,
domain: [dom[0], dom[dom.length-1]],
range: [padding, width+padding]
};
if (scale.type==="pow") layoutSpec.exponent = scale.exponent();
// update legend def
var tdata = (title ? [title] : []).map(ingest);
data.forEach(function(d,i) {
d.label = fmt(d.data);
d.align = i==(data.length-1) ? "right" : i===0 ? "left" : "center";
});
def.scales = [ layoutSpec ];
def.marks[0].from = function() { return tdata; };
def.marks[1].from = function() { return [1]; };
def.marks[2].from = function() { return data; };
return def;
}
function q_legend_def(scale) {
// setup legend marks
var titles = util.extend(m.titles, vg_legendTitle(config)),
gradient = util.extend(m.gradient, vg_legendGradient(config)),
labels = util.extend(m.labels, vg_hLegendLabels(config)),
grad = new Gradient();
// setup color gradient
var dom = scale.domain(),
min = dom[0],
max = dom[dom.length-1],
f = scale.copy().domain([min, max]).range([0,1]);
var stops = (scale.type !== "linear" && scale.ticks) ?
scale.ticks.call(scale, 15) : dom;
if (min !== stops[0]) stops.unshift(min);
if (max !== stops[stops.length-1]) stops.push(max);
for (var i=0, n=stops.length; i<n; ++i) {
grad.stop(f(stops[i]), scale(stops[i]));
}
gradient.properties.enter.fill = {value: grad};
// add / override custom style properties
util.extend(titles.properties.update, titleStyle);
util.extend(gradient.properties.update, gradientStyle);
util.extend(labels.properties.update, labelStyle);
// account for gradient size
var gp = gradient.properties, gh = gradientStyle.height,
hh = (gh && gh.value) || gp.enter.height.value;
labels.properties.enter.y.value = hh;
labels.properties.update.y.value = hh;
// account for title size as needed
if (title) {
var tp = titles.properties, fs = titleStyle.fontSize,
sz = 4 + ((fs && fs.value) || tp.enter.fontSize.value);
gradient.properties.enter.y.value += sz;
labels.properties.enter.y.value += sz;
gradient.properties.update.y.value += sz;
labels.properties.update.y.value += sz;
}
// padding from legend border
titles.properties.enter.x.value += padding;
titles.properties.enter.y.value += padding;
gradient.properties.enter.x.value += padding;
gradient.properties.enter.y.value += padding;
labels.properties.enter.y.value += padding;
gradient.properties.update.x.value += padding;
gradient.properties.update.y.value += padding;
labels.properties.update.y.value += padding;
util.extend(legendDef, {
type: "group",
interactive: false,
properties: {
enter: parseProperties(model, "group", legendStyle),
vg_legendPosition: {
encode: vg_legendPosition,
signals: [], scales: [], data: [], fields: []
}
}
});
legendDef.marks = [titles, gradient, labels].map(function(m) { return parseMark(model, m); });
return legendDef;
}
legend.size = function(x) {
if (!arguments.length) return size;
if (size !== x) { size = x; reset(); }
return legend;
};
legend.shape = function(x) {
if (!arguments.length) return shape;
if (shape !== x) { shape = x; reset(); }
return legend;
};
legend.fill = function(x) {
if (!arguments.length) return fill;
if (fill !== x) { fill = x; reset(); }
return legend;
};
legend.stroke = function(x) {
if (!arguments.length) return stroke;
if (stroke !== x) { stroke = x; reset(); }
return legend;
};
legend.title = function(x) {
if (!arguments.length) return title;
if (title !== x) { title = x; reset(); }
return legend;
};
legend.format = function(x) {
if (!arguments.length) return formatString;
if (formatString !== x) {
formatString = x;
reset();
}
return legend;
};
legend.spacing = function(x) {
if (!arguments.length) return spacing;
if (spacing !== +x) { spacing = +x; reset(); }
return legend;
};
legend.orient = function(x) {
if (!arguments.length) return orient;
orient = x in vg_legendOrients ? x + "" : config.legend.orient;
return legend;
};
legend.offset = function(x) {
if (!arguments.length) return offset;
offset = +x;
return legend;
};
legend.values = function(x) {
if (!arguments.length) return values;
values = x;
return legend;
};
legend.legendProperties = function(x) {
if (!arguments.length) return legendStyle;
legendStyle = x;
return legend;
};
legend.symbolProperties = function(x) {
if (!arguments.length) return symbolStyle;
symbolStyle = x;
return legend;
};
legend.gradientProperties = function(x) {
if (!arguments.length) return gradientStyle;
gradientStyle = x;
return legend;
};
legend.labelProperties = function(x) {
if (!arguments.length) return labelStyle;
labelStyle = x;
return legend;
};
legend.titleProperties = function(x) {
if (!arguments.length) return titleStyle;
titleStyle = x;
return legend;
};
legend.reset = function() {
reset();
return legend;
};
return legend;
}
var vg_legendOrients = {right: 1, left: 1};
function vg_legendPosition(item, group, trans, db, signals, predicates) {
var o = trans ? {} : item, gx,
offset = item.mark.def.offset,
orient = item.mark.def.orient,
pad = item.mark.def.padding * 2,
lw = ~~item.bounds.width() + (item.width ? 0 : pad),
lh = ~~item.bounds.height() + (item.height ? 0 : pad),
pos = group._legendPositions ||
(group._legendPositions = {right: 0.5, left: 0.5});
o.x = 0.5;
o.width = lw;
o.y = pos[orient];
pos[orient] += (o.height = lh);
// HACK: use to estimate group bounds during animated transition
if (!trans && group.bounds) {
group.bounds.delta = group.bounds.x2 - group.width;
}
switch (orient) {
case "left": {
gx = group.bounds ? group.bounds.x1 : 0;
o.x += gx - offset - lw;
break;
}
case "right": {
gx = group.width + (group.bounds && trans ? group.bounds.delta : 0);
o.x += gx + offset;
break;
}
}
if (trans) trans.interpolate(item, o);
var enc = item.mark.def.properties.enter.encode;
enc.call(enc, item, group, trans, db, signals, predicates);
return true;
}
function vg_legendSymbolExtend(mark, size, shape, fill, stroke) {
var e = mark.properties.enter,
u = mark.properties.update;
if (size) e.size = u.size = {scale: size.scaleName, field: "data"};
if (shape) e.shape = u.shape = {scale: shape.scaleName, field: "data"};
if (fill) e.fill = u.fill = {scale: fill.scaleName, field: "data"};
if (stroke) e.stroke = u.stroke = {scale: stroke.scaleName, field: "data"};
}
function vg_legendTitle(config) {
var cfg = config.legend;
return {
type: "text",
interactive: false,
key: "data",
properties: {
enter: {
x: {value: 0},
y: {value: 0},
fill: {value: cfg.titleColor},
font: {value: cfg.titleFont},
fontSize: {value: cfg.titleFontSize},
fontWeight: {value: cfg.titleFontWeight},
baseline: {value: "top"},
text: {field: "data"},
opacity: {value: 1e-6}
},
exit: { opacity: {value: 1e-6} },
update: { opacity: {value: 1} }
}
};
}
function vg_legendSymbols(config) {
var cfg = config.legend;
return {
type: "symbol",
interactive: false,
key: "data",
properties: {
enter: {
x: {field: "offset", mult: 0.5},
y: {scale: "legend", field: "index"},
shape: {value: cfg.symbolShape},
size: {value: cfg.symbolSize},
stroke: {value: cfg.symbolColor},
strokeWidth: {value: cfg.symbolStrokeWidth},
opacity: {value: 1e-6}
},
exit: { opacity: {value: 1e-6} },
update: {
x: {field: "offset", mult: 0.5},
y: {scale: "legend", field: "index"},
opacity: {value: 1}
}
}
};
}
function vg_vLegendLabels(config) {
var cfg = config.legend;
return {
type: "text",
interactive: false,
key: "data",
properties: {
enter: {
x: {field: "offset", offset: 5},
y: {scale: "legend", field: "index"},
fill: {value: cfg.labelColor},
font: {value: cfg.labelFont},
fontSize: {value: cfg.labelFontSize},
align: {value: cfg.labelAlign},
baseline: {value: cfg.labelBaseline},
text: {field: "label"},
opacity: {value: 1e-6}
},
exit: { opacity: {value: 1e-6} },
update: {
opacity: {value: 1},
x: {field: "offset", offset: 5},
y: {scale: "legend", field: "index"},
}
}
};
}
function vg_legendGradient(config) {
var cfg = config.legend;
return {
type: "rect",
interactive: false,
properties: {
enter: {
x: {value: 0},
y: {value: 0},
width: {value: cfg.gradientWidth},
height: {value: cfg.gradientHeight},
stroke: {value: cfg.gradientStrokeColor},
strokeWidth: {value: cfg.gradientStrokeWidth},
opacity: {value: 1e-6}
},
exit: { opacity: {value: 1e-6} },
update: {
x: {value: 0},
y: {value: 0},
opacity: {value: 1}
}
}
};
}
function vg_hLegendLabels(config) {
var cfg = config.legend;
return {
type: "text",
interactive: false,
key: "data",
properties: {
enter: {
x: {scale: "legend", field: "data"},
y: {value: 20},
dy: {value: 2},
fill: {value: cfg.labelColor},
font: {value: cfg.labelFont},
fontSize: {value: cfg.labelFontSize},
align: {field: "align"},
baseline: {value: "top"},
text: {field: "label"},
opacity: {value: 1e-6}
},
exit: { opacity: {value: 1e-6} },
update: {
x: {scale: "legend", field: "data"},
y: {value: 20},
opacity: {value: 1}
}
}
};
}
module.exports = lgnd;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNyYy9zY2VuZS9sZWdlbmQuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSIsImZpbGUiOiJnZW5lcmF0ZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlc0NvbnRlbnQiOlsidmFyIGQzID0gKHR5cGVvZiB3aW5kb3cgIT09IFwidW5kZWZpbmVkXCIgPyB3aW5kb3cuZDMgOiB0eXBlb2YgZ2xvYmFsICE9PSBcInVuZGVmaW5lZFwiID8gZ2xvYmFsLmQzIDogbnVsbCksXG4gICAgdXRpbCA9IHJlcXVpcmUoJ2RhdGFsaWIvc3JjL3V0aWwnKSxcbiAgICBHcmFkaWVudCA9IHJlcXVpcmUoJ3ZlZ2Etc2NlbmVncmFwaC9zcmMvdXRpbC9HcmFkaWVudCcpLFxuICAgIHBhcnNlUHJvcGVydGllcyA9IHJlcXVpcmUoJy4uL3BhcnNlL3Byb3BlcnRpZXMnKSxcbiAgICBwYXJzZU1hcmsgPSByZXF1aXJlKCcuLi9wYXJzZS9tYXJrJyk7XG5cbmZ1bmN0aW9uIGxnbmQobW9kZWwpIHtcbiAgdmFyIHNpemUgPSBudWxsLFxuICAgICAgc2hhcGUgPSBudWxsLFxuICAgICAgZmlsbCA9IG51bGwsXG4gICAgICBzdHJva2UgPSBudWxsLFxuICAgICAgc3BhY2luZyA9IG51bGwsXG4gICAgICB2YWx1ZXMgPSBudWxsLFxuICAgICAgZm9ybWF0ID0gbnVsbCxcbiAgICAgIGZvcm1hdFN0cmluZyA9IG51bGwsXG4gICAgICBjb25maWcgPSBtb2RlbC5jb25maWcoKSxcbiAgICAgIHRpdGxlLFxuICAgICAgb3JpZW50ID0gXCJyaWdodFwiLFxuICAgICAgb2Zmc2V0ID0gY29uZmlnLmxlZ2VuZC5vZmZzZXQsXG4gICAgICBwYWRkaW5nID0gY29uZmlnLmxlZ2VuZC5wYWRkaW5nLFxuICAgICAgdGlja0FyZ3VtZW50cyA9IFs1XSxcbiAgICAgIGxlZ2VuZFN0eWxlID0ge30sXG4gICAgICBzeW1ib2xTdHlsZSA9IHt9LFxuICAgICAgZ3JhZGllbnRTdHlsZSA9IHt9LFxuICAgICAgdGl0bGVTdHlsZSA9IHt9LFxuICAgICAgbGFiZWxTdHlsZSA9IHt9LFxuICAgICAgbSA9IHsgLy8gTGVnZW5kIG1hcmtzIGFzIHJlZmVyZW5jZXMgZm9yIHVwZGF0ZXNcbiAgICAgICAgdGl0bGVzOiAge30sXG4gICAgICAgIHN5bWJvbHM6IHt9LFxuICAgICAgICBsYWJlbHM6ICB7fSxcbiAgICAgICAgZ3JhZGllbnQ6IHt9XG4gICAgICB9O1xuXG4gIHZhciBsZWdlbmQgPSB7fSxcbiAgICAgIGxlZ2VuZERlZiA9IHt9O1xuXG4gIGZ1bmN0aW9uIHJlc2V0KCkgeyBsZWdlbmREZWYudHlwZSA9IG51bGw7IH1cbiAgZnVuY3Rpb24gaW5nZXN0KGQsIGkpIHsgcmV0dXJuIHtkYXRhOiBkLCBpbmRleDogaX07IH1cblxuICBsZWdlbmQuZGVmID0gZnVuY3Rpb24oKSB7XG4gICAgdmFyIHNjYWxlID0gc2l6ZSB8fCBzaGFwZSB8fCBmaWxsIHx8IHN0cm9rZTtcbiAgICBcbiAgICBmb3JtYXQgPSAhZm9ybWF0U3RyaW5nID8gbnVsbCA6ICgoc2NhbGUudHlwZSA9PT0gJ3RpbWUnKSA/XG4gICAgICBkMy50aW1lLmZvcm1hdChmb3JtYXRTdHJpbmcpIDogZDMuZm9ybWF0KGZvcm1hdFN0cmluZykpO1xuICAgIFxuICAgIGlmICghbGVnZW5kRGVmLnR5cGUpIHtcbiAgICAgIGxlZ2VuZERlZiA9IChzY2FsZT09PWZpbGwgfHwgc2NhbGU9PT1zdHJva2UpICYmICFkaXNjcmV0ZShzY2FsZS50eXBlKSA/XG4gICAgICAgIHF1YW50RGVmKHNjYWxlKSA6IG9yZGluYWxEZWYoc2NhbGUpOyAgICAgIFxuICAgIH1cbiAgICBsZWdlbmREZWYub3JpZW50ID0gb3JpZW50O1xuICAgIGxlZ2VuZERlZi5vZmZzZXQgPSBvZmZzZXQ7XG4gICAgbGVnZW5kRGVmLnBhZGRpbmcgPSBwYWRkaW5nO1xuICAgIHJldHVybiBsZWdlbmREZWY7XG4gIH07XG5cbiAgZnVuY3Rpb24gZGlzY3JldGUodHlwZSkge1xuICAgIHJldHVybiB0eXBlPT09XCJvcmRpbmFsXCIgfHwgdHlwZT09PVwicXVhbnRpemVcIiB8fFxuICAgICAgICAgICB0eXBlPT09XCJxdWFudGlsZVwiIHx8IHR5cGU9PT1cInRocmVzaG9sZFwiO1xuICB9XG5cbiAgZnVuY3Rpb24gb3JkaW5hbERlZihzY2FsZSkge1xuICAgIHZhciBkZWYgPSBvX2xlZ2VuZF9kZWYoc2l6ZSwgc2hhcGUsIGZpbGwsIHN0cm9rZSk7XG5cbiAgICAvLyBnZW5lcmF0ZSBkYXRhXG4gICAgdmFyIGRhdGEgPSAodmFsdWVzID09IG51bGwgP1xuICAgICAgKHNjYWxlLnRpY2tzID8gc2NhbGUudGlja3MuYXBwbHkoc2NhbGUsIHRpY2tBcmd1bWVudHMpIDogc2NhbGUuZG9tYWluKCkpIDpcbiAgICAgIHZhbHVlcykubWFwKGluZ2VzdCk7XG4gICAgdmFyIGZtdCA9IGZvcm1hdD09bnVsbCA/IChzY2FsZS50aWNrRm9ybWF0ID8gc2NhbGUudGlja0Zvcm1hdC5hcHBseShzY2FsZSwgdGlja0FyZ3VtZW50cykgOiBTdHJpbmcpIDogZm9ybWF0O1xuICAgIFxuICAgIC8vIGRldGVybWluZSBzcGFjaW5nIGJldHdlZW4gbGVnZW5kIGVudHJpZXNcbiAgICB2YXIgZnMsIHJhbmdlLCBvZmZzZXQsIHBhZD01LCBkb21haW4gPSBkMy5yYW5nZShkYXRhLmxlbmd0aCk7XG4gICAgaWYgKHNpemUpIHtcbiAgICAgIHJhbmdlID0gZGF0YS5tYXAoZnVuY3Rpb24oeCkgeyByZXR1cm4gTWF0aC5zcXJ0KHNpemUoeC5kYXRhKSk7IH0pO1xuICAgICAgb2Zmc2V0ID0gZDMubWF4KHJhbmdlKTtcbiAgICAgIHJhbmdlID0gcmFuZ2UucmVkdWNlKGZ1bmN0aW9uKGEsYixpLHopIHtcbiAgICAgICAgICBpZiAoaSA+IDApIGFbaV0gPSBhW2ktMV0gKyB6W2ktMV0vMiArIHBhZDtcbiAgICAgICAgICByZXR1cm4gKGFbaV0gKz0gYi8yLCBhKTsgfSwgWzBdKS5tYXAoTWF0aC5yb3VuZCk7XG4gICAgfSBlbHNlIHtcbiAgICAgIG9mZnNldCA9IE1hdGgucm91bmQoTWF0aC5zcXJ0KGNvbmZpZy5sZWdlbmQuc3ltYm9sU2l6ZSkpO1xuICAgICAgcmFuZ2UgPSBzcGFjaW5nIHx8XG4gICAgICAgIChmcyA9IGxhYmVsU3R5bGUuZm9udFNpemUpICYmIChmcy52YWx1ZSArIHBhZCkgfHxcbiAgICAgICAgKGNvbmZpZy5sZWdlbmQubGFiZWxGb250U2l6ZSArIHBhZCk7XG4gICAgICByYW5nZSA9IGRvbWFpbi5tYXAoZnVuY3Rpb24oZCxpKSB7XG4gICAgICAgIHJldHVybiBNYXRoLnJvdW5kKG9mZnNldC8yICsgaSpyYW5nZSk7XG4gICAgICB9KTtcbiAgICB9XG5cbiAgICAvLyBhY2NvdW50IGZvciBwYWRkaW5nIGFuZCB0aXRsZSBzaXplXG4gICAgdmFyIHN6ID0gcGFkZGluZywgdHM7XG4gICAgaWYgKHRpdGxlKSB7XG4gICAgICB0cyA9IHRpdGxlU3R5bGUuZm9udFNpemU7XG4gICAgICBzeiArPSA1ICsgKCh0cyAmJiB0cy52YWx1ZSkgfHwgY29uZmlnLmxlZ2VuZC50aXRsZUZvbnRTaXplKTtcbiAgICB9XG4gICAgZm9yICh2YXIgaT0wLCBuPXJhbmdlLmxlbmd0aDsgaTxuOyArK2kpIHJhbmdlW2ldICs9IHN6O1xuICAgIFxuICAgIC8vIGJ1aWxkIHNjYWxlIGZvciBsYWJlbCBsYXlvdXRcbiAgICB2YXIgc2NhbGVTcGVjID0ge1xuICAgICAgbmFtZTogXCJsZWdlbmRcIixcbiAgICAgIHR5cGU6IFwib3JkaW5hbFwiLFxuICAgICAgcG9pbnRzOiB0cnVlLFxuICAgICAgZG9tYWluOiBkb21haW4sXG4gICAgICByYW5nZTogcmFuZ2VcbiAgICB9O1xuICAgIFxuICAgIC8vIHVwZGF0ZSBsZWdlbmQgZGVmXG4gICAgdmFyIHRkYXRhID0gKHRpdGxlID8gW3RpdGxlXSA6IFtdKS5tYXAoaW5nZXN0KTtcbiAgICBkYXRhLmZvckVhY2goZnVuY3Rpb24oZCkge1xuICAgICAgZC5sYWJlbCA9IGZtdChkLmRhdGEpO1xuICAgICAgZC5vZmZzZXQgPSBvZmZzZXQ7XG4gICAgfSk7XG4gICAgZGVmLnNjYWxlcyA9IFsgc2NhbGVTcGVjIF07XG4gICAgZGVmLm1hcmtzWzBdLmZyb20gPSBmdW5jdGlvbigpIHsgcmV0dXJuIHRkYXRhOyB9O1xuICAgIGRlZi5tYXJrc1sxXS5mcm9tID0gZnVuY3Rpb24oKSB7IHJldHVybiBkYXRhOyB9O1xuICAgIGRlZi5tYXJrc1syXS5mcm9tID0gZGVmLm1hcmtzWzFdLmZyb207XG5cbiAgICByZXR1cm4gZGVmO1xuICB9XG5cbiAgZnVuY3Rpb24gb19sZWdlbmRfZGVmKHNpemUsIHNoYXBlLCBmaWxsLCBzdHJva2UpIHtcbiAgICAvLyBzZXR1cCBsZWdlbmQgbWFya3NcbiAgICB2YXIgdGl0bGVzICA9IHV0aWwuZXh0ZW5kKG0udGl0bGVzLCB2Z19sZWdlbmRUaXRsZShjb25maWcpKSxcbiAgICAgICAgc3ltYm9scyA9IHV0aWwuZXh0ZW5kKG0uc3ltYm9scywgdmdfbGVnZW5kU3ltYm9scyhjb25maWcpKSxcbiAgICAgICAgbGFiZWxzICA9IHV0aWwuZXh0ZW5kKG0ubGFiZWxzLCB2Z192TGVnZW5kTGFiZWxzKGNvbmZpZykpO1xuXG4gICAgLy8gZXh0ZW5kIGxlZ2VuZCBtYXJrc1xuICAgIHZnX2xlZ2VuZFN5bWJvbEV4dGVuZChzeW1ib2xzLCBzaXplLCBzaGFwZSwgZmlsbCwgc3Ryb2tlKTtcbiAgICBcbiAgICAvLyBhZGQgLyBvdmVycmlkZSBjdXN0b20gc3R5bGUgcHJvcGVydGllc1xuICAgIHV0aWwuZXh0ZW5kKHRpdGxlcy5wcm9wZXJ0aWVzLnVwZGF0ZSwgIHRpdGxlU3R5bGUpO1xuICAgIHV0aWwuZXh0ZW5kKHN5bWJvbHMucHJvcGVydGllcy51cGRhdGUsIHN5bWJvbFN0eWxlKTtcbiAgICB1dGlsLmV4dGVuZChsYWJlbHMucHJvcGVydGllcy51cGRhdGUsICBsYWJlbFN0eWxlKTtcblxuICAgIC8vIHBhZGRpbmcgZnJvbSBsZWdlbmQgYm9yZGVyXG4gICAgdGl0bGVzLnByb3BlcnRpZXMuZW50ZXIueC52YWx1ZSArPSBwYWRkaW5nO1xuICAgIHRpdGxlcy5wcm9wZXJ0aWVzLmVudGVyLnkudmFsdWUgKz0gcGFkZGluZztcbiAgICBsYWJlbHMucHJvcGVydGllcy5lbnRlci54Lm9mZnNldCArPSBwYWRkaW5nICsgMTtcbiAgICBzeW1ib2xzLnByb3BlcnRpZXMuZW50ZXIueC5vZmZzZXQgPSBwYWRkaW5nICsgMTtcbiAgICBsYWJlbHMucHJvcGVydGllcy51cGRhdGUueC5vZmZzZXQgKz0gcGFkZGluZyArIDE7XG4gICAgc3ltYm9scy5wcm9wZXJ0aWVzLnVwZGF0ZS54Lm9mZnNldCA9IHBhZGRpbmcgKyAxO1xuXG4gICAgdXRpbC5leHRlbmQobGVnZW5kRGVmLCB7XG4gICAgICB0eXBlOiBcImdyb3VwXCIsXG4gICAgICBpbnRlcmFjdGl2ZTogZmFsc2UsXG4gICAgICBwcm9wZXJ0aWVzOiB7XG4gICAgICAgIGVudGVyOiBwYXJzZVByb3BlcnRpZXMobW9kZWwsIFwiZ3JvdXBcIiwgbGVnZW5kU3R5bGUpLFxuICAgICAgICB2Z19sZWdlbmRQb3NpdGlvbjoge1xuICAgICAgICAgIGVuY29kZTogdmdfbGVnZW5kUG9zaXRpb24sXG4gICAgICAgICAgc2lnbmFsczogW10sIHNjYWxlczpbXSwgZGF0YTogW10sIGZpZWxkczogW11cbiAgICAgICAgfVxuICAgICAgfVxuICAgIH0pO1xuXG4gICAgbGVnZW5kRGVmLm1hcmtzID0gW3RpdGxlcywgc3ltYm9scywgbGFiZWxzXS5tYXAoZnVuY3Rpb24obSkgeyByZXR1cm4gcGFyc2VNYXJrKG1vZGVsLCBtKTsgfSk7XG4gICAgcmV0dXJuIGxlZ2VuZERlZjtcbiAgfVxuXG4gIGZ1bmN0aW9uIHF1YW50RGVmKHNjYWxlKSB7XG4gICAgdmFyIGRlZiA9IHFfbGVnZW5kX2RlZihzY2FsZSksXG4gICAgICAgIGRvbSA9IHNjYWxlLmRvbWFpbigpLFxuICAgICAgICBkYXRhID0gKHZhbHVlcyA9PSBudWxsID9cbiAgICAgICAgICAoc2NhbGUudGlja3MgPyBzY2FsZS50aWNrcy5hcHBseShzY2FsZSwgdGlja0FyZ3VtZW50cykgOiBzY2FsZS5kb21haW4oKSkgOlxuICAgICAgICAgIHZhbHVlcykubWFwKGluZ2VzdCksXG4gICAgICAgIHdpZHRoID0gKGdyYWRpZW50U3R5bGUud2lkdGggJiYgZ3JhZGllbnRTdHlsZS53aWR0aC52YWx1ZSkgfHwgY29uZmlnLmxlZ2VuZC5ncmFkaWVudFdpZHRoLFxuICAgICAgICBmbXQgPSBmb3JtYXQ9PW51bGwgPyAoc2NhbGUudGlja0Zvcm1hdCA/IHNjYWxlLnRpY2tGb3JtYXQuYXBwbHkoc2NhbGUsIHRpY2tBcmd1bWVudHMpIDogU3RyaW5nKSA6IGZvcm1hdDtcblxuICAgIC8vIGJ1aWxkIHNjYWxlIGZvciBsYWJlbCBsYXlvdXRcbiAgICB2YXIgbGF5b3V0U3BlYyA9IHtcbiAgICAgIG5hbWU6IFwibGVnZW5kXCIsXG4gICAgICB0eXBlOiBzY2FsZS50eXBlLFxuICAgICAgcm91bmQ6IHRydWUsXG4gICAgICB6ZXJvOiBmYWxzZSxcbiAgICAgIGRvbWFpbjogW2RvbVswXSwgZG9tW2RvbS5sZW5ndGgtMV1dLFxuICAgICAgcmFuZ2U6IFtwYWRkaW5nLCB3aWR0aCtwYWRkaW5nXVxuICAgIH07XG4gICAgaWYgKHNjYWxlLnR5cGU9PT1cInBvd1wiKSBsYXlvdXRTcGVjLmV4cG9uZW50ID0gc2NhbGUuZXhwb25lbnQoKTtcbiAgICBcbiAgICAvLyB1cGRhdGUgbGVnZW5kIGRlZlxuICAgIHZhciB0ZGF0YSA9ICh0aXRsZSA/IFt0aXRsZV0gOiBbXSkubWFwKGluZ2VzdCk7XG4gICAgZGF0YS5mb3JFYWNoKGZ1bmN0aW9uKGQsaSkge1xuICAgICAgZC5sYWJlbCA9IGZtdChkLmRhdGEpO1xuICAgICAgZC5hbGlnbiA9IGk9PShkYXRhLmxlbmd0aC0xKSA/IFwicmlnaHRcIiA6IGk9PT0wID8gXCJsZWZ0XCIgOiBcImNlbnRlclwiO1xuICAgIH0pO1xuICAgIGRlZi5zY2FsZXMgPSBbIGxheW91dFNwZWMgXTtcbiAgICBkZWYubWFya3NbMF0uZnJvbSA9IGZ1bmN0aW9uKCkgeyByZXR1cm4gdGRhdGE7IH07XG4gICAgZGVmLm1hcmtzWzFdLmZyb20gPSBmdW5jdGlvbigpIHsgcmV0dXJuIFsxXTsgfTtcbiAgICBkZWYubWFya3NbMl0uZnJvbSA9IGZ1bmN0aW9uKCkgeyByZXR1cm4gZGF0YTsgfTtcbiAgICByZXR1cm4gZGVmO1xuICB9XG4gIFxuICBmdW5jdGlvbiBxX2xlZ2VuZF9kZWYoc2NhbGUpIHtcbiAgICAvLyBzZXR1cCBsZWdlbmQgbWFya3NcbiAgICB2YXIgdGl0bGVzID0gdXRpbC5leHRlbmQobS50aXRsZXMsIHZnX2xlZ2VuZFRpdGxlKGNvbmZpZykpLFxuICAgICAgICBncmFkaWVudCA9IHV0aWwuZXh0ZW5kKG0uZ3JhZGllbnQsIHZnX2xlZ2VuZEdyYWRpZW50KGNvbmZpZykpLFxuICAgICAgICBsYWJlbHMgPSB1dGlsLmV4dGVuZChtLmxhYmVscywgdmdfaExlZ2VuZExhYmVscyhjb25maWcpKSxcbiAgICAgICAgZ3JhZCA9IG5ldyBHcmFkaWVudCgpO1xuXG4gICAgLy8gc2V0dXAgY29sb3IgZ3JhZGllbnRcbiAgICB2YXIgZG9tID0gc2NhbGUuZG9tYWluKCksXG4gICAgICAgIG1pbiA9IGRvbVswXSxcbiAgICAgICAgbWF4ID0gZG9tW2RvbS5sZW5ndGgtMV0sXG4gICAgICAgIGYgPSBzY2FsZS5jb3B5KCkuZG9tYWluKFttaW4sIG1heF0pLnJhbmdlKFswLDFdKTtcbiAgICAgICAgXG4gICAgdmFyIHN0b3BzID0gKHNjYWxlLnR5cGUgIT09IFwibGluZWFyXCIgJiYgc2NhbGUudGlja3MpID9cbiAgICAgIHNjYWxlLnRpY2tzLmNhbGwoc2NhbGUsIDE1KSA6IGRvbTtcbiAgICBpZiAobWluICE9PSBzdG9wc1swXSkgc3RvcHMudW5zaGlmdChtaW4pO1xuICAgIGlmIChtYXggIT09IHN0b3BzW3N0b3BzLmxlbmd0aC0xXSkgc3RvcHMucHVzaChtYXgpO1xuXG4gICAgZm9yICh2YXIgaT0wLCBuPXN0b3BzLmxlbmd0aDsgaTxuOyArK2kpIHtcbiAgICAgIGdyYWQuc3RvcChmKHN0b3BzW2ldKSwgc2NhbGUoc3RvcHNbaV0pKTtcbiAgICB9XG4gICAgZ3JhZGllbnQucHJvcGVydGllcy5lbnRlci5maWxsID0ge3ZhbHVlOiBncmFkfTtcblxuICAgIC8vIGFkZCAvIG92ZXJyaWRlIGN1c3RvbSBzdHlsZSBwcm9wZXJ0aWVzXG4gICAgdXRpbC5leHRlbmQodGl0bGVzLnByb3BlcnRpZXMudXBkYXRlLCB0aXRsZVN0eWxlKTtcbiAgICB1dGlsLmV4dGVuZChncmFkaWVudC5wcm9wZXJ0aWVzLnVwZGF0ZSwgZ3JhZGllbnRTdHlsZSk7XG4gICAgdXRpbC5leHRlbmQobGFiZWxzLnByb3BlcnRpZXMudXBkYXRlLCBsYWJlbFN0eWxlKTtcblxuICAgIC8vIGFjY291bnQgZm9yIGdyYWRpZW50IHNpemVcbiAgICB2YXIgZ3AgPSBncmFkaWVudC5wcm9wZXJ0aWVzLCBnaCA9IGdyYWRpZW50U3R5bGUuaGVpZ2h0LFxuICAgICAgICBoaCA9IChnaCAmJiBnaC52YWx1ZSkgfHwgZ3AuZW50ZXIuaGVpZ2h0LnZhbHVlO1xuICAgIGxhYmVscy5wcm9wZXJ0aWVzLmVudGVyLnkudmFsdWUgPSBoaDtcbiAgICBsYWJlbHMucHJvcGVydGllcy51cGRhdGUueS52YWx1ZSA9IGhoO1xuXG4gICAgLy8gYWNjb3VudCBmb3IgdGl0bGUgc2l6ZSBhcyBuZWVkZWRcbiAgICBpZiAodGl0bGUpIHtcbiAgICAgIHZhciB0cCA9IHRpdGxlcy5wcm9wZXJ0aWVzLCBmcyA9IHRpdGxlU3R5bGUuZm9udFNpemUsXG4gICAgICAgICAgc3ogPSA0ICsgKChmcyAmJiBmcy52YWx1ZSkgfHwgdHAuZW50ZXIuZm9udFNpemUudmFsdWUpO1xuICAgICAgZ3JhZGllbnQucHJvcGVydGllcy5lbnRlci55LnZhbHVlICs9IHN6O1xuICAgICAgbGFiZWxzLnByb3BlcnRpZXMuZW50ZXIueS52YWx1ZSArPSBzejtcbiAgICAgIGdyYWRpZW50LnByb3BlcnRpZXMudXBkYXRlLnkudmFsdWUgKz0gc3o7XG4gICAgICBsYWJlbHMucHJvcGVydGllcy51cGRhdGUueS52YWx1ZSArPSBzejtcbiAgICB9XG4gICAgXG4gICAgLy8gcGFkZGluZyBmcm9tIGxlZ2VuZCBib3JkZXJcbiAgICB0aXRsZXMucHJvcGVydGllcy5lbnRlci54LnZhbHVlICs9IHBhZGRpbmc7XG4gICAgdGl0bGVzLnByb3BlcnRpZXMuZW50ZXIueS52YWx1ZSArPSBwYWRkaW5nO1xuICAgIGdyYWRpZW50LnByb3BlcnRpZXMuZW50ZXIueC52YWx1ZSArPSBwYWRkaW5nO1xuICAgIGdyYWRpZW50LnByb3BlcnRpZXMuZW50ZXIueS52YWx1ZSArPSBwYWRkaW5nO1xuICAgIGxhYmVscy5wcm9wZXJ0aWVzLmVudGVyLnkudmFsdWUgKz0gcGFkZGluZztcbiAgICBncmFkaWVudC5wcm9wZXJ0aWVzLnVwZGF0ZS54LnZhbHVlICs9IHBhZGRpbmc7XG4gICAgZ3JhZGllbnQucHJvcGVydGllcy51cGRhdGUueS52YWx1ZSArPSBwYWRkaW5nO1xuICAgIGxhYmVscy5wcm9wZXJ0aWVzLnVwZGF0ZS55LnZhbHVlICs9IHBhZGRpbmc7XG5cbiAgICB1dGlsLmV4dGVuZChsZWdlbmREZWYsIHtcbiAgICAgIHR5cGU6IFwiZ3JvdXBcIixcbiAgICAgIGludGVyYWN0aXZlOiBmYWxzZSxcbiAgICAgIHByb3BlcnRpZXM6IHtcbiAgICAgICAgZW50ZXI6IHBhcnNlUHJvcGVydGllcyhtb2RlbCwgXCJncm91cFwiLCBsZWdlbmRTdHlsZSksXG4gICAgICAgIHZnX2xlZ2VuZFBvc2l0aW9uOiB7XG4gICAgICAgICAgZW5jb2RlOiB2Z19sZWdlbmRQb3NpdGlvbixcbiAgICAgICAgICBzaWduYWxzOiBbXSwgc2NhbGVzOiBbXSwgZGF0YTogW10sIGZpZWxkczogW11cbiAgICAgICAgfVxuICAgICAgfVxuICAgIH0pO1xuXG4gICAgbGVnZW5kRGVmLm1hcmtzID0gW3RpdGxlcywgZ3JhZGllbnQsIGxhYmVsc10ubWFwKGZ1bmN0aW9uKG0pIHsgcmV0dXJuIHBhcnNlTWFyayhtb2RlbCwgbSk7IH0pO1xuICAgIHJldHVybiBsZWdlbmREZWY7XG4gIH1cblxuICBsZWdlbmQuc2l6ZSA9IGZ1bmN0aW9uKHgpIHtcbiAgICBpZiAoIWFyZ3VtZW50cy5sZW5ndGgpIHJldHVybiBzaXplO1xuICAgIGlmIChzaXplICE9PSB4KSB7IHNpemUgPSB4OyByZXNldCgpOyB9XG4gICAgcmV0dXJuIGxlZ2VuZDtcbiAgfTtcblxuICBsZWdlbmQuc2hhcGUgPSBmdW5jdGlvbih4KSB7XG4gICAgaWYgKCFhcmd1bWVudHMubGVuZ3RoKSByZXR1cm4gc2hhcGU7XG4gICAgaWYgKHNoYXBlICE9PSB4KSB7IHNoYXBlID0geDsgcmVzZXQoKTsgfVxuICAgIHJldHVybiBsZWdlbmQ7XG4gIH07XG5cbiAgbGVnZW5kLmZpbGwgPSBmdW5jdGlvbih4KSB7XG4gICAgaWYgKCFhcmd1bWVudHMubGVuZ3RoKSByZXR1cm4gZmlsbDtcbiAgICBpZiAoZmlsbCAhPT0geCkgeyBmaWxsID0geDsgcmVzZXQoKTsgfVxuICAgIHJldHVybiBsZWdlbmQ7XG4gIH07XG4gIFxuICBsZWdlbmQuc3Ryb2tlID0gZnVuY3Rpb24oeCkge1xuICAgIGlmICghYXJndW1lbnRzLmxlbmd0aCkgcmV0dXJuIHN0cm9rZTtcbiAgICBpZiAoc3Ryb2tlICE9PSB4KSB7IHN0cm9rZSA9IHg7IHJlc2V0KCk7IH1cbiAgICByZXR1cm4gbGVnZW5kO1xuICB9O1xuXG4gIGxlZ2VuZC50aXRsZSA9IGZ1bmN0aW9uKHgpIHtcbiAgICBpZiAoIWFyZ3VtZW50cy5sZW5ndGgpIHJldHVybiB0aXRsZTtcbiAgICBpZiAodGl0bGUgIT09IHgpIHsgdGl0bGUgPSB4OyByZXNldCgpOyB9XG4gICAgcmV0dXJuIGxlZ2VuZDtcbiAgfTtcblxuICBsZWdlbmQuZm9ybWF0ID0gZnVuY3Rpb24oeCkge1xuICAgIGlmICghYXJndW1lbnRzLmxlbmd0aCkgcmV0dXJuIGZvcm1hdFN0cmluZztcbiAgICBpZiAoZm9ybWF0U3RyaW5nICE9PSB4KSB7XG4gICAgICBmb3JtYXRTdHJpbmcgPSB4O1xuICAgICAgcmVzZXQoKTtcbiAgICB9XG4gICAgcmV0dXJuIGxlZ2VuZDtcbiAgfTtcblxuICBsZWdlbmQuc3BhY2luZyA9IGZ1bmN0aW9uKHgpIHtcbiAgICBpZiAoIWFyZ3VtZW50cy5sZW5ndGgpIHJldHVybiBzcGFjaW5nO1xuICAgIGlmIChzcGFjaW5nICE9PSAreCkgeyBzcGFjaW5nID0gK3g7IHJlc2V0KCk7IH1cbiAgICByZXR1cm4gbGVnZW5kO1xuICB9O1xuXG4gIGxlZ2VuZC5vcmllbnQgPSBmdW5jdGlvbih4KSB7XG4gICAgaWYgKCFhcmd1bWVudHMubGVuZ3RoKSByZXR1cm4gb3JpZW50O1xuICAgIG9yaWVudCA9IHggaW4gdmdfbGVnZW5kT3JpZW50cyA/IHggKyBcIlwiIDogY29uZmlnLmxlZ2VuZC5vcmllbnQ7XG4gICAgcmV0dXJuIGxlZ2VuZDtcbiAgfTtcblxuICBsZWdlbmQub2Zmc2V0ID0gZnVuY3Rpb24oeCkge1xuICAgIGlmICghYXJndW1lbnRzLmxlbmd0aCkgcmV0dXJuIG9mZnNldDtcbiAgICBvZmZzZXQgPSAreDtcbiAgICByZXR1cm4gbGVnZW5kO1xuICB9O1xuXG4gIGxlZ2VuZC52YWx1ZXMgPSBmdW5jdGlvbih4KSB7XG4gICAgaWYgKCFhcmd1bWVudHMubGVuZ3RoKSByZXR1cm4gdmFsdWVzO1xuICAgIHZhbHVlcyA9IHg7XG4gICAgcmV0dXJuIGxlZ2VuZDtcbiAgfTtcblxuICBsZWdlbmQubGVnZW5kUHJvcGVydGllcyA9IGZ1bmN0aW9uKHgpIHtcbiAgICBpZiAoIWFyZ3VtZW50cy5sZW5ndGgpIHJldHVybiBsZWdlbmRTdHlsZTtcbiAgICBsZWdlbmRTdHlsZSA9IHg7XG4gICAgcmV0dXJuIGxlZ2VuZDtcbiAgfTtcblxuICBsZWdlbmQuc3ltYm9sUHJvcGVydGllcyA9IGZ1bmN0aW9uKHgpIHtcbiAgICBpZiAoIWFyZ3VtZW50cy5sZW5ndGgpIHJldHVybiBzeW1ib2xTdHlsZTtcbiAgICBzeW1ib2xTdHlsZSA9IHg7XG4gICAgcmV0dXJuIGxlZ2VuZDtcbiAgfTtcblxuICBsZWdlbmQuZ3JhZGllbnRQcm9wZXJ0aWVzID0gZnVuY3Rpb24oeCkge1xuICAgIGlmICghYXJndW1lbnRzLmxlbmd0aCkgcmV0dXJuIGdyYWRpZW50U3R5bGU7XG4gICAgZ3JhZGllbnRTdHlsZSA9IHg7XG4gICAgcmV0dXJuIGxlZ2VuZDtcbiAgfTtcblxuICBsZWdlbmQubGFiZWxQcm9wZXJ0aWVzID0gZnVuY3Rpb24oeCkge1xuICAgIGlmICghYXJndW1lbnRzLmxlbmd0aCkgcmV0dXJuIGxhYmVsU3R5bGU7XG4gICAgbGFiZWxTdHlsZSA9IHg7XG4gICAgcmV0dXJuIGxlZ2VuZDtcbiAgfTtcbiAgXG4gIGxlZ2VuZC50aXRsZVByb3BlcnRpZXMgPSBmdW5jdGlvbih4KSB7XG4gICAgaWYgKCFhcmd1bWVudHMubGVuZ3RoKSByZXR1cm4gdGl0bGVTdHlsZTtcbiAgICB0aXRsZVN0eWxlID0geDtcbiAgICByZXR1cm4gbGVnZW5kO1xuICB9O1xuXG4gIGxlZ2VuZC5yZXNldCA9IGZ1bmN0aW9uKCkgeyBcbiAgICByZXNldCgpOyBcbiAgICByZXR1cm4gbGVnZW5kO1xuICB9O1xuXG4gIHJldHVybiBsZWdlbmQ7XG59XG5cbnZhciB2Z19sZWdlbmRPcmllbnRzID0ge3JpZ2h0OiAxLCBsZWZ0OiAxfTtcblxuZnVuY3Rpb24gdmdfbGVnZW5kUG9zaXRpb24oaXRlbSwgZ3JvdXAsIHRyYW5zLCBkYiwgc2lnbmFscywgcHJlZGljYXRlcykge1xuICB2YXIgbyA9IHRyYW5zID8ge30gOiBpdGVtLCBneCxcbiAgICAgIG9mZnNldCA9IGl0ZW0ubWFyay5kZWYub2Zmc2V0LFxuICAgICAgb3JpZW50ID0gaXRlbS5tYXJrLmRlZi5vcmllbnQsXG4gICAgICBwYWQgICAgPSBpdGVtLm1hcmsuZGVmLnBhZGRpbmcgKiAyLFxuICAgICAgbHcgICAgID0gfn5pdGVtLmJvdW5kcy53aWR0aCgpICsgKGl0ZW0ud2lkdGggPyAwIDogcGFkKSxcbiAgICAgIGxoICAgICA9IH5+aXRlbS5ib3VuZHMuaGVpZ2h0KCkgKyAoaXRlbS5oZWlnaHQgPyAwIDogcGFkKSxcbiAgICAgIHBvcyA9IGdyb3VwLl9sZWdlbmRQb3NpdGlvbnMgfHwgXG4gICAgICAgIChncm91cC5fbGVnZW5kUG9zaXRpb25zID0ge3JpZ2h0OiAwLjUsIGxlZnQ6IDAuNX0pO1xuXG4gIG8ueCA9IDAuNTtcbiAgby53aWR0aCA9IGx3O1xuICBvLnkgPSBwb3Nbb3JpZW50XTtcbiAgcG9zW29yaWVudF0gKz0gKG8uaGVpZ2h0ID0gbGgpO1xuXG4gIC8vIEhBQ0s6IHVzZSB0byBlc3RpbWF0ZSBncm91cCBib3VuZHMgZHVyaW5nIGFuaW1hdGVkIHRyYW5zaXRpb25cbiAgaWYgKCF0cmFucyAmJiBncm91cC5ib3VuZHMpIHtcbiAgICBncm91cC5ib3VuZHMuZGVsdGEgPSBncm91cC5ib3VuZHMueDIgLSBncm91cC53aWR0aDtcbiAgfVxuXG4gIHN3aXRjaCAob3JpZW50KSB7XG4gICAgY2FzZSBcImxlZnRcIjogIHtcbiAgICAgIGd4ID0gZ3JvdXAuYm91bmRzID8gZ3JvdXAuYm91bmRzLngxIDogMDtcbiAgICAgIG8ueCArPSBneCAtIG9mZnNldCAtIGx3O1xuICAgICAgYnJlYWs7XG4gICAgfVxuICAgIGNhc2UgXCJyaWdodFwiOiB7XG4gICAgICBneCA9IGdyb3VwLndpZHRoICsgKGdyb3VwLmJvdW5kcyAmJiB0cmFucyA/IGdyb3VwLmJvdW5kcy5kZWx0YSA6IDApO1xuICAgICAgby54ICs9IGd4ICsgb2Zmc2V0O1xuICAgICAgYnJlYWs7XG4gICAgfVxuICB9XG4gIFxuICBpZiAodHJhbnMpIHRyYW5zLmludGVycG9sYXRlKGl0ZW0sIG8pO1xuICB2YXIgZW5jID0gaXRlbS5tYXJrLmRlZi5wcm9wZXJ0aWVzLmVudGVyLmVuY29kZTtcbiAgZW5jLmNhbGwoZW5jLCBpdGVtLCBncm91cCwgdHJhbnMsIGRiLCBzaWduYWxzLCBwcmVkaWNhdGVzKTtcbiAgcmV0dXJuIHRydWU7XG59XG5cbmZ1bmN0aW9uIHZnX2xlZ2VuZFN5bWJvbEV4dGVuZChtYXJrLCBzaXplLCBzaGFwZSwgZmlsbCwgc3Ryb2tlKSB7XG4gIHZhciBlID0gbWFyay5wcm9wZXJ0aWVzLmVudGVyLFxuICAgICAgdSA9IG1hcmsucHJvcGVydGllcy51cGRhdGU7XG4gIGlmIChzaXplKSAgIGUuc2l6ZSAgID0gdS5zaXplICAgPSB7c2NhbGU6IHNpemUuc2NhbGVOYW1lLCAgIGZpZWxkOiBcImRhdGFcIn07XG4gIGlmIChzaGFwZSkgIGUuc2hhcGUgID0gdS5zaGFwZSAgPSB7c2NhbGU6IHNoYXBlLnNjYWxlTmFtZSwgIGZpZWxkOiBcImRhdGFcIn07XG4gIGlmIChmaWxsKSAgIGUuZmlsbCAgID0gdS5maWxsICAgPSB7c2NhbGU6IGZpbGwuc2NhbGVOYW1lLCAgIGZpZWxkOiBcImRhdGFcIn07XG4gIGlmIChzdHJva2UpIGUuc3Ryb2tlID0gdS5zdHJva2UgPSB7c2NhbGU6IHN0cm9rZS5zY2FsZU5hbWUsIGZpZWxkOiBcImRhdGFcIn07XG59XG5cbmZ1bmN0aW9uIHZnX2xlZ2VuZFRpdGxlKGNvbmZpZykge1xuICB2YXIgY2ZnID0gY29uZmlnLmxlZ2VuZDtcbiAgcmV0dXJuIHtcbiAgICB0eXBlOiBcInRleHRcIixcbiAgICBpbnRlcmFjdGl2ZTogZmFsc2UsXG4gICAga2V5OiBcImRhdGFcIixcbiAgICBwcm9wZXJ0aWVzOiB7XG4gICAgICBlbnRlcjoge1xuICAgICAgICB4OiB7dmFsdWU6IDB9LFxuICAgICAgICB5OiB7dmFsdWU6IDB9LFxuICAgICAgICBmaWxsOiB7dmFsdWU6IGNmZy50aXRsZUNvbG9yfSxcbiAgICAgICAgZm9udDoge3ZhbHVlOiBjZmcudGl0bGVGb250fSxcbiAgICAgICAgZm9udFNpemU6IHt2YWx1ZTogY2ZnLnRpdGxlRm9udFNpemV9LFxuICAgICAgICBmb250V2VpZ2h0OiB7dmFsdWU6IGNmZy50aXRsZUZvbnRXZWlnaHR9LFxuICAgICAgICBiYXNlbGluZToge3ZhbHVlOiBcInRvcFwifSxcbiAgICAgICAgdGV4dDoge2ZpZWxkOiBcImRhdGFcIn0sXG4gICAgICAgIG9wYWNpdHk6IHt2YWx1ZTogMWUtNn1cbiAgICAgIH0sXG4gICAgICBleGl0OiB7IG9wYWNpdHk6IHt2YWx1ZTogMWUtNn0gfSxcbiAgICAgIHVwZGF0ZTogeyBvcGFjaXR5OiB7dmFsdWU6IDF9IH1cbiAgICB9XG4gIH07XG59XG5cbmZ1bmN0aW9uIHZnX2xlZ2VuZFN5bWJvbHMoY29uZmlnKSB7XG4gIHZhciBjZmcgPSBjb25maWcubGVnZW5kO1xuICByZXR1cm4ge1xuICAgIHR5cGU6IFwic3ltYm9sXCIsXG4gICAgaW50ZXJhY3RpdmU6IGZhbHNlLFxuICAgIGtleTogXCJkYXRhXCIsXG4gICAgcHJvcGVydGllczoge1xuICAgICAgZW50ZXI6IHtcbiAgICAgICAgeDoge2ZpZWxkOiBcIm9mZnNldFwiLCBtdWx0OiAwLjV9LFxuICAgICAgICB5OiB7c2NhbGU6IFwibGVnZW5kXCIsIGZpZWxkOiBcImluZGV4XCJ9LFxuICAgICAgICBzaGFwZToge3ZhbHVlOiBjZmcuc3ltYm9sU2hhcGV9LFxuICAgICAgICBzaXplOiB7dmFsdWU6IGNmZy5zeW1ib2xTaXplfSxcbiAgICAgICAgc3Ryb2tlOiB7dmFsdWU6IGNmZy5zeW1ib2xDb2xvcn0sXG4gICAgICAgIHN0cm9rZVdpZHRoOiB7dmFsdWU6IGNmZy5zeW1ib2xTdHJva2VXaWR0aH0sXG4gICAgICAgIG9wYWNpdHk6IHt2YWx1ZTogMWUtNn1cbiAgICAgIH0sXG4gICAgICBleGl0OiB7IG9wYWNpdHk6IHt2YWx1ZTogMWUtNn0gfSxcbiAgICAgIHVwZGF0ZToge1xuICAgICAgICB4OiB7ZmllbGQ6IFwib2Zmc2V0XCIsIG11bHQ6IDAuNX0sXG4gICAgICAgIHk6IHtzY2FsZTogXCJsZWdlbmRcIiwgZmllbGQ6IFwiaW5kZXhcIn0sXG4gICAgICAgIG9wYWNpdHk6IHt2YWx1ZTogMX1cbiAgICAgIH1cbiAgICB9XG4gIH07XG59XG5cbmZ1bmN0aW9uIHZnX3ZMZWdlbmRMYWJlbHMoY29uZmlnKSB7XG4gIHZhciBjZmcgPSBjb25maWcubGVnZW5kO1xuICByZXR1cm4ge1xuICAgIHR5cGU6IFwidGV4dFwiLFxuICAgIGludGVyYWN0aXZlOiBmYWxzZSxcbiAgICBrZXk6IFwiZGF0YVwiLFxuICAgIHByb3BlcnRpZXM6IHtcbiAgICAgIGVudGVyOiB7XG4gICAgICAgIHg6IHtmaWVsZDogXCJvZmZzZXRcIiwgb2Zmc2V0OiA1fSxcbiAgICAgICAgeToge3NjYWxlOiBcImxlZ2VuZFwiLCBmaWVsZDogXCJpbmRleFwifSxcbiAgICAgICAgZmlsbDoge3ZhbHVlOiBjZmcubGFiZWxDb2xvcn0sXG4gICAgICAgIGZvbnQ6IHt2YWx1ZTogY2ZnLmxhYmVsRm9udH0sXG4gICAgICAgIGZvbnRTaXplOiB7dmFsdWU6IGNmZy5sYWJlbEZvbnRTaXplfSxcbiAgICAgICAgYWxpZ246IHt2YWx1ZTogY2ZnLmxhYmVsQWxpZ259LFxuICAgICAgICBiYXNlbGluZToge3ZhbHVlOiBjZmcubGFiZWxCYXNlbGluZX0sXG4gICAgICAgIHRleHQ6IHtmaWVsZDogXCJsYWJlbFwifSxcbiAgICAgICAgb3BhY2l0eToge3ZhbHVlOiAxZS02fVxuICAgICAgfSxcbiAgICAgIGV4aXQ6IHsgb3BhY2l0eToge3ZhbHVlOiAxZS02fSB9LFxuICAgICAgdXBkYXRlOiB7XG4gICAgICAgIG9wYWNpdHk6IHt2YWx1ZTogMX0sXG4gICAgICAgIHg6IHtmaWVsZDogXCJvZmZzZXRcIiwgb2Zmc2V0OiA1fSxcbiAgICAgICAgeToge3NjYWxlOiBcImxlZ2VuZFwiLCBmaWVsZDogXCJpbmRleFwifSxcbiAgICAgIH1cbiAgICB9XG4gIH07XG59XG5cbmZ1bmN0aW9uIHZnX2xlZ2VuZEdyYWRpZW50KGNvbmZpZykge1xuICB2YXIgY2ZnID0gY29uZmlnLmxlZ2VuZDtcbiAgcmV0dXJuIHtcbiAgICB0eXBlOiBcInJlY3RcIixcbiAgICBpbnRlcmFjdGl2ZTogZmFsc2UsXG4gICAgcHJvcGVydGllczoge1xuICAgICAgZW50ZXI6IHtcbiAgICAgICAgeDoge3ZhbHVlOiAwfSxcbiAgICAgICAgeToge3ZhbHVlOiAwfSxcbiAgICAgICAgd2lkdGg6IHt2YWx1ZTogY2ZnLmdyYWRpZW50V2lkdGh9LFxuICAgICAgICBoZWlnaHQ6IHt2YWx1ZTogY2ZnLmdyYWRpZW50SGVpZ2h0fSxcbiAgICAgICAgc3Ryb2tlOiB7dmFsdWU6IGNmZy5ncmFkaWVudFN0cm9rZUNvbG9yfSxcbiAgICAgICAgc3Ryb2tlV2lkdGg6IHt2YWx1ZTogY2ZnLmdyYWRpZW50U3Ryb2tlV2lkdGh9LFxuICAgICAgICBvcGFjaXR5OiB7dmFsdWU6IDFlLTZ9XG4gICAgICB9LFxuICAgICAgZXhpdDogeyBvcGFjaXR5OiB7dmFsdWU6IDFlLTZ9IH0sXG4gICAgICB1cGRhdGU6IHtcbiAgICAgICAgeDoge3ZhbHVlOiAwfSxcbiAgICAgICAgeToge3ZhbHVlOiAwfSxcbiAgICAgICAgb3BhY2l0eToge3ZhbHVlOiAxfVxuICAgICAgfVxuICAgIH1cbiAgfTtcbn1cblxuZnVuY3Rpb24gdmdfaExlZ2VuZExhYmVscyhjb25maWcpIHtcbiAgdmFyIGNmZyA9IGNvbmZpZy5sZWdlbmQ7XG4gIHJldHVybiB7XG4gICAgdHlwZTogXCJ0ZXh0XCIsXG4gICAgaW50ZXJhY3RpdmU6IGZhbHNlLFxuICAgIGtleTogXCJkYXRhXCIsXG4gICAgcHJvcGVydGllczoge1xuICAgICAgZW50ZXI6IHtcbiAgICAgICAgeDoge3NjYWxlOiBcImxlZ2VuZFwiLCBmaWVsZDogXCJkYXRhXCJ9LFxuICAgICAgICB5OiB7dmFsdWU6IDIwfSxcbiAgICAgICAgZHk6IHt2YWx1ZTogMn0sXG4gICAgICAgIGZpbGw6IHt2YWx1ZTogY2ZnLmxhYmVsQ29sb3J9LFxuICAgICAgICBmb250OiB7dmFsdWU6IGNmZy5sYWJlbEZvbnR9LFxuICAgICAgICBmb250U2l6ZToge3ZhbHVlOiBjZmcubGFiZWxGb250U2l6ZX0sXG4gICAgICAgIGFsaWduOiB7ZmllbGQ6IFwiYWxpZ25cIn0sXG4gICAgICAgIGJhc2VsaW5lOiB7dmFsdWU6IFwidG9wXCJ9LFxuICAgICAgICB0ZXh0OiB7ZmllbGQ6IFwibGFiZWxcIn0sXG4gICAgICAgIG9wYWNpdHk6IHt2YWx1ZTogMWUtNn1cbiAgICAgIH0sXG4gICAgICBleGl0OiB7IG9wYWNpdHk6IHt2YWx1ZTogMWUtNn0gfSxcbiAgICAgIHVwZGF0ZToge1xuICAgICAgICB4OiB7c2NhbGU6IFwibGVnZW5kXCIsIGZpZWxkOiBcImRhdGFcIn0sXG4gICAgICAgIHk6IHt2YWx1ZTogMjB9LFxuICAgICAgICBvcGFjaXR5OiB7dmFsdWU6IDF9XG4gICAgICB9XG4gICAgfVxuICB9O1xufVxuXG5tb2R1bGUuZXhwb3J0cyA9IGxnbmQ7Il19
},{"../parse/mark":91,"../parse/properties":96,"datalib/src/util":20,"vega-scenegraph/src/util/Gradient":71}],109:[function(require,module,exports){
module.exports = function visit(node, func) {
var i, n, s, m, items;
if (func(node)) return true;
var sets = ['items', 'axisItems', 'legendItems'];
for (s=0, m=sets.length; s<m; ++s) {
if ((items = node[sets[s]])) {
for (i=0, n=items.length; i<n; ++i) {
if (visit(items[i], func)) return true;
}
}
}
};
},{}],110:[function(require,module,exports){
var util = require('datalib/src/util'),
ChangeSet = require('vega-dataflow/src/ChangeSet'),
Tuple = require('vega-dataflow/src/Tuple'),
Deps = require('vega-dataflow/src/Dependencies'),
log = require('vega-logging'),
Transform = require('./Transform'),
Facetor = require('./Facetor');
function Aggregate(graph) {
Transform.prototype.init.call(this, graph);
Transform.addParameters(this, {
groupby: {type: 'array<field>'},
summarize: {
type: 'custom',
set: function(summarize) {
var signals = {},
i, len, f, fields, name, ops;
if (!util.isArray(fields = summarize)) { // Object syntax from util
fields = [];
for (name in summarize) {
ops = util.array(summarize[name]);
fields.push({field: name, ops: ops});
}
}
function sg(x) { if (x.signal) signals[x.signal] = 1; }
for (i=0, len=fields.length; i<len; ++i) {
f = fields[i];
if (f.field.signal) signals[f.field.signal] = 1;
util.array(f.ops).forEach(sg);
util.array(f.as).forEach(sg);
}
this._transform._fieldsDef = fields;
this._transform._aggr = null;
this._transform.dependency(Deps.SIGNALS, util.keys(signals));
return this._transform;
}
}
});
this._fieldsDef = [];
this._aggr = null; // util.Aggregator
this._type = TYPES.TUPLE;
this._acc = {groupby: util.true, value: util.true};
this._cache = {}; // And cache them as aggregators expect original tuples.
// Aggregator needs a full instantiation of the previous tuple.
// Cache them to reduce creation costs.
this._prev = {};
return this.router(true).revises(true);
}
var prototype = (Aggregate.prototype = Object.create(Transform.prototype));
prototype.constructor = Aggregate;
var TYPES = Aggregate.TYPES = {
VALUE: 1,
TUPLE: 2,
MULTI: 3
};
Aggregate.VALID_OPS = [
'values', 'count', 'valid', 'missing', 'distinct',
'sum', 'mean', 'average', 'variance', 'variancep', 'stdev',
'stdevp', 'median', 'q1', 'q3', 'modeskew', 'min', 'max',
'argmin', 'argmax'
];
prototype.type = function(type) {
return (this._type = type, this);
};
prototype.accessors = function(groupby, value) {
var acc = this._acc;
acc.groupby = util.$(groupby) || util.true;
acc.value = util.$(value) || util.true;
};
function standardize(x) {
var acc = this._acc;
if (this._type === TYPES.TUPLE) {
return x;
} else if (this._type === TYPES.VALUE) {
return acc.value(x);
} else {
return this._cache[x._id] || (this._cache[x._id] = {
_id: x._id,
groupby: acc.groupby(x),
value: acc.value(x)
});
}
}
prototype.aggr = function() {
if (this._aggr) return this._aggr;
var graph = this._graph,
groupby = this.param('groupby').field;
var fields = this._fieldsDef.map(function(field) {
var f = util.duplicate(field);
if (field.get) f.get = field.get;
f.name = f.field.signal ? graph.signalRef(f.field.signal) : f.field;
f.ops = f.ops.signal ? graph.signalRef(f.ops.signal) :
util.array(f.ops).map(function(o) {
return o.signal ? graph.signalRef(o.signal) : o;
});
return f;
});
if (!fields.length) fields = {'*':'values'};
var aggr = this._aggr = new Facetor()
.groupby(groupby)
.stream(true)
.summarize(fields);
if (this._type !== TYPES.VALUE) aggr.key('_id');
return aggr;
};
prototype._reset = function(input, output) {
output.rem.push.apply(output.rem, this.aggr().result());
this.aggr().clear();
this._aggr = null;
};
function spoof_prev(x) {
var prev = this._prev[x._id] || (this._prev[x._id] = Object.create(x));
return util.extend(prev, x._prev);
}
prototype.transform = function(input, reset) {
log.debug(input, ['aggregate']);
var output = ChangeSet.create(input);
if (reset) this._reset(input, output);
var t = this,
tpl = this._type === TYPES.TUPLE, // reduce calls to standardize
aggr = this.aggr();
input.add.forEach(function(x) {
aggr._add(tpl ? x : standardize.call(t, x));
});
input.mod.forEach(function(x) {
if (reset) {
// Signal change triggered reflow
aggr._add(tpl ? x : standardize.call(t, x));
} else {
var y = Tuple.has_prev(x) ? spoof_prev.call(t, x) : x;
aggr._mod(tpl ? x : standardize.call(t, x),
tpl ? y : standardize.call(t, y));
}
});
input.rem.forEach(function(x) {
var y = Tuple.has_prev(x) ? spoof_prev.call(t, x) : x;
aggr._rem(tpl ? y : standardize.call(t, y));
t._cache[x._id] = t._prev[x._id] = null;
});
return aggr.changes(input, output);
};
module.exports = Aggregate;
},{"./Facetor":115,"./Transform":127,"datalib/src/util":20,"vega-dataflow/src/ChangeSet":26,"vega-dataflow/src/Dependencies":29,"vega-dataflow/src/Tuple":34,"vega-logging":41}],111:[function(require,module,exports){
var Base = require('./Transform').prototype;
function BatchTransform() {
// Funcptr to nearest shared upstream collector.
// Populated by the dataflow Graph during connection.
this.data = null;
}
var prototype = (BatchTransform.prototype = Object.create(Base));
prototype.constructor = BatchTransform;
prototype.init = function(graph) {
Base.init.call(this, graph);
return this.batch(true);
};
prototype.transform = function(input) {
return this.batchTransform(input, this.data());
};
prototype.batchTransform = function(/* input, data */) {
};
module.exports = BatchTransform;
},{"./Transform":127}],112:[function(require,module,exports){
var bins = require('datalib/src/bins/bins'),
Tuple = require('vega-dataflow/src/Tuple'),
log = require('vega-logging'),
Transform = require('./Transform');
function Bin(graph) {
Transform.prototype.init.call(this, graph);
Transform.addParameters(this, {
field: {type: 'field'},
min: {type: 'value'},
max: {type: 'value'},
base: {type: 'value', default: 10},
maxbins: {type: 'value', default: 20},
step: {type: 'value'},
steps: {type: 'value'},
minstep: {type: 'value'},
div: {type: 'array<value>', default: [5, 2]}
});
this._output = {'bin': 'bin'};
return this;
}
var prototype = (Bin.prototype = Object.create(Transform.prototype));
prototype.constructor = Bin;
prototype.transform = function(input) {
log.debug(input, ['binning']);
var output = this._output.bin,
step = this.param('step'),
steps = this.param('steps'),
minstep = this.param('minstep'),
get = this.param('field').accessor,
opt = {
min: this.param('min'),
max: this.param('max'),
base: this.param('base'),
maxbins: this.param('maxbins'),
div: this.param('div')
};
if (step) opt.step = step;
if (steps) opt.steps = steps;
if (minstep) opt.minstep = minstep;
var b = bins(opt);
function update(d) {
var v = get(d);
v = v == null ? null
: b.start + b.step * ~~((v - b.start) / b.step);
Tuple.set(d, output, v, input.stamp);
}
input.add.forEach(update);
input.mod.forEach(update);
input.rem.forEach(update);
return input;
};
module.exports = Bin;
},{"./Transform":127,"datalib/src/bins/bins":6,"vega-dataflow/src/Tuple":34,"vega-logging":41}],113:[function(require,module,exports){
var ChangeSet = require('vega-dataflow/src/ChangeSet'),
Tuple = require('vega-dataflow/src/Tuple'),
log = require('vega-logging'),
Transform = require('./Transform'),
BatchTransform = require('./BatchTransform');
function Cross(graph) {
BatchTransform.prototype.init.call(this, graph);
Transform.addParameters(this, {
with: {type: 'data'},
diagonal: {type: 'value', default: 'true'}
});
this._output = {'left': 'a', 'right': 'b'};
this._lastRem = null; // Most recent stamp that rem occured.
this._lastWith = null; // Last time we crossed w/withds.
this._ids = {};
this._cache = {};
return this.router(true);
}
var prototype = (Cross.prototype = Object.create(BatchTransform.prototype));
prototype.constructor = Cross;
// Each cached incoming tuple also has a stamp to track if we need to do
// lazy filtering of removed tuples.
function cache(x, t) {
var c = this._cache[x._id] = this._cache[x._id] || {c: [], s: this._stamp};
c.c.push(t);
}
function add(output, left, data, diag, x) {
var i = 0, len = data.length,
prev = x._prev !== undefined ? null : undefined,
t, y, id;
for (; i<len; ++i) {
y = data[i];
id = left ? x._id+'_'+y._id : y._id+'_'+x._id;
if (this._ids[id]) continue;
if (x._id == y._id && !diag) continue;
t = Tuple.ingest({}, prev);
t[this._output.left] = left ? x : y;
t[this._output.right] = left ? y : x;
output.add.push(t);
cache.call(this, x, t);
cache.call(this, y, t);
this._ids[id] = 1;
}
}
function mod(output, left, x) {
var cross = this,
c = this._cache[x._id];
if (this._lastRem > c.s) { // Removed tuples haven't been filtered yet
c.c = c.c.filter(function(y) {
var t = y[cross._output[left ? 'right' : 'left']];
return cross._cache[t._id] !== null;
});
c.s = this._lastRem;
}
output.mod.push.apply(output.mod, c.c);
}
function rem(output, x) {
output.rem.push.apply(output.rem, this._cache[x._id].c);
this._cache[x._id] = null;
this._lastRem = this._stamp;
}
function upFields(input, output) {
if (input.add.length || input.rem.length) {
output.fields[this._output.left] = 1;
output.fields[this._output.right] = 1;
}
}
prototype.batchTransform = function(input, data) {
log.debug(input, ['crossing']);
var w = this.param('with'),
diag = this.param('diagonal'),
selfCross = (!w.name),
woutput = selfCross ? input : w.source.last(),
wdata = selfCross ? data : w.source.values(),
output = ChangeSet.create(input),
r = rem.bind(this, output);
input.rem.forEach(r);
input.add.forEach(add.bind(this, output, true, wdata, diag));
if (!selfCross && woutput.stamp > this._lastWith) {
woutput.rem.forEach(r);
woutput.add.forEach(add.bind(this, output, false, data, diag));
woutput.mod.forEach(mod.bind(this, output, false));
upFields.call(this, woutput, output);
this._lastWith = woutput.stamp;
}
// Mods need to come after all removals have been run.
input.mod.forEach(mod.bind(this, output, true));
upFields.call(this, input, output);
return output;
};
module.exports = Cross;
},{"./BatchTransform":111,"./Transform":127,"vega-dataflow/src/ChangeSet":26,"vega-dataflow/src/Tuple":34,"vega-logging":41}],114:[function(require,module,exports){
var Transform = require('./Transform'),
Aggregate = require('./Aggregate');
function Facet(graph) {
Transform.addParameters(this, {
transform: {
type: "custom",
set: function(pipeline) {
return (this._transform._pipeline = pipeline, this._transform);
},
get: function() {
var parse = require('../parse/transforms'),
facet = this._transform;
return facet._pipeline.map(function(t) {
return parse(facet._graph, t);
});
}
}
});
this._pipeline = [];
Aggregate.call(this, graph);
}
var prototype = (Facet.prototype = Object.create(Aggregate.prototype));
prototype.constructor = Facet;
prototype.aggr = function() {
return Aggregate.prototype.aggr.call(this).facet(this);
};
module.exports = Facet;
},{"../parse/transforms":100,"./Aggregate":110,"./Transform":127}],115:[function(require,module,exports){
var Aggregator = require('datalib/src/aggregate/aggregator'),
Base = Aggregator.prototype,
Flags = Aggregator.Flags,
ChangeSet = require('vega-dataflow/src/ChangeSet'),
Tuple = require('vega-dataflow/src/Tuple'),
util = require('datalib/src/util'),
log = require('vega-logging'),
facetID = 1;
function Facetor() {
Aggregator.call(this);
this._facet = null;
}
var prototype = (Facetor.prototype = Object.create(Base));
prototype.constructor = Facetor;
prototype.facet = function(f) {
if (!arguments.length) return this._facet;
return (this._facet = f, this);
};
prototype._ingest = function(t) {
return Tuple.ingest(t, null);
};
prototype._assign = Tuple.set;
function disconnect_cell(facet) {
log.debug({}, ["deleting cell", this.tuple._id]);
var pipeline = this.ds.pipeline();
facet.removeListener(pipeline[0]);
facet._graph.disconnect(pipeline);
}
prototype._newcell = function(x) {
var cell = Base._newcell.call(this, x),
facet = this._facet,
tuple = cell.tuple,
graph, pipeline;
if (this._facet !== null) {
graph = facet._graph;
pipeline = facet.param('transform');
cell.ds = graph.data(tuple._facetID, pipeline, tuple);
cell.delete = disconnect_cell;
facet.addListener(pipeline[0]);
}
return cell;
};
prototype._newtuple = function(x) {
var t = Base._newtuple.call(this, x);
if (this._facet !== null) {
Tuple.set(t, 'key', this._cellkey(x));
Tuple.set(t, '_facetID', 'vg_'+(facetID++));
}
return t;
};
prototype.clear = function() {
if (this._facet !== null) for (var k in this._cells) {
this._cells[k].delete(this._facet);
}
return Base.clear.call(this);
};
prototype._add = function(x) {
var cell = this._cell(x);
Base._add.call(this, x);
if (this._facet !== null) cell.ds._input.add.push(x);
};
prototype._mod = function(x, prev) {
var cell0 = this._cell(prev),
cell1 = this._cell(x);
Base._mod.call(this, x, prev);
if (this._facet !== null) { // Propagate tuples
if (cell0 === cell1) {
cell0.ds._input.mod.push(x);
} else {
cell0.ds._input.rem.push(x);
cell1.ds._input.add.push(x);
}
}
};
prototype._rem = function(x) {
var cell = this._cell(x);
Base._rem.call(this, x);
if (this._facet !== null) cell.ds._input.rem.push(x);
};
prototype.changes = function(input, output) {
var aggr = this._aggr,
cell, flag, i, k;
function fields(k) { output.fields[k] = 1; }
for (k in this._cells) {
cell = this._cells[k];
flag = cell.flag;
// consolidate collector values
if (cell.collect) {
cell.data.values();
}
// update tuple properties
for (i=0; i<aggr.length; ++i) {
cell.aggs[aggr[i].name].set();
}
// organize output tuples
if (cell.num <= 0) {
if (flag === Flags.MOD_CELL) {
output.rem.push(cell.tuple);
}
if (this._facet !== null) cell.delete(this._facet);
delete this._cells[k];
} else {
if (this._facet !== null) {
// propagate sort, signals, fields, etc.
ChangeSet.copy(input, cell.ds._input);
}
if (flag & Flags.ADD_CELL) {
output.add.push(cell.tuple);
} else if (flag & Flags.MOD_CELL) {
output.mod.push(cell.tuple);
util.keys(cell.tuple._prev).forEach(fields);
}
}
cell.flag = 0;
}
this._rems = false;
return output;
};
module.exports = Facetor;
},{"datalib/src/aggregate/aggregator":3,"datalib/src/util":20,"vega-dataflow/src/ChangeSet":26,"vega-dataflow/src/Tuple":34,"vega-logging":41}],116:[function(require,module,exports){
var ChangeSet = require('vega-dataflow/src/ChangeSet'),
Deps = require('vega-dataflow/src/Dependencies'),
log = require('vega-logging'),
Transform = require('./Transform');
function Filter(graph) {
Transform.prototype.init.call(this, graph);
Transform.addParameters(this, {test: {type: 'expr'}});
this._skip = {};
return this.router(true);
}
var prototype = (Filter.prototype = Object.create(Transform.prototype));
prototype.constructor = Filter;
prototype.transform = function(input) {
log.debug(input, ['filtering']);
var output = ChangeSet.create(input),
graph = this._graph,
skip = this._skip,
test = this.param('test'),
signals = graph.signalValues(this.dependency(Deps.SIGNALS));
input.rem.forEach(function(x) {
if (skip[x._id] !== 1) output.rem.push(x);
else skip[x._id] = 0;
});
input.add.forEach(function(x) {
if (test(x, null, signals)) output.add.push(x);
else skip[x._id] = 1;
});
input.mod.forEach(function(x) {
var b = test(x, null, signals),
s = (skip[x._id] === 1);
if (b && s) {
skip[x._id] = 0;
output.add.push(x);
} else if (b && !s) {
output.mod.push(x);
} else if (!b && s) {
// do nothing, keep skip true
} else { // !b && !s
output.rem.push(x);
skip[x._id] = 1;
}
});
return output;
};
module.exports = Filter;
},{"./Transform":127,"vega-dataflow/src/ChangeSet":26,"vega-dataflow/src/Dependencies":29,"vega-logging":41}],117:[function(require,module,exports){
var ChangeSet = require('vega-dataflow/src/ChangeSet'),
Tuple = require('vega-dataflow/src/Tuple'),
log = require('vega-logging'),
Transform = require('./Transform');
function Fold(graph) {
Transform.prototype.init.call(this, graph);
Transform.addParameters(this, {
fields: {type: 'array<field>'}
});
this._output = {key: 'key', value: 'value'};
this._cache = {};
return this.router(true).revises(true);
}
var prototype = (Fold.prototype = Object.create(Transform.prototype));
prototype.constructor = Fold;
function rst(input, output) {
for (var id in this._cache) {
output.rem.push.apply(output.rem, this._cache[id]);
}
this._cache = {};
}
function get_tuple(x, i, len) {
var list = this._cache[x._id] || (this._cache[x._id] = Array(len));
return list[i] || (list[i] = Tuple.derive(x, x._prev));
}
function fn(data, on, out) {
var i, j, n, m, d, t;
for (i=0, n=data.length; i<n; ++i) {
d = data[i];
for (j=0, m=on.field.length; j<m; ++j) {
t = get_tuple.call(this, d, j, m);
Tuple.set(t, this._output.key, on.field[j]);
Tuple.set(t, this._output.value, on.accessor[j](d));
out.push(t);
}
}
}
prototype.transform = function(input, reset) {
log.debug(input, ['folding']);
var fold = this,
on = this.param('fields'),
output = ChangeSet.create(input);
if (reset) rst.call(this, input, output);
fn.call(this, input.add, on, output.add);
fn.call(this, input.mod, on, reset ? output.add : output.mod);
input.rem.forEach(function(x) {
output.rem.push.apply(output.rem, fold._cache[x._id]);
fold._cache[x._id] = null;
});
// If we're only propagating values, don't mark key/value as updated.
if (input.add.length || input.rem.length ||
on.field.some(function(f) { return !!input.fields[f]; })) {
output.fields[this._output.key] = 1;
output.fields[this._output.value] = 1;
}
return output;
};
module.exports = Fold;
},{"./Transform":127,"vega-dataflow/src/ChangeSet":26,"vega-dataflow/src/Tuple":34,"vega-logging":41}],118:[function(require,module,exports){
(function (global){
var d3 = (typeof window !== "undefined" ? window.d3 : typeof global !== "undefined" ? global.d3 : null),
Tuple = require('vega-dataflow/src/Tuple'),
log = require('vega-logging'),
Transform = require('./Transform');
function Force(graph) {
Transform.prototype.init.call(this, graph);
Transform.addParameters(this, {
size: {type: 'array<value>', default: [500, 500]},
links: {type: 'data'},
linkDistance: {type: 'field|value', default: 20},
linkStrength: {type: 'field|value', default: 1},
charge: {type: 'field|value', default: -30},
chargeDistance: {type: 'field|value', default: Infinity},
iterations: {type: 'value', default: 500},
friction: {type: 'value', default: 0.9},
theta: {type: 'value', default: 0.8},
gravity: {type: 'value', default: 0.1},
alpha: {type: 'value', default: 0.1}
});
this._nodes = [];
this._links = [];
this._layout = d3.layout.force();
this._output = {
'x': 'layout_x',
'y': 'layout_y',
'px': 'layout_px',
'py': 'layout_py',
'fixed': 'layout_fixed',
'weight': 'layout_weight',
'source': '_source',
'target': '_target'
};
return this;
}
var prototype = (Force.prototype = Object.create(Transform.prototype));
prototype.constructor = Force;
prototype.transform = function(nodeInput) {
log.debug(nodeInput, ['force']);
// get variables
var linkInput = this.param('links').source.last(),
layout = this._layout,
output = this._output,
nodes = this._nodes,
links = this._links,
iter = this.param('iterations');
// process added nodes
nodeInput.add.forEach(function(n) {
nodes.push({tuple: n});
});
// process added edges
linkInput.add.forEach(function(l) {
var link = {
tuple: l,
source: nodes[l.source],
target: nodes[l.target]
};
Tuple.set(l, output.source, link.source.tuple);
Tuple.set(l, output.target, link.target.tuple);
links.push(link);
});
// TODO process 'mod' of edge source or target?
// configure layout
layout
.size(this.param('size'))
.linkDistance(this.param('linkDistance'))
.linkStrength(this.param('linkStrength'))
.charge(this.param('charge'))
.chargeDistance(this.param('chargeDistance'))
.friction(this.param('friction'))
.theta(this.param('theta'))
.gravity(this.param('gravity'))
.alpha(this.param('alpha'))
.nodes(nodes)
.links(links);
// run layout
layout.start();
for (var i=0; i<iter; ++i) {
layout.tick();
}
layout.stop();
// copy layout values to nodes
nodes.forEach(function(n) {
Tuple.set(n.tuple, output.x, n.x);
Tuple.set(n.tuple, output.y, n.y);
Tuple.set(n.tuple, output.px, n.px);
Tuple.set(n.tuple, output.py, n.py);
Tuple.set(n.tuple, output.fixed, n.fixed);
Tuple.set(n.tuple, output.weight, n.weight);
});
// process removed nodes
if (nodeInput.rem.length > 0) {
this._nodes = Tuple.idFilter(nodes, nodeInput.rem);
}
// process removed edges
if (linkInput.rem.length > 0) {
this.links = Tuple.idFilter(links, linkInput.rem);
}
// return changeset
nodeInput.fields[output.x] = 1;
nodeInput.fields[output.y] = 1;
return nodeInput;
};
module.exports = Force;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNyYy90cmFuc2Zvcm1zL0ZvcmNlLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EiLCJmaWxlIjoiZ2VuZXJhdGVkLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXNDb250ZW50IjpbInZhciBkMyA9ICh0eXBlb2Ygd2luZG93ICE9PSBcInVuZGVmaW5lZFwiID8gd2luZG93LmQzIDogdHlwZW9mIGdsb2JhbCAhPT0gXCJ1bmRlZmluZWRcIiA/IGdsb2JhbC5kMyA6IG51bGwpLFxuICAgIFR1cGxlID0gcmVxdWlyZSgndmVnYS1kYXRhZmxvdy9zcmMvVHVwbGUnKSxcbiAgICBsb2cgPSByZXF1aXJlKCd2ZWdhLWxvZ2dpbmcnKSxcbiAgICBUcmFuc2Zvcm0gPSByZXF1aXJlKCcuL1RyYW5zZm9ybScpO1xuXG5mdW5jdGlvbiBGb3JjZShncmFwaCkge1xuICBUcmFuc2Zvcm0ucHJvdG90eXBlLmluaXQuY2FsbCh0aGlzLCBncmFwaCk7XG4gIFRyYW5zZm9ybS5hZGRQYXJhbWV0ZXJzKHRoaXMsIHtcbiAgICBzaXplOiB7dHlwZTogJ2FycmF5PHZhbHVlPicsIGRlZmF1bHQ6IFs1MDAsIDUwMF19LFxuICAgIGxpbmtzOiB7dHlwZTogJ2RhdGEnfSxcbiAgICBsaW5rRGlzdGFuY2U6IHt0eXBlOiAnZmllbGR8dmFsdWUnLCBkZWZhdWx0OiAyMH0sXG4gICAgbGlua1N0cmVuZ3RoOiB7dHlwZTogJ2ZpZWxkfHZhbHVlJywgZGVmYXVsdDogMX0sXG4gICAgY2hhcmdlOiB7dHlwZTogJ2ZpZWxkfHZhbHVlJywgZGVmYXVsdDogLTMwfSxcbiAgICBjaGFyZ2VEaXN0YW5jZToge3R5cGU6ICdmaWVsZHx2YWx1ZScsIGRlZmF1bHQ6IEluZmluaXR5fSxcbiAgICBpdGVyYXRpb25zOiB7dHlwZTogJ3ZhbHVlJywgZGVmYXVsdDogNTAwfSxcbiAgICBmcmljdGlvbjoge3R5cGU6ICd2YWx1ZScsIGRlZmF1bHQ6IDAuOX0sXG4gICAgdGhldGE6IHt0eXBlOiAndmFsdWUnLCBkZWZhdWx0OiAwLjh9LFxuICAgIGdyYXZpdHk6IHt0eXBlOiAndmFsdWUnLCBkZWZhdWx0OiAwLjF9LFxuICAgIGFscGhhOiB7dHlwZTogJ3ZhbHVlJywgZGVmYXVsdDogMC4xfVxuICB9KTtcblxuICB0aGlzLl9ub2RlcyAgPSBbXTtcbiAgdGhpcy5fbGlua3MgPSBbXTtcbiAgdGhpcy5fbGF5b3V0ID0gZDMubGF5b3V0LmZvcmNlKCk7XG5cbiAgdGhpcy5fb3V0cHV0ID0ge1xuICAgICd4JzogJ2xheW91dF94JyxcbiAgICAneSc6ICdsYXlvdXRfeScsXG4gICAgJ3B4JzogJ2xheW91dF9weCcsXG4gICAgJ3B5JzogJ2xheW91dF9weScsXG4gICAgJ2ZpeGVkJzogJ2xheW91dF9maXhlZCcsXG4gICAgJ3dlaWdodCc6ICdsYXlvdXRfd2VpZ2h0JyxcbiAgICAnc291cmNlJzogJ19zb3VyY2UnLFxuICAgICd0YXJnZXQnOiAnX3RhcmdldCdcbiAgfTtcblxuICByZXR1cm4gdGhpcztcbn1cblxudmFyIHByb3RvdHlwZSA9IChGb3JjZS5wcm90b3R5cGUgPSBPYmplY3QuY3JlYXRlKFRyYW5zZm9ybS5wcm90b3R5cGUpKTtcbnByb3RvdHlwZS5jb25zdHJ1Y3RvciA9IEZvcmNlO1xuXG5wcm90b3R5cGUudHJhbnNmb3JtID0gZnVuY3Rpb24obm9kZUlucHV0KSB7XG4gIGxvZy5kZWJ1Zyhub2RlSW5wdXQsIFsnZm9yY2UnXSk7XG5cbiAgLy8gZ2V0IHZhcmlhYmxlc1xuICB2YXIgbGlua0lucHV0ID0gdGhpcy5wYXJhbSgnbGlua3MnKS5zb3VyY2UubGFzdCgpLFxuICAgICAgbGF5b3V0ID0gdGhpcy5fbGF5b3V0LFxuICAgICAgb3V0cHV0ID0gdGhpcy5fb3V0cHV0LFxuICAgICAgbm9kZXMgPSB0aGlzLl9ub2RlcyxcbiAgICAgIGxpbmtzID0gdGhpcy5fbGlua3MsXG4gICAgICBpdGVyID0gdGhpcy5wYXJhbSgnaXRlcmF0aW9ucycpO1xuXG4gIC8vIHByb2Nlc3MgYWRkZWQgbm9kZXNcbiAgbm9kZUlucHV0LmFkZC5mb3JFYWNoKGZ1bmN0aW9uKG4pIHtcbiAgICBub2Rlcy5wdXNoKHt0dXBsZTogbn0pO1xuICB9KTtcblxuICAvLyBwcm9jZXNzIGFkZGVkIGVkZ2VzXG4gIGxpbmtJbnB1dC5hZGQuZm9yRWFjaChmdW5jdGlvbihsKSB7XG4gICAgdmFyIGxpbmsgPSB7XG4gICAgICB0dXBsZTogbCxcbiAgICAgIHNvdXJjZTogbm9kZXNbbC5zb3VyY2VdLFxuICAgICAgdGFyZ2V0OiBub2Rlc1tsLnRhcmdldF1cbiAgICB9O1xuICAgIFR1cGxlLnNldChsLCBvdXRwdXQuc291cmNlLCBsaW5rLnNvdXJjZS50dXBsZSk7XG4gICAgVHVwbGUuc2V0KGwsIG91dHB1dC50YXJnZXQsIGxpbmsudGFyZ2V0LnR1cGxlKTtcbiAgICBsaW5rcy5wdXNoKGxpbmspO1xuICB9KTtcblxuICAvLyBUT0RPIHByb2Nlc3MgJ21vZCcgb2YgZWRnZSBzb3VyY2Ugb3IgdGFyZ2V0P1xuXG4gIC8vIGNvbmZpZ3VyZSBsYXlvdXRcbiAgbGF5b3V0XG4gICAgLnNpemUodGhpcy5wYXJhbSgnc2l6ZScpKVxuICAgIC5saW5rRGlzdGFuY2UodGhpcy5wYXJhbSgnbGlua0Rpc3RhbmNlJykpXG4gICAgLmxpbmtTdHJlbmd0aCh0aGlzLnBhcmFtKCdsaW5rU3RyZW5ndGgnKSlcbiAgICAuY2hhcmdlKHRoaXMucGFyYW0oJ2NoYXJnZScpKVxuICAgIC5jaGFyZ2VEaXN0YW5jZSh0aGlzLnBhcmFtKCdjaGFyZ2VEaXN0YW5jZScpKVxuICAgIC5mcmljdGlvbih0aGlzLnBhcmFtKCdmcmljdGlvbicpKVxuICAgIC50aGV0YSh0aGlzLnBhcmFtKCd0aGV0YScpKVxuICAgIC5ncmF2aXR5KHRoaXMucGFyYW0oJ2dyYXZpdHknKSlcbiAgICAuYWxwaGEodGhpcy5wYXJhbSgnYWxwaGEnKSlcbiAgICAubm9kZXMobm9kZXMpXG4gICAgLmxpbmtzKGxpbmtzKTtcblxuICAvLyBydW4gbGF5b3V0XG4gIGxheW91dC5zdGFydCgpO1xuICBmb3IgKHZhciBpPTA7IGk8aXRlcjsgKytpKSB7XG4gICAgbGF5b3V0LnRpY2soKTtcbiAgfVxuICBsYXlvdXQuc3RvcCgpO1xuXG4gIC8vIGNvcHkgbGF5b3V0IHZhbHVlcyB0byBub2Rlc1xuICBub2Rlcy5mb3JFYWNoKGZ1bmN0aW9uKG4pIHtcbiAgICBUdXBsZS5zZXQobi50dXBsZSwgb3V0cHV0LngsIG4ueCk7XG4gICAgVHVwbGUuc2V0KG4udHVwbGUsIG91dHB1dC55LCBuLnkpO1xuICAgIFR1cGxlLnNldChuLnR1cGxlLCBvdXRwdXQucHgsIG4ucHgpO1xuICAgIFR1cGxlLnNldChuLnR1cGxlLCBvdXRwdXQucHksIG4ucHkpO1xuICAgIFR1cGxlLnNldChuLnR1cGxlLCBvdXRwdXQuZml4ZWQsIG4uZml4ZWQpO1xuICAgIFR1cGxlLnNldChuLnR1cGxlLCBvdXRwdXQud2VpZ2h0LCBuLndlaWdodCk7XG4gIH0pO1xuXG4gIC8vIHByb2Nlc3MgcmVtb3ZlZCBub2Rlc1xuICBpZiAobm9kZUlucHV0LnJlbS5sZW5ndGggPiAwKSB7XG4gICAgdGhpcy5fbm9kZXMgPSBUdXBsZS5pZEZpbHRlcihub2Rlcywgbm9kZUlucHV0LnJlbSk7XG4gIH1cblxuICAvLyBwcm9jZXNzIHJlbW92ZWQgZWRnZXNcbiAgaWYgKGxpbmtJbnB1dC5yZW0ubGVuZ3RoID4gMCkge1xuICAgIHRoaXMubGlua3MgPSBUdXBsZS5pZEZpbHRlcihsaW5rcywgbGlua0lucHV0LnJlbSk7XG4gIH1cblxuICAvLyByZXR1cm4gY2hhbmdlc2V0XG4gIG5vZGVJbnB1dC5maWVsZHNbb3V0cHV0LnhdID0gMTtcbiAgbm9kZUlucHV0LmZpZWxkc1tvdXRwdXQueV0gPSAxO1xuICByZXR1cm4gbm9kZUlucHV0O1xufTtcblxubW9kdWxlLmV4cG9ydHMgPSBGb3JjZTsiXX0=
},{"./Transform":127,"vega-dataflow/src/Tuple":34,"vega-logging":41}],119:[function(require,module,exports){
var Tuple = require('vega-dataflow/src/Tuple'),
Deps = require('vega-dataflow/src/Dependencies'),
log = require('vega-logging'),
Transform = require('./Transform');
function Formula(graph) {
Transform.prototype.init.call(this, graph);
Transform.addParameters(this, {
field: {type: 'value'},
expr: {type: 'expr'}
});
return this;
}
var prototype = (Formula.prototype = Object.create(Transform.prototype));
prototype.constructor = Formula;
prototype.transform = function(input) {
log.debug(input, ['formulating']);
var g = this._graph,
field = this.param('field'),
expr = this.param('expr'),
signals = g.signalValues(this.dependency(Deps.SIGNALS));
function set(x) {
Tuple.set(x, field, expr(x, null, signals));
}
input.add.forEach(set);
if (this.reevaluate(input)) {
input.mod.forEach(set);
}
input.fields[field] = 1;
return input;
};
module.exports = Formula;
},{"./Transform":127,"vega-dataflow/src/Dependencies":29,"vega-dataflow/src/Tuple":34,"vega-logging":41}],120:[function(require,module,exports){
(function (global){
var d3 = (typeof window !== "undefined" ? window.d3 : typeof global !== "undefined" ? global.d3 : null),
util = require('datalib/src/util'),
Tuple = require('vega-dataflow/src/Tuple'),
log = require('vega-logging'),
Transform = require('./Transform');
function Geo(graph) {
Transform.prototype.init.call(this, graph);
Transform.addParameters(this, Geo.Parameters);
Transform.addParameters(this, {
lon: {type: 'field'},
lat: {type: 'field'}
});
this._output = {
'x': 'layout_x',
'y': 'layout_y'
};
return this;
}
Geo.Parameters = {
projection: {type: 'value', default: 'mercator'},
center: {type: 'array<value>'},
translate: {type: 'array<value>'},
rotate: {type: 'array<value>'},
scale: {type: 'value'},
precision: {type: 'value'},
clipAngle: {type: 'value'},
clipExtent: {type: 'value'}
};
Geo.d3Projection = function() {
var p = this.param('projection'),
param = Geo.Parameters,
proj, name, value;
if (p !== this._mode) {
this._mode = p;
this._projection = d3.geo[p]();
}
proj = this._projection;
for (name in param) {
if (name === 'projection' || !proj[name]) continue;
value = this.param(name);
if (value === undefined || (util.isArray(value) && value.length === 0)) {
continue;
}
if (value !== proj[name]()) {
proj[name](value);
}
}
return proj;
};
var prototype = (Geo.prototype = Object.create(Transform.prototype));
prototype.constructor = Geo;
prototype.transform = function(input) {
log.debug(input, ['geo']);
var output = this._output,
lon = this.param('lon').accessor,
lat = this.param('lat').accessor,
proj = Geo.d3Projection.call(this);
function set(t) {
var ll = [lon(t), lat(t)];
var xy = proj(ll);
Tuple.set(t, output.x, xy[0]);
Tuple.set(t, output.y, xy[1]);
}
input.add.forEach(set);
if (this.reevaluate(input)) {
input.mod.forEach(set);
input.rem.forEach(set);
}
input.fields[output.x] = 1;
input.fields[output.y] = 1;
return input;
};
module.exports = Geo;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNyYy90cmFuc2Zvcm1zL0dlby5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwiZmlsZSI6ImdlbmVyYXRlZC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgZDMgPSAodHlwZW9mIHdpbmRvdyAhPT0gXCJ1bmRlZmluZWRcIiA/IHdpbmRvdy5kMyA6IHR5cGVvZiBnbG9iYWwgIT09IFwidW5kZWZpbmVkXCIgPyBnbG9iYWwuZDMgOiBudWxsKSxcbiAgICB1dGlsID0gcmVxdWlyZSgnZGF0YWxpYi9zcmMvdXRpbCcpLFxuICAgIFR1cGxlID0gcmVxdWlyZSgndmVnYS1kYXRhZmxvdy9zcmMvVHVwbGUnKSxcbiAgICBsb2cgPSByZXF1aXJlKCd2ZWdhLWxvZ2dpbmcnKSxcbiAgICBUcmFuc2Zvcm0gPSByZXF1aXJlKCcuL1RyYW5zZm9ybScpO1xuXG5mdW5jdGlvbiBHZW8oZ3JhcGgpIHtcbiAgVHJhbnNmb3JtLnByb3RvdHlwZS5pbml0LmNhbGwodGhpcywgZ3JhcGgpO1xuICBUcmFuc2Zvcm0uYWRkUGFyYW1ldGVycyh0aGlzLCBHZW8uUGFyYW1ldGVycyk7XG4gIFRyYW5zZm9ybS5hZGRQYXJhbWV0ZXJzKHRoaXMsIHtcbiAgICBsb246IHt0eXBlOiAnZmllbGQnfSxcbiAgICBsYXQ6IHt0eXBlOiAnZmllbGQnfVxuICB9KTtcblxuICB0aGlzLl9vdXRwdXQgPSB7XG4gICAgJ3gnOiAnbGF5b3V0X3gnLFxuICAgICd5JzogJ2xheW91dF95J1xuICB9O1xuICByZXR1cm4gdGhpcztcbn1cblxuR2VvLlBhcmFtZXRlcnMgPSB7XG4gIHByb2plY3Rpb246IHt0eXBlOiAndmFsdWUnLCBkZWZhdWx0OiAnbWVyY2F0b3InfSxcbiAgY2VudGVyOiAgICAge3R5cGU6ICdhcnJheTx2YWx1ZT4nfSxcbiAgdHJhbnNsYXRlOiAge3R5cGU6ICdhcnJheTx2YWx1ZT4nfSxcbiAgcm90YXRlOiAgICAge3R5cGU6ICdhcnJheTx2YWx1ZT4nfSxcbiAgc2NhbGU6ICAgICAge3R5cGU6ICd2YWx1ZSd9LFxuICBwcmVjaXNpb246ICB7dHlwZTogJ3ZhbHVlJ30sXG4gIGNsaXBBbmdsZTogIHt0eXBlOiAndmFsdWUnfSxcbiAgY2xpcEV4dGVudDoge3R5cGU6ICd2YWx1ZSd9XG59O1xuXG5HZW8uZDNQcm9qZWN0aW9uID0gZnVuY3Rpb24oKSB7XG4gIHZhciBwID0gdGhpcy5wYXJhbSgncHJvamVjdGlvbicpLFxuICAgICAgcGFyYW0gPSBHZW8uUGFyYW1ldGVycyxcbiAgICAgIHByb2osIG5hbWUsIHZhbHVlO1xuXG4gIGlmIChwICE9PSB0aGlzLl9tb2RlKSB7XG4gICAgdGhpcy5fbW9kZSA9IHA7XG4gICAgdGhpcy5fcHJvamVjdGlvbiA9IGQzLmdlb1twXSgpO1xuICB9XG4gIHByb2ogPSB0aGlzLl9wcm9qZWN0aW9uO1xuXG4gIGZvciAobmFtZSBpbiBwYXJhbSkge1xuICAgIGlmIChuYW1lID09PSAncHJvamVjdGlvbicgfHwgIXByb2pbbmFtZV0pIGNvbnRpbnVlO1xuICAgIHZhbHVlID0gdGhpcy5wYXJhbShuYW1lKTtcbiAgICBpZiAodmFsdWUgPT09IHVuZGVmaW5lZCB8fCAodXRpbC5pc0FycmF5KHZhbHVlKSAmJiB2YWx1ZS5sZW5ndGggPT09IDApKSB7XG4gICAgICBjb250aW51ZTtcbiAgICB9XG4gICAgaWYgKHZhbHVlICE9PSBwcm9qW25hbWVdKCkpIHtcbiAgICAgIHByb2pbbmFtZV0odmFsdWUpO1xuICAgIH1cbiAgfVxuXG4gIHJldHVybiBwcm9qO1xufTtcblxudmFyIHByb3RvdHlwZSA9IChHZW8ucHJvdG90eXBlID0gT2JqZWN0LmNyZWF0ZShUcmFuc2Zvcm0ucHJvdG90eXBlKSk7XG5wcm90b3R5cGUuY29uc3RydWN0b3IgPSBHZW87XG5cbnByb3RvdHlwZS50cmFuc2Zvcm0gPSBmdW5jdGlvbihpbnB1dCkge1xuICBsb2cuZGVidWcoaW5wdXQsIFsnZ2VvJ10pO1xuXG4gIHZhciBvdXRwdXQgPSB0aGlzLl9vdXRwdXQsXG4gICAgICBsb24gPSB0aGlzLnBhcmFtKCdsb24nKS5hY2Nlc3NvcixcbiAgICAgIGxhdCA9IHRoaXMucGFyYW0oJ2xhdCcpLmFjY2Vzc29yLFxuICAgICAgcHJvaiA9IEdlby5kM1Byb2plY3Rpb24uY2FsbCh0aGlzKTtcblxuICBmdW5jdGlvbiBzZXQodCkge1xuICAgIHZhciBsbCA9IFtsb24odCksIGxhdCh0KV07XG4gICAgdmFyIHh5ID0gcHJvaihsbCk7XG4gICAgVHVwbGUuc2V0KHQsIG91dHB1dC54LCB4eVswXSk7XG4gICAgVHVwbGUuc2V0KHQsIG91dHB1dC55LCB4eVsxXSk7XG4gIH1cblxuICBpbnB1dC5hZGQuZm9yRWFjaChzZXQpO1xuICBpZiAodGhpcy5yZWV2YWx1YXRlKGlucHV0KSkge1xuICAgIGlucHV0Lm1vZC5mb3JFYWNoKHNldCk7XG4gICAgaW5wdXQucmVtLmZvckVhY2goc2V0KTtcbiAgfVxuXG4gIGlucHV0LmZpZWxkc1tvdXRwdXQueF0gPSAxO1xuICBpbnB1dC5maWVsZHNbb3V0cHV0LnldID0gMTtcbiAgcmV0dXJuIGlucHV0O1xufTtcblxubW9kdWxlLmV4cG9ydHMgPSBHZW87Il19
},{"./Transform":127,"datalib/src/util":20,"vega-dataflow/src/Tuple":34,"vega-logging":41}],121:[function(require,module,exports){
(function (global){
var d3 = (typeof window !== "undefined" ? window.d3 : typeof global !== "undefined" ? global.d3 : null),
util = require('datalib/src/util'),
Tuple = require('vega-dataflow/src/Tuple'),
log = require('vega-logging'),
Geo = require('./Geo'),
Transform = require('./Transform');
function GeoPath(graph) {
Transform.prototype.init.call(this, graph);
Transform.addParameters(this, Geo.Parameters);
Transform.addParameters(this, {
field: {type: 'field', default: null},
});
this._output = {
'path': 'layout_path'
};
return this;
}
var prototype = (GeoPath.prototype = Object.create(Transform.prototype));
prototype.constructor = GeoPath;
prototype.transform = function(input) {
log.debug(input, ['geopath']);
var output = this._output,
geojson = this.param('field').accessor || util.identity,
proj = Geo.d3Projection.call(this),
path = d3.geo.path().projection(proj);
function set(t) {
Tuple.set(t, output.path, path(geojson(t)));
}
input.add.forEach(set);
if (this.reevaluate(input)) {
input.mod.forEach(set);
input.rem.forEach(set);
}
input.fields[output.path] = 1;
return input;
};
module.exports = GeoPath;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNyYy90cmFuc2Zvcm1zL0dlb1BhdGguanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwiZmlsZSI6ImdlbmVyYXRlZC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgZDMgPSAodHlwZW9mIHdpbmRvdyAhPT0gXCJ1bmRlZmluZWRcIiA/IHdpbmRvdy5kMyA6IHR5cGVvZiBnbG9iYWwgIT09IFwidW5kZWZpbmVkXCIgPyBnbG9iYWwuZDMgOiBudWxsKSxcbiAgICB1dGlsID0gcmVxdWlyZSgnZGF0YWxpYi9zcmMvdXRpbCcpLFxuICAgIFR1cGxlID0gcmVxdWlyZSgndmVnYS1kYXRhZmxvdy9zcmMvVHVwbGUnKSxcbiAgICBsb2cgPSByZXF1aXJlKCd2ZWdhLWxvZ2dpbmcnKSxcbiAgICBHZW8gPSByZXF1aXJlKCcuL0dlbycpLFxuICAgIFRyYW5zZm9ybSA9IHJlcXVpcmUoJy4vVHJhbnNmb3JtJyk7XG5cbmZ1bmN0aW9uIEdlb1BhdGgoZ3JhcGgpIHtcbiAgVHJhbnNmb3JtLnByb3RvdHlwZS5pbml0LmNhbGwodGhpcywgZ3JhcGgpO1xuICBUcmFuc2Zvcm0uYWRkUGFyYW1ldGVycyh0aGlzLCBHZW8uUGFyYW1ldGVycyk7XG4gIFRyYW5zZm9ybS5hZGRQYXJhbWV0ZXJzKHRoaXMsIHtcbiAgICBmaWVsZDoge3R5cGU6ICdmaWVsZCcsIGRlZmF1bHQ6IG51bGx9LFxuICB9KTtcblxuICB0aGlzLl9vdXRwdXQgPSB7XG4gICAgJ3BhdGgnOiAnbGF5b3V0X3BhdGgnXG4gIH07XG4gIHJldHVybiB0aGlzO1xufVxuXG52YXIgcHJvdG90eXBlID0gKEdlb1BhdGgucHJvdG90eXBlID0gT2JqZWN0LmNyZWF0ZShUcmFuc2Zvcm0ucHJvdG90eXBlKSk7XG5wcm90b3R5cGUuY29uc3RydWN0b3IgPSBHZW9QYXRoO1xuXG5wcm90b3R5cGUudHJhbnNmb3JtID0gZnVuY3Rpb24oaW5wdXQpIHtcbiAgbG9nLmRlYnVnKGlucHV0LCBbJ2dlb3BhdGgnXSk7XG5cbiAgdmFyIG91dHB1dCA9IHRoaXMuX291dHB1dCxcbiAgICAgIGdlb2pzb24gPSB0aGlzLnBhcmFtKCdmaWVsZCcpLmFjY2Vzc29yIHx8IHV0aWwuaWRlbnRpdHksXG4gICAgICBwcm9qID0gR2VvLmQzUHJvamVjdGlvbi5jYWxsKHRoaXMpLFxuICAgICAgcGF0aCA9IGQzLmdlby5wYXRoKCkucHJvamVjdGlvbihwcm9qKTtcblxuICBmdW5jdGlvbiBzZXQodCkge1xuICAgIFR1cGxlLnNldCh0LCBvdXRwdXQucGF0aCwgcGF0aChnZW9qc29uKHQpKSk7XG4gIH1cblxuICBpbnB1dC5hZGQuZm9yRWFjaChzZXQpO1xuICBpZiAodGhpcy5yZWV2YWx1YXRlKGlucHV0KSkge1xuICAgIGlucHV0Lm1vZC5mb3JFYWNoKHNldCk7XG4gICAgaW5wdXQucmVtLmZvckVhY2goc2V0KTtcbiAgfVxuXG4gIGlucHV0LmZpZWxkc1tvdXRwdXQucGF0aF0gPSAxO1xuICByZXR1cm4gaW5wdXQ7XG59O1xuXG5tb2R1bGUuZXhwb3J0cyA9IEdlb1BhdGg7Il19
},{"./Geo":120,"./Transform":127,"datalib/src/util":20,"vega-dataflow/src/Tuple":34,"vega-logging":41}],122:[function(require,module,exports){
var Tuple = require('vega-dataflow/src/Tuple'),
log = require('vega-logging'),
Transform = require('./Transform');
function LinkPath(graph) {
Transform.prototype.init.call(this, graph);
Transform.addParameters(this, {
source: {type: 'field', default: '_source'},
target: {type: 'field', default: '_target'},
x: {type: 'field', default: 'layout_x'},
y: {type: 'field', default: 'layout_y'},
tension: {type: 'value', default: 0.2},
shape: {type: 'value', default: 'line'}
});
this._output = {'path': 'layout_path'};
return this;
}
var prototype = (LinkPath.prototype = Object.create(Transform.prototype));
prototype.constructor = LinkPath;
function line(d, source, target, x, y) {
var s = source(d), sx = x(s), sy = y(s),
t = target(d), tx = x(t), ty = y(t);
return 'M' + sx + ',' + sy +
'L' + tx + ',' + ty;
}
function curve(d, source, target, x, y, tension) {
var s = source(d), sx = x(s), sy = y(s),
t = target(d), tx = x(t), ty = y(t),
dx = tx - sx,
dy = ty - sy,
ix = tension * (dx + dy),
iy = tension * (dy - dx);
return 'M' + sx + ',' + sy +
'C' + (sx+ix) + ',' + (sy+iy) +
' ' + (tx+iy) + ',' + (ty-ix) +
' ' + tx + ',' + ty;
}
function diagonalX(d, source, target, x, y) {
var s = source(d), sx = x(s), sy = y(s),
t = target(d), tx = x(t), ty = y(t),
m = (sx + tx) / 2;
return 'M' + sx + ',' + sy +
'C' + m + ',' + sy +
' ' + m + ',' + ty +
' ' + tx + ',' + ty;
}
function diagonalY(d, source, target, x, y) {
var s = source(d), sx = x(s), sy = y(s),
t = target(d), tx = x(t), ty = y(t),
m = (sy + ty) / 2;
return 'M' + sx + ',' + sy +
'C' + sx + ',' + m +
' ' + tx + ',' + m +
' ' + tx + ',' + ty;
}
var shapes = {
line: line,
curve: curve,
diagonal: diagonalX,
diagonalX: diagonalX,
diagonalY: diagonalY
};
prototype.transform = function(input) {
log.debug(input, ['linkpath']);
var output = this._output,
shape = shapes[this.param('shape')] || shapes.line,
source = this.param('source').accessor,
target = this.param('target').accessor,
x = this.param('x').accessor,
y = this.param('y').accessor,
tension = this.param('tension');
function set(t) {
var path = shape(t, source, target, x, y, tension);
Tuple.set(t, output.path, path);
}
input.add.forEach(set);
if (this.reevaluate(input)) {
input.mod.forEach(set);
}
input.fields[output.path] = 1;
return input;
};
module.exports = LinkPath;
},{"./Transform":127,"vega-dataflow/src/Tuple":34,"vega-logging":41}],123:[function(require,module,exports){
var util = require('datalib/src/util'),
Deps = require('vega-dataflow/src/Dependencies'),
expr = require('../parse/expr');
var arrayType = /array/i,
dataType = /data/i,
fieldType = /field/i,
exprType = /expr/i,
valType = /value/i;
function Parameter(name, type, transform) {
this._name = name;
this._type = type;
this._transform = transform;
// If parameter is defined w/signals, it must be resolved
// on every pulse.
this._value = [];
this._accessors = [];
this._resolution = false;
this._signals = {};
}
var prototype = Parameter.prototype;
function get() {
var isArray = arrayType.test(this._type),
isData = dataType.test(this._type),
isField = fieldType.test(this._type);
var val = isArray ? this._value : this._value[0],
acc = isArray ? this._accessors : this._accessors[0];
if (!util.isValid(acc) && valType.test(this._type)) {
return val;
} else {
return isData ? { name: val, source: acc } :
isField ? { field: val, accessor: acc } : val;
}
}
prototype.get = function() {
var graph = this._transform._graph,
isData = dataType.test(this._type),
isField = fieldType.test(this._type),
s, idx, val;
// If we don't require resolution, return the value immediately.
if (!this._resolution) return get.call(this);
if (isData) {
this._accessors = this._value.map(function(v) { return graph.data(v); });
return get.call(this); // TODO: support signal as dataTypes
}
for (s in this._signals) {
idx = this._signals[s];
val = graph.signalRef(s);
if (isField) {
this._accessors[idx] = this._value[idx] != val ?
util.accessor(val) : this._accessors[idx];
}
this._value[idx] = val;
}
return get.call(this);
};
prototype.set = function(value) {
var p = this,
isExpr = exprType.test(this._type),
isData = dataType.test(this._type),
isField = fieldType.test(this._type);
this._value = util.array(value).map(function(v, i) {
if (util.isString(v)) {
if (isExpr) {
var e = expr(v);
p._transform.dependency(Deps.FIELDS, e.fields);
p._transform.dependency(Deps.SIGNALS, e.globals);
return e.fn;
} else if (isField) { // Backwards compatibility
p._accessors[i] = util.accessor(v);
p._transform.dependency(Deps.FIELDS, v);
} else if (isData) {
p._resolution = true;
p._transform.dependency(Deps.DATA, v);
}
return v;
} else if (v.value !== undefined) {
return v.value;
} else if (v.field !== undefined) {
p._accessors[i] = util.accessor(v.field);
p._transform.dependency(Deps.FIELDS, v.field);
return v.field;
} else if (v.signal !== undefined) {
p._resolution = true;
p._signals[v.signal] = i;
p._transform.dependency(Deps.SIGNALS, v.signal);
return v.signal;
}
return v;
});
return p._transform;
};
module.exports = Parameter;
},{"../parse/expr":88,"datalib/src/util":20,"vega-dataflow/src/Dependencies":29}],124:[function(require,module,exports){
(function (global){
var d3 = (typeof window !== "undefined" ? window.d3 : typeof global !== "undefined" ? global.d3 : null),
gen = require('datalib/src/generate'),
Tuple = require('vega-dataflow/src/Tuple'),
log = require('vega-logging'),
Transform = require('./Transform'),
BatchTransform = require('./BatchTransform');
function Pie(graph) {
BatchTransform.prototype.init.call(this, graph);
Transform.addParameters(this, {
field: {type: "field", default: null},
startAngle: {type: "value", default: 0},
endAngle: {type: "value", default: 2 * Math.PI},
sort: {type: "value", default: false}
});
this._output = {
"start": "layout_start",
"end": "layout_end",
"mid": "layout_mid"
};
return this;
}
var prototype = (Pie.prototype = Object.create(BatchTransform.prototype));
prototype.constructor = Pie;
function ones() { return 1; }
prototype.batchTransform = function(input, data) {
log.debug(input, ['pie']);
var output = this._output,
field = this.param("field").accessor || ones,
start = this.param("startAngle"),
stop = this.param("endAngle"),
sort = this.param("sort");
var values = data.map(field),
a = start,
k = (stop - start) / d3.sum(values),
index = gen.range(data.length),
i, t, v;
if (sort) {
index.sort(function(a, b) {
return values[a] - values[b];
});
}
for (i=0; i<index.length; ++i) {
t = data[index[i]];
v = values[index[i]];
Tuple.set(t, output.start, a);
Tuple.set(t, output.mid, (a + 0.5 * v * k));
Tuple.set(t, output.end, (a += v * k));
}
input.fields[output.start] = 1;
input.fields[output.end] = 1;
input.fields[output.mid] = 1;
return input;
};
module.exports = Pie;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNyYy90cmFuc2Zvcm1zL1BpZS5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwiZmlsZSI6ImdlbmVyYXRlZC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgZDMgPSAodHlwZW9mIHdpbmRvdyAhPT0gXCJ1bmRlZmluZWRcIiA/IHdpbmRvdy5kMyA6IHR5cGVvZiBnbG9iYWwgIT09IFwidW5kZWZpbmVkXCIgPyBnbG9iYWwuZDMgOiBudWxsKSxcbiAgICBnZW4gID0gcmVxdWlyZSgnZGF0YWxpYi9zcmMvZ2VuZXJhdGUnKSxcbiAgICBUdXBsZSA9IHJlcXVpcmUoJ3ZlZ2EtZGF0YWZsb3cvc3JjL1R1cGxlJyksXG4gICAgbG9nID0gcmVxdWlyZSgndmVnYS1sb2dnaW5nJyksXG4gICAgVHJhbnNmb3JtID0gcmVxdWlyZSgnLi9UcmFuc2Zvcm0nKSxcbiAgICBCYXRjaFRyYW5zZm9ybSA9IHJlcXVpcmUoJy4vQmF0Y2hUcmFuc2Zvcm0nKTtcblxuZnVuY3Rpb24gUGllKGdyYXBoKSB7XG4gIEJhdGNoVHJhbnNmb3JtLnByb3RvdHlwZS5pbml0LmNhbGwodGhpcywgZ3JhcGgpO1xuICBUcmFuc2Zvcm0uYWRkUGFyYW1ldGVycyh0aGlzLCB7XG4gICAgZmllbGQ6ICAgICAge3R5cGU6IFwiZmllbGRcIiwgZGVmYXVsdDogbnVsbH0sXG4gICAgc3RhcnRBbmdsZToge3R5cGU6IFwidmFsdWVcIiwgZGVmYXVsdDogMH0sXG4gICAgZW5kQW5nbGU6ICAge3R5cGU6IFwidmFsdWVcIiwgZGVmYXVsdDogMiAqIE1hdGguUEl9LFxuICAgIHNvcnQ6ICAgICAgIHt0eXBlOiBcInZhbHVlXCIsIGRlZmF1bHQ6IGZhbHNlfVxuICB9KTtcblxuICB0aGlzLl9vdXRwdXQgPSB7XG4gICAgXCJzdGFydFwiOiBcImxheW91dF9zdGFydFwiLFxuICAgIFwiZW5kXCI6ICAgXCJsYXlvdXRfZW5kXCIsXG4gICAgXCJtaWRcIjogICBcImxheW91dF9taWRcIlxuICB9O1xuXG4gIHJldHVybiB0aGlzO1xufVxuXG52YXIgcHJvdG90eXBlID0gKFBpZS5wcm90b3R5cGUgPSBPYmplY3QuY3JlYXRlKEJhdGNoVHJhbnNmb3JtLnByb3RvdHlwZSkpO1xucHJvdG90eXBlLmNvbnN0cnVjdG9yID0gUGllO1xuXG5mdW5jdGlvbiBvbmVzKCkgeyByZXR1cm4gMTsgfVxuXG5wcm90b3R5cGUuYmF0Y2hUcmFuc2Zvcm0gPSBmdW5jdGlvbihpbnB1dCwgZGF0YSkge1xuICBsb2cuZGVidWcoaW5wdXQsIFsncGllJ10pO1xuXG4gIHZhciBvdXRwdXQgPSB0aGlzLl9vdXRwdXQsXG4gICAgICBmaWVsZCA9IHRoaXMucGFyYW0oXCJmaWVsZFwiKS5hY2Nlc3NvciB8fCBvbmVzLFxuICAgICAgc3RhcnQgPSB0aGlzLnBhcmFtKFwic3RhcnRBbmdsZVwiKSxcbiAgICAgIHN0b3AgPSB0aGlzLnBhcmFtKFwiZW5kQW5nbGVcIiksXG4gICAgICBzb3J0ID0gdGhpcy5wYXJhbShcInNvcnRcIik7XG5cbiAgdmFyIHZhbHVlcyA9IGRhdGEubWFwKGZpZWxkKSxcbiAgICAgIGEgPSBzdGFydCxcbiAgICAgIGsgPSAoc3RvcCAtIHN0YXJ0KSAvIGQzLnN1bSh2YWx1ZXMpLFxuICAgICAgaW5kZXggPSBnZW4ucmFuZ2UoZGF0YS5sZW5ndGgpLFxuICAgICAgaSwgdCwgdjtcblxuICBpZiAoc29ydCkge1xuICAgIGluZGV4LnNvcnQoZnVuY3Rpb24oYSwgYikge1xuICAgICAgcmV0dXJuIHZhbHVlc1thXSAtIHZhbHVlc1tiXTtcbiAgICB9KTtcbiAgfVxuXG4gIGZvciAoaT0wOyBpPGluZGV4Lmxlbmd0aDsgKytpKSB7XG4gICAgdCA9IGRhdGFbaW5kZXhbaV1dO1xuICAgIHYgPSB2YWx1ZXNbaW5kZXhbaV1dO1xuICAgIFR1cGxlLnNldCh0LCBvdXRwdXQuc3RhcnQsIGEpO1xuICAgIFR1cGxlLnNldCh0LCBvdXRwdXQubWlkLCAoYSArIDAuNSAqIHYgKiBrKSk7XG4gICAgVHVwbGUuc2V0KHQsIG91dHB1dC5lbmQsIChhICs9IHYgKiBrKSk7XG4gIH1cblxuICBpbnB1dC5maWVsZHNbb3V0cHV0LnN0YXJ0XSA9IDE7XG4gIGlucHV0LmZpZWxkc1tvdXRwdXQuZW5kXSA9IDE7XG4gIGlucHV0LmZpZWxkc1tvdXRwdXQubWlkXSA9IDE7XG4gIHJldHVybiBpbnB1dDtcbn07XG5cbm1vZHVsZS5leHBvcnRzID0gUGllOyJdfQ==
},{"./BatchTransform":111,"./Transform":127,"datalib/src/generate":7,"vega-dataflow/src/Tuple":34,"vega-logging":41}],125:[function(require,module,exports){
var util = require('datalib/src/util'),
log = require('vega-logging'),
Transform = require('./Transform');
function Sort(graph) {
Transform.prototype.init.call(this, graph);
Transform.addParameters(this, {by: {type: 'array<field>'} });
this.router(true);
}
var prototype = (Sort.prototype = Object.create(Transform.prototype));
prototype.constructor = Sort;
prototype.transform = function(input) {
log.debug(input, ['sorting']);
if (input.add.length || input.mod.length || input.rem.length) {
input.sort = util.comparator(this.param('by').field);
}
return input;
};
module.exports = Sort;
},{"./Transform":127,"datalib/src/util":20,"vega-logging":41}],126:[function(require,module,exports){
var util = require('datalib/src/util'),
Tuple = require('vega-dataflow/src/Tuple'),
log = require('vega-logging'),
Transform = require('./Transform'),
BatchTransform = require('./BatchTransform');
function Stack(graph) {
BatchTransform.prototype.init.call(this, graph);
Transform.addParameters(this, {
groupby: {type: 'array<field>'},
sortby: {type: 'array<field>'},
field: {type: 'field'},
offset: {type: 'value', default: 'zero'}
});
this._output = {
'start': 'layout_start',
'end': 'layout_end',
'mid': 'layout_mid'
};
return this;
}
var prototype = (Stack.prototype = Object.create(BatchTransform.prototype));
prototype.constructor = Stack;
prototype.batchTransform = function(input, data) {
log.debug(input, ['stacking']);
var groupby = this.param('groupby').accessor,
sortby = util.comparator(this.param('sortby').field),
field = this.param('field').accessor,
offset = this.param('offset'),
output = this._output;
// partition, sum, and sort the stack groups
var groups = partition(data, groupby, sortby, field);
// compute stack layouts per group
for (var i=0, max=groups.max; i<groups.length; ++i) {
var group = groups[i],
sum = group.sum,
off = offset==='center' ? (max - sum)/2 : 0,
scale = offset==='normalize' ? (1/sum) : 1,
j, x, a, b = off, v = 0;
// set stack coordinates for each datum in group
for (j=0; j<group.length; ++j) {
x = group[j];
a = b; // use previous value for start point
v += field(x);
b = scale * v + off; // compute end point
Tuple.set(x, output.start, a);
Tuple.set(x, output.end, b);
Tuple.set(x, output.mid, 0.5 * (a + b));
}
}
input.fields[output.start] = 1;
input.fields[output.end] = 1;
input.fields[output.mid] = 1;
return input;
};
function partition(data, groupby, sortby, field) {
var groups = [],
get = function(f) { return f(x); },
map, i, x, k, g, s, max;
// partition data points into stack groups
if (groupby == null) {
groups.push(data.slice());
} else {
for (map={}, i=0; i<data.length; ++i) {
x = data[i];
k = groupby.map(get);
g = map[k] || (groups.push(map[k] = []), map[k]);
g.push(x);
}
}
// compute sums of groups, sort groups as needed
for (k=0, max=0; k<groups.length; ++k) {
g = groups[k];
for (i=0, s=0; i<g.length; ++i) {
s += field(g[i]);
}
g.sum = s;
if (s > max) max = s;
if (sortby != null) g.sort(sortby);
}
groups.max = max;
return groups;
}
module.exports = Stack;
},{"./BatchTransform":111,"./Transform":127,"datalib/src/util":20,"vega-dataflow/src/Tuple":34,"vega-logging":41}],127:[function(require,module,exports){
var Base = require('vega-dataflow/src/Node').prototype, // jshint ignore:line
Deps = require('vega-dataflow/src/Dependencies'),
Parameter = require('./Parameter');
function Transform(graph) {
if (graph) Base.init.call(this, graph);
}
Transform.addParameters = function(proto, params) {
proto._parameters = proto._parameters || {};
for (var name in params) {
var p = params[name],
param = new Parameter(name, p.type, proto);
proto._parameters[name] = param;
if (p.type === 'custom') {
if (p.set) param.set = p.set.bind(param);
if (p.get) param.get = p.get.bind(param);
}
if (p.hasOwnProperty('default')) param.set(p.default);
}
};
var prototype = (Transform.prototype = Object.create(Base));
prototype.constructor = Transform;
prototype.param = function(name, value) {
var param = this._parameters[name];
return (param === undefined) ? this :
(arguments.length === 1) ? param.get() : param.set(value);
};
// Perform transformation. Subclasses should override.
prototype.transform = function(input/*, reset */) {
return input;
};
prototype.evaluate = function(input) {
// Many transforms store caches that must be invalidated if
// a signal value has changed.
var reset = this._stamp < input.stamp &&
this.dependency(Deps.SIGNALS).some(function(s) {
return !!input.signals[s];
});
return this.transform(input, reset);
};
prototype.output = function(map) {
for (var key in this._output) {
if (map[key] !== undefined) {
this._output[key] = map[key];
}
}
return this;
};
module.exports = Transform;
},{"./Parameter":123,"vega-dataflow/src/Dependencies":29,"vega-dataflow/src/Node":31}],128:[function(require,module,exports){
(function (global){
var d3 = (typeof window !== "undefined" ? window.d3 : typeof global !== "undefined" ? global.d3 : null),
util = require('datalib/src/util'),
Tuple = require('vega-dataflow/src/Tuple'),
log = require('vega-logging'),
Transform = require('./Transform'),
BatchTransform = require('./BatchTransform');
var defaultRatio = 0.5 * (1 + Math.sqrt(5));
function Treemap(graph) {
BatchTransform.prototype.init.call(this, graph);
Transform.addParameters(this, {
// hierarchy parameters
sort: {type: 'array<field>', default: ['-value']},
children: {type: 'field', default: 'children'},
field: {type: 'field', default: 'value'},
// treemap parameters
size: {type: 'array<value>', default: [500, 500]},
round: {type: 'value', default: true},
sticky: {type: 'value', default: false},
ratio: {type: 'value', default: defaultRatio},
padding: {type: 'value', default: null},
mode: {type: 'value', default: 'squarify'}
});
this._layout = d3.layout.treemap();
this._output = {
'x': 'layout_x',
'y': 'layout_y',
'width': 'layout_width',
'height': 'layout_height',
'depth': 'layout_depth',
};
return this;
}
var prototype = (Treemap.prototype = Object.create(BatchTransform.prototype));
prototype.constructor = Treemap;
prototype.batchTransform = function(input, data) {
log.debug(input, ['treemap']);
// get variables
var layout = this._layout,
output = this._output;
// configure layout
layout
.sort(util.comparator(this.param('sort').field))
.children(this.param('children').accessor)
.value(this.param('field').accessor)
.size(this.param('size'))
.round(this.param('round'))
.sticky(this.param('sticky'))
.ratio(this.param('ratio'))
.padding(this.param('padding'))
.mode(this.param('mode'))
.nodes(data[0]);
// copy layout values to nodes
data.forEach(function(n) {
Tuple.set(n, output.x, n.x);
Tuple.set(n, output.y, n.y);
Tuple.set(n, output.width, n.dx);
Tuple.set(n, output.height, n.dy);
Tuple.set(n, output.depth, n.depth);
});
// return changeset
input.fields[output.x] = 1;
input.fields[output.y] = 1;
input.fields[output.width] = 1;
input.fields[output.height] = 1;
return input;
};
module.exports = Treemap;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNyYy90cmFuc2Zvcm1zL1RyZWVtYXAuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSIsImZpbGUiOiJnZW5lcmF0ZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlc0NvbnRlbnQiOlsidmFyIGQzID0gKHR5cGVvZiB3aW5kb3cgIT09IFwidW5kZWZpbmVkXCIgPyB3aW5kb3cuZDMgOiB0eXBlb2YgZ2xvYmFsICE9PSBcInVuZGVmaW5lZFwiID8gZ2xvYmFsLmQzIDogbnVsbCksXG4gICAgdXRpbCA9IHJlcXVpcmUoJ2RhdGFsaWIvc3JjL3V0aWwnKSxcbiAgICBUdXBsZSA9IHJlcXVpcmUoJ3ZlZ2EtZGF0YWZsb3cvc3JjL1R1cGxlJyksXG4gICAgbG9nID0gcmVxdWlyZSgndmVnYS1sb2dnaW5nJyksXG4gICAgVHJhbnNmb3JtID0gcmVxdWlyZSgnLi9UcmFuc2Zvcm0nKSxcbiAgICBCYXRjaFRyYW5zZm9ybSA9IHJlcXVpcmUoJy4vQmF0Y2hUcmFuc2Zvcm0nKTtcblxudmFyIGRlZmF1bHRSYXRpbyA9IDAuNSAqICgxICsgTWF0aC5zcXJ0KDUpKTtcblxuZnVuY3Rpb24gVHJlZW1hcChncmFwaCkge1xuICBCYXRjaFRyYW5zZm9ybS5wcm90b3R5cGUuaW5pdC5jYWxsKHRoaXMsIGdyYXBoKTtcbiAgVHJhbnNmb3JtLmFkZFBhcmFtZXRlcnModGhpcywge1xuICAgIC8vIGhpZXJhcmNoeSBwYXJhbWV0ZXJzXG4gICAgc29ydDoge3R5cGU6ICdhcnJheTxmaWVsZD4nLCBkZWZhdWx0OiBbJy12YWx1ZSddfSxcbiAgICBjaGlsZHJlbjoge3R5cGU6ICdmaWVsZCcsIGRlZmF1bHQ6ICdjaGlsZHJlbid9LFxuICAgIGZpZWxkOiB7dHlwZTogJ2ZpZWxkJywgZGVmYXVsdDogJ3ZhbHVlJ30sXG4gICAgLy8gdHJlZW1hcCBwYXJhbWV0ZXJzXG4gICAgc2l6ZToge3R5cGU6ICdhcnJheTx2YWx1ZT4nLCBkZWZhdWx0OiBbNTAwLCA1MDBdfSxcbiAgICByb3VuZDoge3R5cGU6ICd2YWx1ZScsIGRlZmF1bHQ6IHRydWV9LFxuICAgIHN0aWNreToge3R5cGU6ICd2YWx1ZScsIGRlZmF1bHQ6IGZhbHNlfSxcbiAgICByYXRpbzoge3R5cGU6ICd2YWx1ZScsIGRlZmF1bHQ6IGRlZmF1bHRSYXRpb30sXG4gICAgcGFkZGluZzoge3R5cGU6ICd2YWx1ZScsIGRlZmF1bHQ6IG51bGx9LFxuICAgIG1vZGU6IHt0eXBlOiAndmFsdWUnLCBkZWZhdWx0OiAnc3F1YXJpZnknfVxuICB9KTtcblxuICB0aGlzLl9sYXlvdXQgPSBkMy5sYXlvdXQudHJlZW1hcCgpO1xuXG4gIHRoaXMuX291dHB1dCA9IHtcbiAgICAneCc6ICAgICAgJ2xheW91dF94JyxcbiAgICAneSc6ICAgICAgJ2xheW91dF95JyxcbiAgICAnd2lkdGgnOiAgJ2xheW91dF93aWR0aCcsXG4gICAgJ2hlaWdodCc6ICdsYXlvdXRfaGVpZ2h0JyxcbiAgICAnZGVwdGgnOiAgJ2xheW91dF9kZXB0aCcsXG4gIH07XG4gIHJldHVybiB0aGlzO1xufVxuXG52YXIgcHJvdG90eXBlID0gKFRyZWVtYXAucHJvdG90eXBlID0gT2JqZWN0LmNyZWF0ZShCYXRjaFRyYW5zZm9ybS5wcm90b3R5cGUpKTtcbnByb3RvdHlwZS5jb25zdHJ1Y3RvciA9IFRyZWVtYXA7XG5cbnByb3RvdHlwZS5iYXRjaFRyYW5zZm9ybSA9IGZ1bmN0aW9uKGlucHV0LCBkYXRhKSB7XG4gIGxvZy5kZWJ1ZyhpbnB1dCwgWyd0cmVlbWFwJ10pO1xuXG4gIC8vIGdldCB2YXJpYWJsZXNcbiAgdmFyIGxheW91dCA9IHRoaXMuX2xheW91dCxcbiAgICAgIG91dHB1dCA9IHRoaXMuX291dHB1dDtcblxuICAvLyBjb25maWd1cmUgbGF5b3V0XG4gIGxheW91dFxuICAgIC5zb3J0KHV0aWwuY29tcGFyYXRvcih0aGlzLnBhcmFtKCdzb3J0JykuZmllbGQpKVxuICAgIC5jaGlsZHJlbih0aGlzLnBhcmFtKCdjaGlsZHJlbicpLmFjY2Vzc29yKVxuICAgIC52YWx1ZSh0aGlzLnBhcmFtKCdmaWVsZCcpLmFjY2Vzc29yKVxuICAgIC5zaXplKHRoaXMucGFyYW0oJ3NpemUnKSlcbiAgICAucm91bmQodGhpcy5wYXJhbSgncm91bmQnKSlcbiAgICAuc3RpY2t5KHRoaXMucGFyYW0oJ3N0aWNreScpKVxuICAgIC5yYXRpbyh0aGlzLnBhcmFtKCdyYXRpbycpKVxuICAgIC5wYWRkaW5nKHRoaXMucGFyYW0oJ3BhZGRpbmcnKSlcbiAgICAubW9kZSh0aGlzLnBhcmFtKCdtb2RlJykpXG4gICAgLm5vZGVzKGRhdGFbMF0pO1xuXG4gIC8vIGNvcHkgbGF5b3V0IHZhbHVlcyB0byBub2Rlc1xuICBkYXRhLmZvckVhY2goZnVuY3Rpb24obikge1xuICAgIFR1cGxlLnNldChuLCBvdXRwdXQueCwgbi54KTtcbiAgICBUdXBsZS5zZXQobiwgb3V0cHV0LnksIG4ueSk7XG4gICAgVHVwbGUuc2V0KG4sIG91dHB1dC53aWR0aCwgbi5keCk7XG4gICAgVHVwbGUuc2V0KG4sIG91dHB1dC5oZWlnaHQsIG4uZHkpO1xuICAgIFR1cGxlLnNldChuLCBvdXRwdXQuZGVwdGgsIG4uZGVwdGgpO1xuICB9KTtcblxuICAvLyByZXR1cm4gY2hhbmdlc2V0XG4gIGlucHV0LmZpZWxkc1tvdXRwdXQueF0gPSAxO1xuICBpbnB1dC5maWVsZHNbb3V0cHV0LnldID0gMTtcbiAgaW5wdXQuZmllbGRzW291dHB1dC53aWR0aF0gPSAxO1xuICBpbnB1dC5maWVsZHNbb3V0cHV0LmhlaWdodF0gPSAxO1xuICByZXR1cm4gaW5wdXQ7XG59O1xuXG5tb2R1bGUuZXhwb3J0cyA9IFRyZWVtYXA7Il19
},{"./BatchTransform":111,"./Transform":127,"datalib/src/util":20,"vega-dataflow/src/Tuple":34,"vega-logging":41}],129:[function(require,module,exports){
var util = require('datalib/src/util'),
Collector = require('vega-dataflow/src/Collector'),
log = require('vega-logging'),
Transform = require('./Transform');
function Zip(graph) {
Transform.prototype.init.call(this, graph);
Transform.addParameters(this, {
with: {type: 'data'},
as: {type: 'value'},
key: {type: 'field', default: 'data'},
withKey: {type: 'field', default: null},
default: {type: 'value'}
});
this._map = {};
this._collector = new Collector(graph);
this._lastJoin = 0;
return this.revises(true);
}
var prototype = (Zip.prototype = Object.create(Transform.prototype));
prototype.constructor = Zip;
function mp(k) {
return this._map[k] || (this._map[k] = []);
}
prototype.transform = function(input) {
log.debug(input, ['zipping']);
var w = this.param('with'),
wds = w.source,
woutput = wds.last(),
wdata = wds.values(),
key = this.param('key'),
withKey = this.param('withKey'),
as = this.param('as'),
dflt = this.param('default'),
map = mp.bind(this),
rem = {};
if (withKey.field) {
if (woutput && woutput.stamp > this._lastJoin) {
woutput.rem.forEach(function(x) {
var m = map(withKey.accessor(x));
if (m[0]) m[0].forEach(function(d) { d[as] = dflt; });
m[1] = null;
});
woutput.add.forEach(function(x) {
var m = map(withKey.accessor(x));
if (m[0]) m[0].forEach(function(d) { d[as] = x; });
m[1] = x;
});
// Only process woutput.mod tuples if the join key has changed.
// Other field updates will auto-propagate via prototype.
if (woutput.fields[withKey.field]) {
woutput.mod.forEach(function(x) {
var prev;
if (!x._prev || (prev = withKey.accessor(x._prev)) === undefined) return;
var prevm = map(prev);
if (prevm[0]) prevm[0].forEach(function(d) { d[as] = dflt; });
prevm[1] = null;
var m = map(withKey.accessor(x));
if (m[0]) m[0].forEach(function(d) { d[as] = x; });
m[1] = x;
});
}
this._lastJoin = woutput.stamp;
}
input.add.forEach(function(x) {
var m = map(key.accessor(x));
x[as] = m[1] || dflt;
(m[0]=m[0]||[]).push(x);
});
input.rem.forEach(function(x) {
var k = key.accessor(x);
(rem[k]=rem[k]||{})[x._id] = 1;
});
if (input.fields[key.field]) {
input.mod.forEach(function(x) {
var prev;
if (!x._prev || (prev = key.accessor(x._prev)) === undefined) return;
var m = map(key.accessor(x));
x[as] = m[1] || dflt;
(m[0]=m[0]||[]).push(x);
(rem[prev]=rem[prev]||{})[x._id] = 1;
});
}
util.keys(rem).forEach(function(k) {
var m = map(k);
if (!m[0]) return;
m[0] = m[0].filter(function(x) { return rem[k][x._id] !== 1; });
});
} else {
// We only need to run a non-key-join again if we've got any add/rem
// on input or woutput
if (!(input.add.length || input.rem.length ||
woutput.add.length || woutput.rem.length)) {
return input;
}
// If we don't have a key-join, then we need to materialize both
// data sources to iterate through them.
this._collector.evaluate(input);
var data = this._collector.data(),
wlen = wdata.length, i;
for (i=0; i<data.length; i++) {
data[i][as] = wdata[i%wlen];
}
}
input.fields[as] = 1;
return input;
};
module.exports = Zip;
},{"./Transform":127,"datalib/src/util":20,"vega-dataflow/src/Collector":27,"vega-logging":41}],130:[function(require,module,exports){
module.exports = {
aggregate: require('./Aggregate'),
bin: require('./Bin'),
cross: require('./Cross'),
linkpath: require('./LinkPath'),
facet: require('./Facet'),
filter: require('./Filter'),
fold: require('./Fold'),
force: require('./Force'),
formula: require('./Formula'),
geo: require('./Geo'),
geopath: require('./GeoPath'),
pie: require('./Pie'),
sort: require('./Sort'),
stack: require('./Stack'),
treemap: require('./Treemap'),
zip: require('./Zip')
};
},{"./Aggregate":110,"./Bin":112,"./Cross":113,"./Facet":114,"./Filter":116,"./Fold":117,"./Force":118,"./Formula":119,"./Geo":120,"./GeoPath":121,"./LinkPath":122,"./Pie":124,"./Sort":125,"./Stack":126,"./Treemap":128,"./Zip":129}]},{},[1])(1)
});
//# sourceMappingURL=vega.js.map
|
clients/packages/admin-client/src/mobilizations/components/list/items/created-at.js
|
nossas/bonde-client
|
import PropTypes from 'prop-types'
import React from 'react'
import { FormattedMessage } from 'react-intl'
/* eslint-disable camelcase */
const CreatedAt = ({ created_at, createdAt }) => {
const date = new Date(Date.parse(created_at || createdAt))
return (
<div className='created-at px3 col col-2'>
{`${`${date.getDate()}`.padStart(2, '0')}`}
{`/${`${date.getMonth() + 1}`.padStart(2, '0')}`}
{`/${date.getFullYear()}`}
</div>
)
}
/* eslint-disable camelcase */
CreatedAt.propTypes = {
created_at: PropTypes.string,
createdAt: PropTypes.string
}
export default CreatedAt
const Header = () => (
<div className='created-at-header px3 col col-2'>
<FormattedMessage
id='mobilizations.components--list.items.created-at.header.text'
defaultMessage='Criada em'
/>
</div>
)
CreatedAt.Header = Header
|
examples/huge-apps/components/Dashboard.js
|
SpainTrain/react-router
|
import React from 'react';
import { Link } from 'react-router';
class Dashboard extends React.Component {
render () {
let { courses } = this.props;
return (
<div>
<h2>Super Scalable Apps</h2>
<p>
Open the network tab as you navigate. Notice that only the amount of
your app that is required is actually downloaded as you navigate
around. Even the route configuration objects are loaded on the fly.
This way, a new route added deep in your app will not affect the
initial bundle of your application.
</p>
<h2>Courses</h2>{' '}
<ul>
{courses.map(course => (
<li key={course.id}>
<Link to={`/course/${course.id}`}>{course.name}</Link>
</li>
))}
</ul>
</div>
);
}
}
export default Dashboard;
|
src/routes/notFound/index.js
|
jimmykobe1171/chatbotta
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Layout from '../../components/Layout';
import NotFound from './NotFound';
const title = 'Page Not Found';
export default {
path: '*',
action() {
return {
title,
component: <Layout><NotFound title={title} /></Layout>,
status: 404,
};
},
};
|
fields/types/date/DateField.js
|
helloworld3q3q/keystone
|
import DateInput from '../../components/DateInput';
import Field from '../Field';
import moment from 'moment';
import React from 'react';
import { Button, FormInput } from '../../../admin/client/App/elemental';
import { InputGroup } from 'elemental';
/*
TODO: Implement yearRange Prop, or deprecate for max / min values (better)
*/
const DEFAULT_INPUT_FORMAT = 'YYYY-MM-DD';
const DEFAULT_FORMAT_STRING = 'Do MMM YYYY';
module.exports = Field.create({
displayName: 'DateField',
statics: {
type: 'Date',
},
propTypes: {
formatString: React.PropTypes.string,
inputFormat: React.PropTypes.string,
label: React.PropTypes.string,
note: React.PropTypes.string,
onChange: React.PropTypes.func,
path: React.PropTypes.string,
value: React.PropTypes.string,
},
getDefaultProps () {
return {
formatString: DEFAULT_FORMAT_STRING,
inputFormat: DEFAULT_INPUT_FORMAT,
};
},
valueChanged ({ value }) {
this.props.onChange({
path: this.props.path,
value: value,
});
},
moment (value) {
var m = moment(value);
if (this.props.isUTC) m.utc();
return m;
},
isValid (value) {
return this.moment(value, this.inputFormat).isValid();
},
format (value) {
return value ? this.moment(value).format(this.props.formatString) : '';
},
setToday () {
this.valueChanged({
value: this.moment(new Date()).format(this.props.inputFormat),
});
},
renderValue () {
return (
<FormInput noedit>
{this.format(this.props.value)}
</FormInput>
);
},
renderField () {
let value = this.moment(this.props.value);
value = this.props.value && value.isValid()
? value.format(this.props.inputFormat)
: this.props.value;
return (
<InputGroup>
<InputGroup.Section grow>
<DateInput
format={this.props.inputFormat}
name={this.getInputName(this.props.path)}
onChange={this.valueChanged}
ref="dateInput"
value={value}
/>
</InputGroup.Section>
<InputGroup.Section>
<Button onClick={this.setToday}>Today</Button>
</InputGroup.Section>
</InputGroup>
);
},
});
|
ajax/libs/react-modal/0.2.0/react-modal.js
|
nolsherry/cdnjs
|
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.ReactModal=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){
var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null);
var ExecutionEnvironment = _dereq_('react/lib/ExecutionEnvironment');
var ModalPortal = React.createFactory(_dereq_('./ModalPortal'));
var ariaAppHider = _dereq_('../helpers/ariaAppHider');
var injectCSS = _dereq_('../helpers/injectCSS');
var SafeHTMLElement = ExecutionEnvironment.canUseDOM ? window.HTMLElement : {};
var Modal = module.exports = React.createClass({
displayName: 'Modal',
statics: {
setAppElement: ariaAppHider.setElement,
injectCSS: injectCSS
},
propTypes: {
isOpen: React.PropTypes.bool.isRequired,
onRequestClose: React.PropTypes.func,
appElement: React.PropTypes.instanceOf(SafeHTMLElement),
closeTimeoutMS: React.PropTypes.number,
ariaHideApp: React.PropTypes.bool
},
getDefaultProps: function () {
return {
isOpen: false,
ariaHideApp: true,
closeTimeoutMS: 0
};
},
componentDidMount: function() {
this.node = document.createElement('div');
this.node.className = 'ReactModalPortal';
document.body.appendChild(this.node);
this.renderPortal(this.props);
},
componentWillReceiveProps: function(newProps) {
this.renderPortal(newProps);
},
componentWillUnmount: function() {
React.unmountComponentAtNode(this.node);
document.body.removeChild(this.node);
},
renderPortal: function(props) {
if (props.ariaHideApp) {
ariaAppHider.toggle(props.isOpen, props.appElement);
}
sanitizeProps(props);
if (this.portal)
this.portal.setProps(props);
else
this.portal = React.render(ModalPortal(props), this.node);
},
render: function () {
return null;
}
});
function sanitizeProps(props) {
delete props.ref;
}
},{"../helpers/ariaAppHider":3,"../helpers/injectCSS":5,"./ModalPortal":2,"react/lib/ExecutionEnvironment":10}],2:[function(_dereq_,module,exports){
var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null);
var div = React.DOM.div;
var focusManager = _dereq_('../helpers/focusManager');
var scopeTab = _dereq_('../helpers/scopeTab');
var cx = _dereq_('classnames');
// so that our CSS is statically analyzable
var CLASS_NAMES = {
overlay: {
base: 'ReactModal__Overlay',
afterOpen: 'ReactModal__Overlay--after-open',
beforeClose: 'ReactModal__Overlay--before-close'
},
content: {
base: 'ReactModal__Content',
afterOpen: 'ReactModal__Content--after-open',
beforeClose: 'ReactModal__Content--before-close'
}
};
var OVERLAY_STYLES = { position: 'fixed', left: 0, right: 0, top: 0, bottom: 0 };
function stopPropagation(event) {
event.stopPropagation();
}
var ModalPortal = module.exports = React.createClass({
displayName: 'ModalPortal',
getInitialState: function() {
return {
afterOpen: false,
beforeClose: false
};
},
componentDidMount: function() {
// Focus needs to be set when mounting and already open
if (this.props.isOpen) {
this.setFocusAfterRender(true);
this.open();
}
},
componentWillReceiveProps: function(newProps) {
// Focus only needs to be set once when the modal is being opened
if (!this.props.isOpen && newProps.isOpen) {
this.setFocusAfterRender(true);
this.open();
} else if (this.props.isOpen && !newProps.isOpen) {
this.close();
}
},
componentDidUpdate: function () {
if (this.focusAfterRender) {
this.focusContent();
this.setFocusAfterRender(false);
}
},
setFocusAfterRender: function (focus) {
this.focusAfterRender = focus;
},
open: function() {
focusManager.setupScopedFocus(this.getDOMNode());
focusManager.markForFocusLater();
this.setState({isOpen: true}, function() {
this.setState({afterOpen: true});
}.bind(this));
},
close: function() {
if (!this.ownerHandlesClose())
return;
if (this.props.closeTimeoutMS > 0)
this.closeWithTimeout();
else
this.closeWithoutTimeout();
},
focusContent: function() {
this.refs.content.getDOMNode().focus();
},
closeWithTimeout: function() {
this.setState({beforeClose: true}, function() {
setTimeout(this.closeWithoutTimeout, this.props.closeTimeoutMS);
}.bind(this));
},
closeWithoutTimeout: function() {
this.setState({
afterOpen: false,
beforeClose: false
}, this.afterClose);
},
afterClose: function() {
focusManager.returnFocus();
focusManager.teardownScopedFocus();
},
handleKeyDown: function(event) {
if (event.keyCode == 9 /*tab*/) scopeTab(this.refs.content.getDOMNode(), event);
if (event.keyCode == 27 /*esc*/) this.requestClose();
},
handleOverlayClick: function() {
if (this.ownerHandlesClose())
this.requestClose();
else
this.focusContent();
},
requestClose: function() {
if (this.ownerHandlesClose())
this.props.onRequestClose();
},
ownerHandlesClose: function() {
return this.props.onRequestClose;
},
shouldBeClosed: function() {
return !this.props.isOpen && !this.state.beforeClose;
},
buildClassName: function(which) {
var className = CLASS_NAMES[which].base;
if (this.state.afterOpen)
className += ' '+CLASS_NAMES[which].afterOpen;
if (this.state.beforeClose)
className += ' '+CLASS_NAMES[which].beforeClose;
return className;
},
render: function() {
return this.shouldBeClosed() ? div() : (
div({
ref: "overlay",
className: cx(this.buildClassName('overlay'), this.props.overlayClassName),
style: OVERLAY_STYLES,
onClick: this.handleOverlayClick
},
div({
ref: "content",
style: this.props.style,
className: cx(this.buildClassName('content'), this.props.className),
tabIndex: "-1",
onClick: stopPropagation,
onKeyDown: this.handleKeyDown
},
this.props.children
)
)
);
}
});
},{"../helpers/focusManager":4,"../helpers/scopeTab":6,"classnames":9}],3:[function(_dereq_,module,exports){
var _element = null;
function setElement(element) {
_element = element;
}
function hide(appElement) {
validateElement(appElement);
(appElement || _element).setAttribute('aria-hidden', 'true');
}
function show(appElement) {
validateElement(appElement);
(appElement || _element).removeAttribute('aria-hidden');
}
function toggle(shouldHide, appElement) {
if (shouldHide)
hide(appElement);
else
show(appElement);
}
function validateElement(appElement) {
if (!appElement && !_element)
throw new Error('react-modal: You must set an element with `Modal.setAppElement(el)` to make this accessible');
}
function resetForTesting() {
_element = null;
}
exports.toggle = toggle;
exports.setElement = setElement;
exports.show = show;
exports.hide = hide;
exports.resetForTesting = resetForTesting;
},{}],4:[function(_dereq_,module,exports){
var findTabbable = _dereq_('../helpers/tabbable');
var modalElement = null;
var focusLaterElement = null;
var needToFocus = false;
function handleBlur(event) {
needToFocus = true;
}
function handleFocus(event) {
if (needToFocus) {
needToFocus = false;
if (!modalElement) {
return;
}
// need to see how jQuery shims document.on('focusin') so we don't need the
// setTimeout, firefox doesn't support focusin, if it did, we could focus
// the the element outisde of a setTimeout. Side-effect of this
// implementation is that the document.body gets focus, and then we focus
// our element right after, seems fine.
setTimeout(function() {
if (modalElement.contains(document.activeElement))
return;
var el = (findTabbable(modalElement)[0] || modalElement);
el.focus();
}, 0);
}
}
exports.markForFocusLater = function() {
focusLaterElement = document.activeElement;
};
exports.returnFocus = function() {
try {
focusLaterElement.focus();
}
catch (e) {
console.warn('You tried to return focus to '+focusLaterElement+' but it is not in the DOM anymore');
}
focusLaterElement = null;
};
exports.setupScopedFocus = function(element) {
modalElement = element;
if (window.addEventListener) {
window.addEventListener('blur', handleBlur, false);
document.addEventListener('focus', handleFocus, true);
} else {
window.attachEvent('onBlur', handleBlur);
document.attachEvent('onFocus', handleFocus);
}
};
exports.teardownScopedFocus = function() {
modalElement = null;
if (window.addEventListener) {
window.removeEventListener('blur', handleBlur);
document.removeEventListener('focus', handleFocus);
} else {
window.detachEvent('onBlur', handleBlur);
document.detachEvent('onFocus', handleFocus);
}
};
},{"../helpers/tabbable":7}],5:[function(_dereq_,module,exports){
module.exports = function() {
injectStyle([
'.ReactModal__Overlay {',
' background-color: rgba(255, 255, 255, 0.75);',
'}',
'.ReactModal__Content {',
' position: absolute;',
' top: 40px;',
' left: 40px;',
' right: 40px;',
' bottom: 40px;',
' border: 1px solid #ccc;',
' background: #fff;',
' overflow: auto;',
' -webkit-overflow-scrolling: touch;',
' border-radius: 4px;',
' outline: none;',
' padding: 20px;',
'}',
'@media (max-width: 768px) {',
' .ReactModal__Content {',
' top: 10px;',
' left: 10px;',
' right: 10px;',
' bottom: 10px;',
' padding: 10px;',
' }',
'}'
].join('\n'));
};
function injectStyle(css) {
var style = document.getElementById('rackt-style');
if (!style) {
style = document.createElement('style');
style.setAttribute('id', 'rackt-style');
var head = document.getElementsByTagName('head')[0];
head.insertBefore(style, head.firstChild);
}
style.innerHTML = style.innerHTML+'\n'+css;
}
},{}],6:[function(_dereq_,module,exports){
var findTabbable = _dereq_('../helpers/tabbable');
module.exports = function(node, event) {
var tabbable = findTabbable(node);
var finalTabbable = tabbable[event.shiftKey ? 0 : tabbable.length - 1];
var leavingFinalTabbable = (
finalTabbable === document.activeElement ||
// handle immediate shift+tab after opening with mouse
node === document.activeElement
);
if (!leavingFinalTabbable) return;
event.preventDefault();
var target = tabbable[event.shiftKey ? tabbable.length - 1 : 0];
target.focus();
};
},{"../helpers/tabbable":7}],7:[function(_dereq_,module,exports){
/*!
* Adapted from jQuery UI core
*
* http://jqueryui.com
*
* Copyright 2014 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/category/ui-core/
*/
function focusable(element, isTabIndexNotNaN) {
var nodeName = element.nodeName.toLowerCase();
return (/input|select|textarea|button|object/.test(nodeName) ?
!element.disabled :
"a" === nodeName ?
element.href || isTabIndexNotNaN :
isTabIndexNotNaN) && visible(element);
}
function hidden(el) {
return (el.offsetWidth <= 0 && el.offsetHeight <= 0) ||
el.style.display === 'none';
}
function visible(element) {
while (element) {
if (element === document.body) break;
if (hidden(element)) return false;
element = element.parentNode;
}
return true;
}
function tabbable(element) {
var tabIndex = element.getAttribute('tabindex');
if (tabIndex === null) tabIndex = undefined;
var isTabIndexNaN = isNaN(tabIndex);
return (isTabIndexNaN || tabIndex >= 0) && focusable(element, !isTabIndexNaN);
}
function findTabbableDescendants(element) {
return [].slice.call(element.querySelectorAll('*'), 0).filter(function(el) {
return tabbable(el);
});
}
module.exports = findTabbableDescendants;
},{}],8:[function(_dereq_,module,exports){
module.exports = _dereq_('./components/Modal');
},{"./components/Modal":1}],9:[function(_dereq_,module,exports){
/*!
Copyright (c) 2015 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
function classNames() {
var classes = '';
var arg;
for (var i = 0; i < arguments.length; i++) {
arg = arguments[i];
if (!arg) {
continue;
}
if ('string' === typeof arg || 'number' === typeof arg) {
classes += ' ' + arg;
} else if (Object.prototype.toString.call(arg) === '[object Array]') {
classes += ' ' + classNames.apply(null, arg);
} else if ('object' === typeof arg) {
for (var key in arg) {
if (!arg.hasOwnProperty(key) || !arg[key]) {
continue;
}
classes += ' ' + key;
}
}
}
return classes.substr(1);
}
// safely export classNames for node / browserify
if (typeof module !== 'undefined' && module.exports) {
module.exports = classNames;
}
// safely export classNames for RequireJS
if (typeof define !== 'undefined' && define.amd) {
define('classnames', [], function() {
return classNames;
});
}
},{}],10:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule 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;
},{}]},{},[8])
(8)
});
|
src/components/common/form/OpenWebMediaFieldArray.js
|
mitmedialab/MediaCloud-Web-Tools
|
import PropTypes from 'prop-types';
import React from 'react';
import { injectIntl } from 'react-intl';
import { reduxForm, FieldArray, Field, propTypes } from 'redux-form';
import withIntlForm from '../hocs/IntlForm';
import OpenWebMediaItem from '../OpenWebMediaItem';
const renderCollectionSelector = ({ allowRemoval, fields, meta, onDelete }) => (
<div>
{fields.map((name, index) => (
<Field
key={name}
name={name}
component={(info) => {
const handleDelete = ((allowRemoval || info.meta.dirty)) ? () => { fields.remove(index); onDelete(info.input.value); } : undefined;
const val = info.input.value;
let tempObj = {};
if (val && typeof val === 'number') {
tempObj.id = val;
} else {
tempObj = info.input.value;
}
return (
<OpenWebMediaItem object={tempObj} onDelete={handleDelete} />
);
}}
/>
))}
{ meta.error !== null && meta.error !== undefined ? <div className="error">{meta.error}</div> : '' }
</div>
);
renderCollectionSelector.propTypes = {
fields: PropTypes.object,
meta: PropTypes.object,
allowRemoval: PropTypes.bool,
validate: PropTypes.func,
onDelete: PropTypes.func,
};
const OpenWebMediaFieldArray = (props) => {
const { fieldName, initialValues, allowRemoval, onDelete } = props;
return (
<div className="explorer-source-collection-form">
<FieldArray
form={propTypes.form}
name={fieldName}
validate={propTypes.validate}
allowRemoval={allowRemoval}
component={renderCollectionSelector}
initialValues={initialValues}
onDelete={onDelete}
/>
</div>
);
};
OpenWebMediaFieldArray.propTypes = {
// from parent
intl: PropTypes.object.isRequired,
initialValues: PropTypes.object,
selected: PropTypes.object,
allowRemoval: PropTypes.bool,
fieldName: PropTypes.string,
// valid: PropTypes.bool, not using - but this is helpful to determine if validation is getting
onDelete: PropTypes.func,
};
export default
injectIntl(
withIntlForm(
reduxForm({ propTypes })(
OpenWebMediaFieldArray
)
)
);
|
node_modules/react-native/node_modules/react-tools/src/core/__tests__/ReactMultiChildReconcile-test.js
|
dancurtiss/MLBSchedules
|
/**
* 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';
require('mock-modules');
var React = require('React');
var ReactInstanceMap = require('ReactInstanceMap');
var ReactTestUtils = require('ReactTestUtils');
var ReactMount = require('ReactMount');
var mapObject = require('mapObject');
var stripEmptyValues = function(obj) {
var ret = {};
var name;
for (name in obj) {
if (!obj.hasOwnProperty(name)) {
continue;
}
if (obj[name] !== null && obj[name] !== undefined) {
ret[name] = obj[name];
}
}
return ret;
};
/**
* Child key names are wrapped like '.$key:0'. We strip the extra chars out
* here. This relies on an implementation detail of the rendering system.
*/
var getOriginalKey = function(childName) {
var match = childName.match(/^\.\$([^.]+)$/);
expect(match).not.toBeNull();
return match[1];
};
/**
* Contains internal static internal state in order to test that updates to
* existing children won't reinitialize components, when moving children -
* reusing existing DOM/memory resources.
*/
var StatusDisplay = React.createClass({
getInitialState: function() {
return {internalState: Math.random()};
},
getStatus: function() {
return this.props.status;
},
getInternalState: function() {
return this.state.internalState;
},
render: function() {
return (
<div>
{this.state.internalState}
</div>
);
}
});
/**
* Displays friends statuses.
*/
var FriendsStatusDisplay = React.createClass({
/**
* Retrieves the rendered children in a nice format for comparing to the input
* `this.props.usernameToStatus`. Gets the order directly from each rendered
* child's `index` field. Refs are not maintained in the rendered order, and
* neither is `this._renderedChildren` (surprisingly).
*/
getStatusDisplays: function() {
var name;
var orderOfUsernames = [];
// TODO: Update this to a better test that doesn't rely so much on internal
// implementation details.
var statusDisplays =
ReactInstanceMap.get(this)
._renderedComponent
._renderedComponent
._renderedChildren;
for (name in statusDisplays) {
var child = statusDisplays[name];
var isPresent = !!child;
if (isPresent) {
orderOfUsernames[child._mountIndex] = getOriginalKey(name);
}
}
var res = {};
var i;
for (i = 0; i < orderOfUsernames.length; i++) {
var key = orderOfUsernames[i];
res[key] = this.refs[key];
}
return res;
},
render: function() {
var children = [];
var key;
for (key in this.props.usernameToStatus) {
var status = this.props.usernameToStatus[key];
children.push(
!status ? null :
<StatusDisplay key={key} ref={key} status={status} />
);
}
return (
<div>
{children}
</div>
);
}
});
function getInteralStateByUserName(statusDisplays) {
return mapObject(statusDisplays, function(statusDisplay, key) {
return statusDisplay.getInternalState();
});
}
/**
* Verifies that the rendered `StatusDisplay` instances match the `props` that
* were responsible for allocating them. Checks the content of the user's status
* message as well as the order of them.
*/
function verifyStatuses(statusDisplays, props) {
var nonEmptyStatusDisplays = stripEmptyValues(statusDisplays);
var nonEmptyStatusProps = stripEmptyValues(props.usernameToStatus);
var username;
expect(Object.keys(nonEmptyStatusDisplays).length)
.toEqual(Object.keys(nonEmptyStatusProps).length);
for (username in nonEmptyStatusDisplays) {
if (!nonEmptyStatusDisplays.hasOwnProperty(username)) {
continue;
}
expect(nonEmptyStatusDisplays[username].getStatus())
.toEqual(nonEmptyStatusProps[username]);
}
// now go the other way to make sure we got them all.
for (username in nonEmptyStatusProps) {
if (!nonEmptyStatusProps.hasOwnProperty(username)) {
continue;
}
expect(nonEmptyStatusDisplays[username].getStatus())
.toEqual(nonEmptyStatusProps[username]);
}
expect(Object.keys(nonEmptyStatusDisplays))
.toEqual(Object.keys(nonEmptyStatusProps));
}
/**
* For all statusDisplays that existed in the previous iteration of the
* sequence, verify that the state has been preserved. `StatusDisplay` contains
* a unique number that allows us to track internal state across ordering
* movements.
*/
function verifyStatesPreserved(lastInternalStates, statusDisplays) {
var key;
for (key in statusDisplays) {
if (!statusDisplays.hasOwnProperty(key)) {
continue;
}
if (lastInternalStates[key]) {
expect(lastInternalStates[key])
.toEqual(statusDisplays[key].getInternalState());
}
}
}
/**
* Verifies that the internal representation of a set of `renderedChildren`
* accurately reflects what is in the DOM.
*/
function verifyDomOrderingAccurate(parentInstance, statusDisplays) {
var containerNode = parentInstance.getDOMNode();
var statusDisplayNodes = containerNode.childNodes;
var i;
var orderedDomIds = [];
for (i = 0; i < statusDisplayNodes.length; i++) {
orderedDomIds.push(ReactMount.getID(statusDisplayNodes[i]));
}
var orderedLogicalIds = [];
var username;
for (username in statusDisplays) {
if (!statusDisplays.hasOwnProperty(username)) {
continue;
}
var statusDisplay = statusDisplays[username];
orderedLogicalIds.push(ReactInstanceMap.get(statusDisplay)._rootNodeID);
}
expect(orderedDomIds).toEqual(orderedLogicalIds);
}
/**
* Todo: Check that internal state is preserved across transitions
*/
function testPropsSequence(sequence) {
var i;
var parentInstance = ReactTestUtils.renderIntoDocument(
<FriendsStatusDisplay {...sequence[0]} />
);
var statusDisplays = parentInstance.getStatusDisplays();
var lastInternalStates = getInteralStateByUserName(statusDisplays);
verifyStatuses(statusDisplays, sequence[0]);
for (i = 1; i < sequence.length; i++) {
parentInstance.replaceProps(sequence[i]);
statusDisplays = parentInstance.getStatusDisplays();
verifyStatuses(statusDisplays, sequence[i]);
verifyStatesPreserved(lastInternalStates, statusDisplays);
verifyDomOrderingAccurate(parentInstance, statusDisplays);
lastInternalStates = getInteralStateByUserName(statusDisplays);
}
}
describe('ReactMultiChildReconcile', function() {
beforeEach(function() {
require('mock-modules').dumpCache();
});
it('should reset internal state if removed then readded', function() {
// Test basics.
var props = {
usernameToStatus: {
jcw: 'jcwStatus'
}
};
var parentInstance = ReactTestUtils.renderIntoDocument(
<FriendsStatusDisplay {...props} />
);
var statusDisplays = parentInstance.getStatusDisplays();
var startingInternalState = statusDisplays.jcw.getInternalState();
// Now remove the child.
parentInstance.replaceProps({usernameToStatus: {} });
statusDisplays = parentInstance.getStatusDisplays();
expect(statusDisplays.jcw).toBeFalsy();
// Now reset the props that cause there to be a child
parentInstance.replaceProps(props);
statusDisplays = parentInstance.getStatusDisplays();
expect(statusDisplays.jcw).toBeTruthy();
expect(statusDisplays.jcw.getInternalState())
.toNotBe(startingInternalState);
});
it('should create unique identity', function() {
// Test basics.
var usernameToStatus = {
jcw: 'jcwStatus',
awalke: 'awalkeStatus',
bob: 'bobStatus'
};
testPropsSequence([ {usernameToStatus: usernameToStatus} ]);
});
it('should preserve order if children order has not changed', function() {
var PROPS_SEQUENCE = [
{
usernameToStatus: {
jcw: 'jcwStatus',
jordanjcw: 'jordanjcwStatus'
}
},
{
usernameToStatus: {
jcw: 'jcwstatus2',
jordanjcw: 'jordanjcwstatus2'
}
}
];
testPropsSequence(PROPS_SEQUENCE);
});
it('should transition from zero to one children correctly', function() {
var PROPS_SEQUENCE = [
{usernameToStatus: {} },
{
usernameToStatus: {
first: 'firstStatus'
}
}
];
testPropsSequence(PROPS_SEQUENCE);
});
it('should transition from one to zero children correctly', function() {
var PROPS_SEQUENCE = [
{
usernameToStatus: {
first: 'firstStatus'
}
},
{usernameToStatus: {} }
];
testPropsSequence(PROPS_SEQUENCE);
});
it('should transition from one child to null children', function() {
testPropsSequence([
{
usernameToStatus: {
first: 'firstStatus'
}
},
{}
]);
});
it('should transition from null children to one child', function() {
testPropsSequence([
{},
{
usernameToStatus: {
first: 'firstStatus'
}
}
]);
});
it('should transition from zero children to null children', function() {
testPropsSequence([
{
usernameToStatus: {}
},
{}
]);
});
it('should transition from null children to zero children', function() {
testPropsSequence([
{},
{
usernameToStatus: {}
}
]);
});
/**
* `FriendsStatusDisplay` renders nulls as empty children (it's a convention
* of `FriendsStatusDisplay`, nothing related to React or these test cases.
*/
it('should remove nulled out children at the beginning', function() {
var PROPS_SEQUENCE = [
{
usernameToStatus: {
jcw: 'jcwStatus',
jordanjcw: 'jordanjcwStatus'
}
},
{
usernameToStatus: {
jcw: null,
jordanjcw: 'jordanjcwstatus2'
}
}
];
testPropsSequence(PROPS_SEQUENCE);
});
it('should remove nulled out children at the end', function() {
var PROPS_SEQUENCE = [
{
usernameToStatus: {
jcw: 'jcwStatus',
jordanjcw: 'jordanjcwStatus'
}
},
{
usernameToStatus: {
jcw: 'jcwstatus2',
jordanjcw: null
}
}
];
testPropsSequence(PROPS_SEQUENCE);
});
it('should reverse the order of two children', function() {
var PROPS_SEQUENCE = [
{
usernameToStatus: {
userOne: 'userOneStatus',
userTwo: 'userTwoStatus'
}
},
{
usernameToStatus: {
userTwo: 'userTwoStatus',
userOne: 'userOneStatus'
}
}
];
testPropsSequence(PROPS_SEQUENCE);
});
it('should reverse the order of more than two children', function() {
var PROPS_SEQUENCE = [
{
usernameToStatus: {
userOne: 'userOneStatus',
userTwo: 'userTwoStatus',
userThree: 'userThreeStatus'
}
},
{
usernameToStatus: {
userThree: 'userThreeStatus',
userTwo: 'userTwoStatus',
userOne: 'userOneStatus'
}
}
];
testPropsSequence(PROPS_SEQUENCE);
});
it('should cycle order correctly', function() {
var PROPS_SEQUENCE = [
{
usernameToStatus: {
userOne: 'userOneStatus',
userTwo: 'userTwoStatus',
userThree: 'userThreeStatus',
userFour: 'userFourStatus'
}
},
{
usernameToStatus: {
userTwo: 'userTwoStatus',
userThree: 'userThreeStatus',
userFour: 'userFourStatus',
userOne: 'userOneStatus'
}
},
{
usernameToStatus: {
userThree: 'userThreeStatus',
userFour: 'userFourStatus',
userOne: 'userOneStatus',
userTwo: 'userTwoStatus'
}
},
{
usernameToStatus: {
userFour: 'userFourStatus',
userOne: 'userOneStatus',
userTwo: 'userTwoStatus',
userThree: 'userThreeStatus'
}
},
{
usernameToStatus: { // Full circle!
userOne: 'userOneStatus',
userTwo: 'userTwoStatus',
userThree: 'userThreeStatus',
userFour: 'userFourStatus'
}
}
];
testPropsSequence(PROPS_SEQUENCE);
});
it('should cycle order correctly in the other direction', function() {
var PROPS_SEQUENCE = [
{
usernameToStatus: {
userOne: 'userOneStatus',
userTwo: 'userTwoStatus',
userThree: 'userThreeStatus',
userFour: 'userFourStatus'
}
},
{
usernameToStatus: {
userFour: 'userFourStatus',
userOne: 'userOneStatus',
userTwo: 'userTwoStatus',
userThree: 'userThreeStatus'
}
},
{
usernameToStatus: {
userThree: 'userThreeStatus',
userFour: 'userFourStatus',
userOne: 'userOneStatus',
userTwo: 'userTwoStatus'
}
},
{
usernameToStatus: {
userTwo: 'userTwoStatus',
userThree: 'userThreeStatus',
userFour: 'userFourStatus',
userOne: 'userOneStatus'
}
},
{
usernameToStatus: { // Full circle!
userOne: 'userOneStatus',
userTwo: 'userTwoStatus',
userThree: 'userThreeStatus',
userFour: 'userFourStatus'
}
}
];
testPropsSequence(PROPS_SEQUENCE);
});
it('should remove nulled out children and ignore ' +
'new null children', function() {
var PROPS_SEQUENCE = [
{
usernameToStatus: {
jcw: 'jcwStatus',
jordanjcw: 'jordanjcwStatus'
}
},
{
usernameToStatus: {
jordanjcw: 'jordanjcwstatus2',
jcw: null,
another: null
}
}
];
testPropsSequence(PROPS_SEQUENCE);
});
it('should remove nulled out children and reorder remaining', function() {
var PROPS_SEQUENCE = [
{
usernameToStatus: {
jcw: 'jcwStatus',
jordanjcw: 'jordanjcwStatus',
john: 'johnStatus', // john will go away
joe: 'joeStatus'
}
},
{
usernameToStatus: {
jordanjcw: 'jordanjcwStatus',
joe: 'joeStatus',
jcw: 'jcwStatus'
}
}
];
testPropsSequence(PROPS_SEQUENCE);
});
it('should append children to the end', function() {
var PROPS_SEQUENCE = [
{
usernameToStatus: {
jcw: 'jcwStatus',
jordanjcw: 'jordanjcwStatus'
}
},
{
usernameToStatus: {
jcw: 'jcwStatus',
jordanjcw: 'jordanjcwStatus',
jordanjcwnew: 'jordanjcwnewStatus'
}
}
];
testPropsSequence(PROPS_SEQUENCE);
});
it('should append multiple children to the end', function() {
var PROPS_SEQUENCE = [
{
usernameToStatus: {
jcw: 'jcwStatus',
jordanjcw: 'jordanjcwStatus'
}
},
{
usernameToStatus: {
jcw: 'jcwStatus',
jordanjcw: 'jordanjcwStatus',
jordanjcwnew: 'jordanjcwnewStatus',
jordanjcwnew2: 'jordanjcwnewStatus2'
}
}
];
testPropsSequence(PROPS_SEQUENCE);
});
it('should prepend children to the beginning', function() {
var PROPS_SEQUENCE = [
{
usernameToStatus: {
jcw: 'jcwStatus',
jordanjcw: 'jordanjcwStatus'
}
},
{
usernameToStatus: {
newUsername: 'newUsernameStatus',
jcw: 'jcwStatus',
jordanjcw: 'jordanjcwStatus'
}
}
];
testPropsSequence(PROPS_SEQUENCE);
});
it('should prepend multiple children to the beginning', function() {
var PROPS_SEQUENCE = [
{
usernameToStatus: {
jcw: 'jcwStatus',
jordanjcw: 'jordanjcwStatus'
}
},
{
usernameToStatus: {
newNewUsername: 'newNewUsernameStatus',
newUsername: 'newUsernameStatus',
jcw: 'jcwStatus',
jordanjcw: 'jordanjcwStatus'
}
}
];
testPropsSequence(PROPS_SEQUENCE);
});
it('should not prepend an empty child to the beginning', function() {
var PROPS_SEQUENCE = [
{
usernameToStatus: {
jcw: 'jcwStatus',
jordanjcw: 'jordanjcwStatus'
}
},
{
usernameToStatus: {
emptyUsername: null,
jcw: 'jcwStatus',
jordanjcw: 'jordanjcwStatus'
}
}
];
testPropsSequence(PROPS_SEQUENCE);
});
it('should not append an empty child to the end', function() {
var PROPS_SEQUENCE = [
{
usernameToStatus: {
jcw: 'jcwStatus',
jordanjcw: 'jordanjcwStatus'
}
},
{
usernameToStatus: {
jcw: 'jcwStatus',
jordanjcw: 'jordanjcwStatus',
emptyUsername: null
}
}
];
testPropsSequence(PROPS_SEQUENCE);
});
it('should not insert empty children in the middle', function() {
var PROPS_SEQUENCE = [
{
usernameToStatus: {
jcw: 'jcwStatus',
jordanjcw: 'jordanjcwStatus'
}
},
{
usernameToStatus: {
jcw: 'jcwstatus2',
skipOverMe: null,
skipOverMeToo: null,
definitelySkipOverMe: null,
jordanjcw: 'jordanjcwstatus2'
}
}
];
testPropsSequence(PROPS_SEQUENCE);
});
it('should insert one new child in the middle', function() {
var PROPS_SEQUENCE = [
{
usernameToStatus: {
jcw: 'jcwStatus',
jordanjcw: 'jordanjcwStatus'
}
},
{
usernameToStatus: {
jcw: 'jcwstatus2',
insertThis: 'insertThisStatus',
jordanjcw: 'jordanjcwstatus2'
}
}
];
testPropsSequence(PROPS_SEQUENCE);
});
it('should insert multiple new truthy children in the middle', function() {
var PROPS_SEQUENCE = [
{
usernameToStatus: {
jcw: 'jcwStatus',
jordanjcw: 'jordanjcwStatus'
}
},
{
usernameToStatus: {
jcw: 'jcwstatus2',
insertThis: 'insertThisStatus',
insertThisToo: 'insertThisTooStatus',
definitelyInsertThisToo: 'definitelyInsertThisTooStatus',
jordanjcw: 'jordanjcwstatus2'
}
}
];
testPropsSequence(PROPS_SEQUENCE);
});
it('should insert non-empty children in middle where nulls were', function() {
var PROPS_SEQUENCE = [
{
usernameToStatus: {
jcw: 'jcwStatus',
insertThis: null,
insertThisToo: null,
definitelyInsertThisToo: null,
jordanjcw: 'jordanjcwStatus'
}
},
{
usernameToStatus: {
jcw: 'jcwstatus2',
insertThis: 'insertThisStatus',
insertThisToo: 'insertThisTooStatus',
definitelyInsertThisToo: 'definitelyInsertThisTooStatus',
jordanjcw: 'jordanjcwstatus2'
}
}
];
testPropsSequence(PROPS_SEQUENCE);
});
});
|
site/components/PageBody.js
|
cesarandreu/react-dnd
|
import React from 'react';
import './PageBody.less';
export default class PageBody {
static propTypes = {
hasSidebar: React.PropTypes.bool
};
render() {
var {hasSidebar, html, ...props} = this.props;
return (
<div className={`PageBody ${hasSidebar ? 'PageBody--hasSidebar' : ''}`}>
<div className="PageBody-container">
{this.props.children}
</div>
</div>
);
}
}
|
src/components/Header/Header.js
|
LeraSavchenko/Maysternia
|
import React from 'react';
import { defineMessages, FormattedMessage } from 'react-intl';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Header.css';
import Link from '../Link';
import LanguageSwitcher from '../LanguageSwitcher';
const messages = defineMessages({
brand: {
id: 'header.brand',
defaultMessage: 'Майстерня',
},
contactsPhone: {
id: 'header.contacts.phone',
defaultMessage: '+38 066 445 59 00',
},
contactsMessage: {
id: 'header.contacts.message',
defaultMessage: 'Доставка по Україні',
},
contactButton: {
id: 'header.contact.button',
defaultMessage: 'Зв\'язатись з нами',
},
});
class Header extends React.Component {
render() {
return (
<div className={s.root}>
<div className={s.container}>
<Link className={s.brand} to="/">
<FormattedMessage {...messages.brand} />
</Link>
<div className={s.contacts}>
<FormattedMessage {...messages.contactsPhone} /><br />
<span className={s.contactsMessage}><FormattedMessage {...messages.contactsMessage} /></span>
</div>
<Link className={s.contactButton} to="/">
<div className={s.button}>
<FormattedMessage {...messages.contactButton} />
</div>
</Link>
<span className={s.lang}><LanguageSwitcher /></span>
<Link className={s.hamburger} to="/">
<div className={s.hamburgerBar}></div>
<div className={s.hamburgerBar}></div>
<div className={s.hamburgerBar}></div>
</Link>
</div>
</div>
);
}
}
export default withStyles(s)(Header);
|
client/modules/App/__tests__/App.spec.js
|
Parinaaz/TempApplication17
|
import React from 'react';
import test from 'ava';
import sinon from 'sinon';
import { shallow, mount } from 'enzyme';
import { App } from '../App';
import styles from '../App.css';
import { intlShape } from 'react-intl';
import { intl } from '../../../util/react-intl-test-helper';
import { toggleAddPost } from '../AppActions';
const intlProp = { ...intl, enabledLanguages: ['en', 'fr'] };
const children = <h1>Test</h1>;
const dispatch = sinon.spy();
const props = {
children,
dispatch,
intl: intlProp,
};
test('renders properly', t => {
const wrapper = shallow(
<App {...props} />
);
// t.is(wrapper.find('Helmet').length, 1);
t.is(wrapper.find('Header').length, 1);
t.is(wrapper.find('Footer').length, 1);
t.is(wrapper.find('Header').prop('toggleAddPost'), wrapper.instance().toggleAddPostSection);
t.truthy(wrapper.find('Header + div').hasClass(styles.container));
t.truthy(wrapper.find('Header + div').children(), children);
});
test('calls componentDidMount', t => {
sinon.spy(App.prototype, 'componentDidMount');
mount(
<App {...props} />,
{
context: {
router: {
isActive: sinon.stub().returns(true),
push: sinon.stub(),
replace: sinon.stub(),
go: sinon.stub(),
goBack: sinon.stub(),
goForward: sinon.stub(),
setRouteLeaveHook: sinon.stub(),
createHref: sinon.stub(),
},
intl,
},
childContextTypes: {
router: React.PropTypes.object,
intl: intlShape,
},
},
);
t.truthy(App.prototype.componentDidMount.calledOnce);
App.prototype.componentDidMount.restore();
});
test('calling toggleAddPostSection dispatches toggleAddPost', t => {
const wrapper = shallow(
<App {...props} />
);
wrapper.instance().toggleAddPostSection();
t.truthy(dispatch.calledOnce);
t.truthy(dispatch.calledWith(toggleAddPost()));
});
|
client/app/containers/Recipes/index.js
|
vulcan-estudios/pwa-examples
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { withRouter, Link } from 'react-router';
import Recipe from 'client/app/components/Recipe';
const mapStateToProps = function (state) {
return {
recipes: state.recipes,
};
};
class RecipesContainer extends Component {
constructor () {
super(...arguments);
}
render () {
const { recipes } = this.props;
const recipesElements = recipes.map(recipe => (
<Recipe key={recipe.id} {...recipe}>
<Link className="button small" to={`/blender/${recipe.id}`}>Make</Link>
</Recipe>
));
return (
<div className='recipes row column'>
{recipesElements}
</div>
);
}
}
export default withRouter(connect(mapStateToProps)(RecipesContainer));
|
pootle/static/js/admin/components/Project/ProjectController.js
|
JohnnyKing94/pootle
|
/*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import React from 'react';
import Search from '../Search';
import ProjectAdd from './ProjectAdd';
import ProjectEdit from './ProjectEdit';
const ProjectController = React.createClass({
propTypes: {
items: React.PropTypes.object.isRequired,
model: React.PropTypes.func.isRequired,
onAdd: React.PropTypes.func.isRequired,
onCancel: React.PropTypes.func.isRequired,
onDelete: React.PropTypes.func.isRequired,
onSearch: React.PropTypes.func.isRequired,
onSelectItem: React.PropTypes.func.isRequired,
onSuccess: React.PropTypes.func.isRequired,
searchQuery: React.PropTypes.string.isRequired,
selectedItem: React.PropTypes.object,
view: React.PropTypes.string.isRequired,
},
render() {
const viewsMap = {
add: (
<ProjectAdd
model={this.props.model}
collection={this.props.items}
onSuccess={this.props.onSuccess}
onCancel={this.props.onCancel}
/>
),
edit: (
<ProjectEdit
model={this.props.selectedItem}
collection={this.props.items}
onAdd={this.props.onAdd}
onSuccess={this.props.onSuccess}
onDelete={this.props.onDelete}
/>
),
};
const args = {
count: this.props.items.count,
};
let msg;
if (this.props.searchQuery) {
msg = ngettext('%(count)s project matches your query.',
'%(count)s projects match your query.', args.count);
} else {
msg = ngettext(
'There is %(count)s project.',
'There are %(count)s projects. Below are the most recently added ones.',
args.count
);
}
const resultsCaption = interpolate(msg, args, true);
return (
<div className="admin-app-projects">
<div className="module first">
<Search
fields={['index', 'code', 'fullname', 'disabled']}
onSearch={this.props.onSearch}
onSelectItem={this.props.onSelectItem}
items={this.props.items}
selectedItem={this.props.selectedItem}
searchLabel={gettext('Search Projects')}
searchPlaceholder={gettext('Find project by name, code')}
resultsCaption={resultsCaption}
searchQuery={this.props.searchQuery}
/>
</div>
<div className="module admin-content">
{viewsMap[this.props.view]}
</div>
</div>
);
},
});
export default ProjectController;
|
client/food-product-index.js
|
gobble43/gobble-dist-web
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import configureStore from './../common/configureStore';
const initialState = window.__INITIAL_STATE__;
const store = configureStore(initialState);
import FoodProductContainer from './../common/food-product/FoodProductContainer';
ReactDOM.render(
<Provider store={store}>
<FoodProductContainer />
</Provider>,
document.querySelector('.root')
);
|
src/svg-icons/av/library-books.js
|
skarnecki/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvLibraryBooks = (props) => (
<SvgIcon {...props}>
<path d="M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-1 9H9V9h10v2zm-4 4H9v-2h6v2zm4-8H9V5h10v2z"/>
</SvgIcon>
);
AvLibraryBooks = pure(AvLibraryBooks);
AvLibraryBooks.displayName = 'AvLibraryBooks';
export default AvLibraryBooks;
|
ajax/libs/tinymce/4.1.3/plugins/legacyoutput/plugin.js
|
automaticgiant/cdnjs
|
/**
* plugin.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*
* This plugin will force TinyMCE to produce deprecated legacy output such as font elements, u elements, align
* attributes and so forth. There are a few cases where these old items might be needed for example in email applications or with Flash
*
* However you should NOT use this plugin if you are building some system that produces web contents such as a CMS. All these elements are
* not apart of the newer specifications for HTML and XHTML.
*/
/*global tinymce:true */
(function(tinymce) {
// Override inline_styles setting to force TinyMCE to produce deprecated contents
tinymce.on('AddEditor', function(e) {
e.editor.settings.inline_styles = false;
});
tinymce.PluginManager.add('legacyoutput', function(editor, url, $) {
editor.on('init', function() {
var alignElements = 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img',
fontSizes = tinymce.explode(editor.settings.font_size_style_values),
schema = editor.schema;
// Override some internal formats to produce legacy elements and attributes
editor.formatter.register({
// Change alignment formats to use the deprecated align attribute
alignleft: {selector: alignElements, attributes: {align: 'left'}},
aligncenter: {selector: alignElements, attributes: {align: 'center'}},
alignright: {selector: alignElements, attributes: {align: 'right'}},
alignjustify: {selector: alignElements, attributes: {align: 'justify'}},
// Change the basic formatting elements to use deprecated element types
bold: [
{inline: 'b', remove: 'all'},
{inline: 'strong', remove: 'all'},
{inline: 'span', styles: {fontWeight: 'bold'}}
],
italic: [
{inline: 'i', remove: 'all'},
{inline: 'em', remove: 'all'},
{inline: 'span', styles: {fontStyle: 'italic'}}
],
underline: [
{inline: 'u', remove: 'all'},
{inline: 'span', styles: {textDecoration: 'underline'}, exact: true}
],
strikethrough: [
{inline: 'strike', remove: 'all'},
{inline: 'span', styles: {textDecoration: 'line-through'}, exact: true}
],
// Change font size and font family to use the deprecated font element
fontname: {inline: 'font', attributes: {face: '%value'}},
fontsize: {
inline: 'font',
attributes: {
size: function(vars) {
return tinymce.inArray(fontSizes, vars.value) + 1;
}
}
},
// Setup font elements for colors as well
forecolor: {inline: 'font', attributes: {color: '%value'}},
hilitecolor: {inline: 'font', styles: {backgroundColor: '%value'}}
});
// Check that deprecated elements are allowed if not add them
tinymce.each('b,i,u,strike'.split(','), function(name) {
schema.addValidElements(name + '[*]');
});
// Add font element if it's missing
if (!schema.getElementRule("font")) {
schema.addValidElements("font[face|size|color|style]");
}
// Add the missing and depreacted align attribute for the serialization engine
tinymce.each(alignElements.split(','), function(name) {
var rule = schema.getElementRule(name);
if (rule) {
if (!rule.attributes.align) {
rule.attributes.align = {};
rule.attributesOrder.push('align');
}
}
});
});
editor.addButton('fontsizeselect', function() {
var items = [], defaultFontsizeFormats = '8pt=1 10pt=2 12pt=3 14pt=4 18pt=5 24pt=6 36pt=7';
var fontsize_formats = editor.settings.fontsize_formats || defaultFontsizeFormats;
editor.$.each(fontsize_formats.split(' '), function(i, item) {
var text = item, value = item;
var values = item.split('=');
if (values.length > 1) {
text = values[0];
value = values[1];
}
items.push({text: text, value: value});
});
return {
type: 'listbox',
text: 'Font Sizes',
tooltip: 'Font Sizes',
values: items,
fixedWidth: true,
onPostRender: function() {
var self = this;
editor.on('NodeChange', function() {
var fontElm;
fontElm = editor.dom.getParent(editor.selection.getNode(), 'font');
if (fontElm) {
self.value(fontElm.size);
} else {
self.value('');
}
});
},
onclick: function(e) {
if (e.control.settings.value) {
editor.execCommand('FontSize', false, e.control.settings.value);
}
}
};
});
editor.addButton('fontselect', function() {
function createFormats(formats) {
formats = formats.replace(/;$/, '').split(';');
var i = formats.length;
while (i--) {
formats[i] = formats[i].split('=');
}
return formats;
}
var defaultFontsFormats =
'Andale Mono=andale mono,times;' +
'Arial=arial,helvetica,sans-serif;' +
'Arial Black=arial black,avant garde;' +
'Book Antiqua=book antiqua,palatino;' +
'Comic Sans MS=comic sans ms,sans-serif;' +
'Courier New=courier new,courier;' +
'Georgia=georgia,palatino;' +
'Helvetica=helvetica;' +
'Impact=impact,chicago;' +
'Symbol=symbol;' +
'Tahoma=tahoma,arial,helvetica,sans-serif;' +
'Terminal=terminal,monaco;' +
'Times New Roman=times new roman,times;' +
'Trebuchet MS=trebuchet ms,geneva;' +
'Verdana=verdana,geneva;' +
'Webdings=webdings;' +
'Wingdings=wingdings,zapf dingbats';
var items = [], fonts = createFormats(editor.settings.font_formats || defaultFontsFormats);
$.each(fonts, function(i, font) {
items.push({
text: {raw: font[0]},
value: font[1],
textStyle: font[1].indexOf('dings') == -1 ? 'font-family:' + font[1] : ''
});
});
return {
type: 'listbox',
text: 'Font Family',
tooltip: 'Font Family',
values: items,
fixedWidth: true,
onPostRender: function() {
var self = this;
editor.on('NodeChange', function() {
var fontElm;
fontElm = editor.dom.getParent(editor.selection.getNode(), 'font');
if (fontElm) {
self.value(fontElm.face);
} else {
self.value('');
}
});
},
onselect: function(e) {
if (e.control.settings.value) {
editor.execCommand('FontName', false, e.control.settings.value);
}
}
};
});
});
})(tinymce);
|
test/integration/image-component/base-path/pages/missing-src.js
|
JeromeFitz/next.js
|
import React from 'react'
import Image from 'next/image'
const Page = () => {
return (
<div>
<Image width={200}></Image>
</div>
)
}
export default Page
|
src/js/MethodControlSaturate.js
|
majofeechiou/drawing-board
|
'use strict';
import React from 'react';
import GloablTools from './GloablTools';
import Extend from 'Extend';
import Settings from './Settings';
import GloablData from './GloablData';
import MethodActions from './MethodActions';
export default class MethodControlSaturate extends React.Component {
constructor(props) {
super(props);
this.arrangeProps( props );
this.handleChangeRange = this.handleChangeRange.bind(this);
this.submitAction = this.submitAction.bind(this);
this.prevewAction = this.prevewAction.bind(this);
this.listenPreviewImageChange = this.listenPreviewImageChange.bind(this);
}
componentWillMount(){
let _scope = this;
GloablTools.Emitter().on('preview.image.object.data.changing', _scope.listenPreviewImageChange );
}
componentWillUnmount(){
let _scope = this;
GloablTools.Emitter().off('preview.image.object.data.changing', _scope.listenPreviewImageChange );
}
getComponentMethod(){
return Settings.METHOD_SATURATE;
}
componentWillReceiveProps(nextProps){
this.arrangeProps(nextProps);
}
listenPreviewImageChange(){
let _scope = this;
let _json_new = _scope.arrangeState({imgObj:{src:GloablData.getImageObjectSrc()}});
_scope.setState( _json_new );
}
arrangeState( json ){
json = json || {} ;
let _json_output = Extend.deep(
{},
{ control: this.props.control },
this.state,
{ control:
{
range: (this.refs && this.refs.range)? Number(this.refs.range.value) : Number(this.props.control.range)
}
},
{ imgObj:
{
src: ( this.state && this.state.imgObj )? this.state.imgObj.src : GloablData.getImageObjectSrc()
}
}
);
return Extend.deep( _json_output, json );
}
getNowImageDataBase64(){
let _data_now = GloablData.getNowImageData() ;
return _data_now.data;
}
arrangeProps(json_next, callback){
let _str_base64 = this.getNowImageDataBase64() ;
if( this.state ){
this.setState( {
control: json_next.control,
imgObj: this.state.imgObj
} );
}else{
this.state = {
control:json_next.control,
imgObj: {
src: _str_base64 || GloablData.getImageObjectSrc()
}
};
}
if( callback ){
callback();
}
}
prevewAction(){
let _scope = this;
GloablTools.Emitter().emit( 'method.cotroller.previewing', {
from: GloablData.getFrom(),
method: _scope.getComponentMethod(),
control: _scope.state.control
} );
}
submitAction(){
let _scope = this;
GloablTools.Emitter().emit( 'method.cotroller.control.asking', {
from: GloablData.getFrom(),
method: _scope.getComponentMethod(),
control: _scope.state.control
} );
}
handleChangeRange(e) {
let _json_new = Extend.deep( this.state, {
control: {
range: Number(this.refs.range.value)
}
} );
this.setState( _json_new );
}
render(){
let _scope = this;
let _str_img_src = ( this.state && this.state.imgObj )? this.state.imgObj.src : '' ;
return (
<div className="pkg-control">
<If condition={ _str_img_src && (typeof _str_img_src === 'string') && _str_img_src!=='' }>
<div className="pkg-control-right pkg-conpreview">
<img src={_str_img_src} className="pkg-conpreview-image" />
</div>
</If>
<div className="pkg-control-left ui-center">
<div className="pkg-range">
<input
className="pkg-range-opt"
type="range"
ref="range"
step="1"
min="-100"
max="100"
value={this.state.control.range}
onChange={this.handleChangeRange} />
<span className="pkg-range-show">{this.state.control.range} / 100</span>
</div>
<MethodActions
prevewAction={_scope.prevewAction}
submitAction={_scope.submitAction} />
</div>
</div>
);
}
};
MethodControlSaturate.propTypes = {
control: React.PropTypes.object,
},
MethodControlSaturate.defaultProps = {
control: {},
};
|
ajax/libs/react-swipe/2.0.3/react-swipe.js
|
honestree/cdnjs
|
(function (root, factory) {
if (typeof module !== 'undefined' && module.exports) {
module.exports = factory(
require('react/addons'),
require('swipe-js-iso')
);
} else {
root.ReactSwipe = factory(
root.React,
root.Swipe
);
}
})(this, function (React, Swipe) {
var styles = {
container: {
overflow: 'hidden',
visibility: 'hidden',
position: 'relative'
},
wrapper: {
overflow: 'hidden',
position: 'relative'
},
child: {
float: 'left',
width: '100%',
position: 'relative'
}
};
var ReactSwipe = React.createClass({
// https://github.com/thebird/Swipe#config-options
propTypes: {
startSlide : React.PropTypes.number,
slideToIndex : React.PropTypes.number,
speed : React.PropTypes.number,
auto : React.PropTypes.number,
continuous : React.PropTypes.bool,
disableScroll : React.PropTypes.bool,
stopPropagation : React.PropTypes.bool,
callback : React.PropTypes.func,
transitionEnd : React.PropTypes.func
},
componentDidMount: function () {
if (this.isMounted()) {
this.swipe = Swipe(this.getDOMNode(), this.props);
}
},
componentDidUpdate: function () {
if (this.props.slideToIndex) {
this.swipe.slide(this.props.slideToIndex);
}
},
componentWillUnmount: function () {
this.swipe.kill();
delete this.swipe;
},
shouldComponentUpdate: function (nextProps) {
return this.props.slideToIndex !== nextProps.slideToIndex;
},
render: function() {
return React.createElement('div', React.__spread({}, this.props, {style: styles.container}),
React.createElement('div', {style: styles.wrapper},
React.Children.map(this.props.children, function (child) {
return React.addons.cloneWithProps(child, {style: styles.child});
})
)
);
}
});
return ReactSwipe;
});
|
client/src/pages/welcome.js
|
otavioarc/freeCodeCamp
|
import React from 'react';
import PropTypes from 'prop-types';
import { navigate } from 'gatsby';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { Grid, Row, Col, Button } from '@freecodecamp/react-bootstrap';
import Helmet from 'react-helmet';
import { Loader, Spacer } from '../components/helpers';
import Layout from '../components/layouts/Default';
import { userSelector, userFetchStateSelector } from '../redux';
import { randomQuote } from '../utils/get-words';
import './welcome.css';
const propTypes = {
fetchState: PropTypes.shape({
pending: PropTypes.bool,
complete: PropTypes.bool,
errored: PropTypes.bool
}),
user: PropTypes.shape({
acceptedPrivacyTerms: PropTypes.bool,
username: PropTypes.string,
completedChallengeCount: PropTypes.number,
completedProjectCount: PropTypes.number,
completedCertCount: PropTypes.number,
completedLegacyCertCount: PropTypes.number
})
};
const mapStateToProps = createSelector(
userFetchStateSelector,
userSelector,
(fetchState, user) => ({ fetchState, user })
);
const mapDispatchToProps = dispatch => bindActionCreators({}, dispatch);
function Welcome({
fetchState: { pending, complete },
user: {
acceptedPrivacyTerms,
name = '',
completedChallengeCount = 0,
completedProjectCount = 0,
completedCertCount = 0,
completedLegacyCertCount = 0
}
}) {
if (pending && !complete) {
return (
<Layout>
<div className='loader-wrapper'>
<Loader />
</div>
</Layout>
);
}
if (!acceptedPrivacyTerms) {
navigate('/accept-privacy-terms');
return null;
}
const { quote, author } = randomQuote();
return (
<Layout>
<Helmet>
<title>Welcome {name ? name : 'Camper'} | freeCodeCamp.org</title>
</Helmet>
<main>
<Grid className='text-center'>
<Row>
<Col xs={12}>
<Spacer />
<h1 className='big-heading'>Welcome {name ? name : 'Camper'}!</h1>
</Col>
</Row>
<Spacer />
<Row>
<Col sm={8} smOffset={2} xs={12}>
<a
className='update-link'
href='/n/7gR5pBM-K?refsource=userhome'
target='_blank'
>
We're building a massive open dataset about new coders. Take the
2018 New Coder Survey. It only takes 5 minutes.
</a>
</Col>
</Row>
<Spacer />
<Row className='quote-partial'>
<Col sm={10} smOffset={1} xs={12}>
<blockquote className='blockquote'>
<span>
<q>{quote}</q>
<footer className='quote-author blockquote-footer'>
<cite>{author}</cite>
</footer>
</span>
</blockquote>
</Col>
</Row>
<Spacer />
<Row>
<Col sm={8} smOffset={2} xs={12}>
<p className='stats'>
You have completed <span>{completedChallengeCount}</span> of{' '}
<span>1408</span> coding challenges.
</p>
<p className='stats'>
You have built <span>{completedProjectCount}</span> of{' '}
<span>30</span> projects.
</p>
{completedLegacyCertCount ? (
<p className='stats'>
You have earned <span>{completedLegacyCertCount}</span> of{' '}
<span>4</span> legacy certifications.
</p>
) : null}
<p className='stats'>
You have earned <span>{completedCertCount}</span> of{' '}
<span>6</span> certifications.
</p>
</Col>
</Row>
<Spacer />
<Row>
<Col sm={8} smOffset={2} xs={12}>
<Button block={true} bsStyle='primary' className='btn-cta-big'>
Go to my next challenge
</Button>
</Col>
</Row>
<Spacer size={4} />
</Grid>
</main>
</Layout>
);
}
Welcome.displayName = 'Welcome';
Welcome.propTypes = propTypes;
export default connect(
mapStateToProps,
mapDispatchToProps
)(Welcome);
|
ajax/libs/F2/1.3.0/f2.js
|
ppoffice/cdnjs
|
;(function(exports) {
if (exports.F2 && !exports.F2_TESTING_MODE) {
return;
}
/*!
JSON.org requires the following notice to accompany json2:
Copyright (c) 2002 JSON.org
http://json.org
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
/*
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (typeof JSON !== 'object') {
JSON = {};
}
(function () {
'use strict';
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function (key) {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function (key) {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({'': j}, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());
/*!
* jQuery JavaScript Library v1.8.3
* The jQuery Foundation and other contributors require the following notice to accompany jQuery:
*
* Copyright (c) 2013 jQuery Foundation and other contributors
*
* http://jquery.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
* IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
(function( window, undefined ) {
var
// A central reference to the root jQuery(document)
rootjQuery,
// The deferred used on DOM ready
readyList,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
location = window.location,
navigator = window.navigator,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// Save a reference to some core methods
core_push = Array.prototype.push,
core_slice = Array.prototype.slice,
core_indexOf = Array.prototype.indexOf,
core_toString = Object.prototype.toString,
core_hasOwn = Object.prototype.hasOwnProperty,
core_trim = String.prototype.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,
// Used for detecting and trimming whitespace
core_rnotwhite = /\S/,
core_rspace = /\s+/,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return ( letter + "" ).toUpperCase();
},
// The ready event handler and self cleanup method
DOMContentLoaded = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
} else if ( document.readyState === "complete" ) {
// we're here because readyState === "complete" in oldIE
// which is good enough for us to call the dom ready!
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
},
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = ( context && context.nodeType ? context.ownerDocument || context : document );
// scripts is true for back-compat
selector = jQuery.parseHTML( match[1], doc, true );
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
this.attr.call( selector, context, true );
}
return jQuery.merge( this, selector );
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.8.3",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
eq: function( i ) {
i = +i;
return i === -1 ?
this.slice( i ) :
this.slice( i, i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ),
"slice", core_slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ core_toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// scripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, scripts ) {
var parsed;
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
scripts = context;
context = 0;
}
context = context || document;
// Single tag
if ( (parsed = rsingleTag.exec( data )) ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] );
return jQuery.merge( [],
(parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes );
},
parseJSON: function( data ) {
if ( !data || typeof data !== "string") {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && core_rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var name,
i = 0,
length = obj.length,
isObj = length === undefined || jQuery.isFunction( obj );
if ( args ) {
if ( isObj ) {
for ( name in obj ) {
if ( callback.apply( obj[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( obj[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in obj ) {
if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var type,
ret = results || [];
if ( arr != null ) {
// The window, strings (and functions) also have 'length'
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
type = jQuery.type( arr );
if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) {
core_push.call( ret, arr );
} else {
jQuery.merge( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value, key,
ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, pass ) {
var exec,
bulk = key == null,
i = 0,
length = elems.length;
// Sets many values
if ( key && typeof key === "object" ) {
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], 1, emptyGet, value );
}
chainable = 1;
// Sets one value
} else if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = pass === undefined && jQuery.isFunction( value );
if ( bulk ) {
// Bulk operations only iterate when executing function values
if ( exec ) {
exec = fn;
fn = function( elem, key, value ) {
return exec.call( jQuery( elem ), value );
};
// Otherwise they run against the entire set
} else {
fn.call( elems, value );
fn = null;
}
}
if ( fn ) {
for (; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
}
chainable = 1;
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready, 1 );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.split( core_rspace ), function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Control if a given callback is in the list
has: function( fn ) {
return jQuery.inArray( fn, list ) > -1;
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ]( jQuery.isFunction( fn ) ?
function() {
var returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
}
} :
newDefer[ action ]
);
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ] = list.fire
deferred[ tuple[0] ] = list.fire;
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function() {
var support,
all,
a,
select,
opt,
input,
fragment,
eventName,
i,
isSupported,
clickFn,
div = document.createElement("div");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Support tests won't run in some limited or non-browser environments
all = div.getElementsByTagName("*");
a = div.getElementsByTagName("a")[ 0 ];
if ( !all || !a || !all.length ) {
return {};
}
// First batch of tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: ( div.firstChild.nodeType === 3 ),
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: ( a.getAttribute("href") === "/a" ),
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.5/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: ( input.value === "on" ),
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// Tests for enctype support on a form (#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
boxModel: ( document.compatMode === "CSS1Compat" ),
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
boxSizingReliable: true,
pixelPosition: false
};
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
div.attachEvent( "onclick", clickFn = function() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
});
div.cloneNode( true ).fireEvent("onclick");
div.detachEvent( "onclick", clickFn );
}
// Check if a radio maintains its value
// after being appended to the DOM
input = document.createElement("input");
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
input.setAttribute( "checked", "checked" );
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "name", "t" );
div.appendChild( input );
fragment = document.createDocumentFragment();
fragment.appendChild( div.lastChild );
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
fragment.removeChild( input );
fragment.appendChild( div );
// Technique from Juriy Zaytsev
// http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
// We only care about the case where non-standard event systems
// are used, namely in IE. Short-circuiting here helps us to
// avoid an eval call (in setAttribute) which can cause CSP
// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
if ( div.attachEvent ) {
for ( i in {
submit: true,
change: true,
focusin: true
}) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) {
div.setAttribute( eventName, "return;" );
isSupported = ( typeof div[ eventName ] === "function" );
}
support[ i + "Bubbles" ] = isSupported;
}
}
// Run tests that need a body at doc ready
jQuery(function() {
var container, div, tds, marginDiv,
divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px";
body.insertBefore( container, body.firstChild );
// Construct the test element
div = document.createElement("div");
container.appendChild( div );
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE <= 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior
div.innerHTML = "";
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
support.boxSizing = ( div.offsetWidth === 4 );
support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );
// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = document.createElement("div");
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
div.appendChild( marginDiv );
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== "undefined" ) {
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
// (IE < 8 does this)
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "block";
div.style.overflow = "visible";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
container.style.zoom = 1;
}
// Null elements to avoid leaks in IE
body.removeChild( container );
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
fragment.removeChild( div );
all = a = select = opt = input = fragment = div = null;
return support;
})();
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
jQuery.extend({
cache: {},
deletedIds: [],
// Remove at next major release (1.9/2.0)
uuid: 0,
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i, l,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
},
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var parts, part, attr, name, l,
elem = this[0],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attr = elem.attributes;
for ( l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( !name.indexOf( "data-" ) ) {
name = jQuery.camelCase( name.substring(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
parts = key.split( ".", 2 );
parts[1] = parts[1] ? "." + parts[1] : "";
part = parts[1] + "!";
return jQuery.access( this, function( value ) {
if ( value === undefined ) {
data = this.triggerHandler( "getData" + part, [ parts[0] ] );
// Try to fetch any internally stored data first
if ( data === undefined && elem ) {
data = jQuery.data( elem, key );
data = dataAttr( elem, key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
}
parts[1] = value;
this.each(function() {
var self = jQuery( this );
self.triggerHandler( "setData" + part, parts );
jQuery.data( this, key, value );
self.triggerHandler( "changeData" + part, parts );
});
}, null, value, arguments.length > 1, null, false );
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery.removeData( elem, type + "queue", true );
jQuery.removeData( elem, key, true );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook, fixSpecified,
rclass = /[\t\r\n]/g,
rreturn = /\r/g,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea|)$/i,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classNames, i, l, elem,
setClass, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call(this, j, this.className) );
});
}
if ( value && typeof value === "string" ) {
classNames = value.split( core_rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
var removes, className, elem, c, cl, i, l;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call(this, j, this.className) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
removes = ( value || "" ).split( core_rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 && elem.className ) {
className = (" " + elem.className + " ").replace( rclass, " " );
// loop over each item in the removal list
for ( c = 0, cl = removes.length; c < cl; c++ ) {
// Remove until there is nothing to remove,
while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) {
className = className.replace( " " + removes[ c ] + " " , " " );
}
}
elem.className = value ? jQuery.trim( className ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( core_rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val,
self = jQuery(this);
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
// Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9
attrFn: {},
attr: function( elem, name, value, pass ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) {
return jQuery( elem )[ name ]( value );
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var propName, attrNames, name, isBool,
i = 0;
if ( value && elem.nodeType === 1 ) {
attrNames = value.split( core_rspace );
for ( ; i < attrNames.length; i++ ) {
name = attrNames[ i ];
if ( name ) {
propName = jQuery.propFix[ name ] || name;
isBool = rboolean.test( name );
// See #9699 for explanation of this approach (setting first, then removal)
// Do not do this for boolean attributes (see #10870)
if ( !isBool ) {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
// Set corresponding property to false for boolean attributes
if ( isBool && propName in elem ) {
elem[ propName ] = false;
}
}
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to it's default in case type is set after value
// This is for element creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
},
// Use the value property for back compat
// Use the nodeHook for button elements in IE6/7 (#1954)
value: {
get: function( elem, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.get( elem, name );
}
return name in elem ?
elem.value :
null;
},
set: function( elem, value, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.set( elem, value, name );
}
// Does not return so that setAttribute is also used
elem.value = value;
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return ( elem[ name ] = value );
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
}
});
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode,
property = jQuery.prop( elem, name );
return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
fixSpecified = {
name: true,
id: true,
coords: true
};
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret;
ret = elem.getAttributeNode( name );
return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ?
ret.value :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
ret = document.createAttribute( name );
elem.setAttributeNode( ret );
}
return ( ret.value = value + "" );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
if ( value === "" ) {
value = "false";
}
nodeHook.set( elem, value, name );
}
};
}
// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret === null ? undefined : ret;
}
});
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Normalize to lowercase since IE uppercases css property names
return elem.style.cssText.toLowerCase() || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
});
});
var rformElems = /^(?:textarea|input|select)$/i,
rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/,
rhoverHack = /(?:^|\s)hover(\.\S+|)\b/,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
hoverHack = function( events ) {
return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
};
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
add: function( elem, types, handler, data, selector ) {
var elemData, eventHandle, events,
t, tns, type, namespaces, handleObj,
handleObjIn, handlers, special;
// Don't attach events to noData or text/comment nodes (allow plain objects tho)
if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
events = elemData.events;
if ( !events ) {
elemData.events = events = {};
}
eventHandle = elemData.handle;
if ( !eventHandle ) {
elemData.handle = eventHandle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = jQuery.trim( hoverHack(types) ).split( " " );
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = tns[1];
namespaces = ( tns[2] || "" ).split( "." ).sort();
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: tns[1],
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
handlers = events[ type ];
if ( !handlers ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var t, tns, type, origType, namespaces, origCount,
j, events, special, eventType, handleObj,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = jQuery.trim( hoverHack( types || "" ) ).split(" ");
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = origType = tns[1];
namespaces = tns[2];
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector? special.delegateType : special.bindType ) || type;
eventType = events[ type ] || [];
origCount = eventType.length;
namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
// Remove matching events
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !namespaces || namespaces.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
eventType.splice( j--, 1 );
if ( handleObj.selector ) {
eventType.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( eventType.length === 0 && origCount !== eventType.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery.removeData( elem, "events", true );
}
},
// Events that are safe to short-circuit if no handlers are attached.
// Native DOM events should not be added, they may have inline handlers.
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function( event, data, elem, onlyHandlers ) {
// Don't do events on text and comment nodes
if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {
return;
}
// Event object or event type
var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType,
type = event.type || event,
namespaces = [];
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "!" ) >= 0 ) {
// Exclusive events trigger only for the exact event (no namespaces)
type = type.slice(0, -1);
exclusive = true;
}
if ( type.indexOf( "." ) >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
// No jQuery handlers for this event type, and it can't have inline handlers
return;
}
// Caller can pass in an Event, Object, or just an event type string
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
new jQuery.Event( type, event ) :
// Just the event type (string)
new jQuery.Event( type );
event.type = type;
event.isTrigger = true;
event.exclusive = exclusive;
event.namespace = namespaces.join( "." );
event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";
// Handle a global trigger
if ( !elem ) {
// TODO: Stop taunting the data cache; remove global events and always attach to document
cache = jQuery.cache;
for ( i in cache ) {
if ( cache[ i ].events && cache[ i ].events[ type ] ) {
jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );
}
}
return;
}
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data != null ? jQuery.makeArray( data ) : [];
data.unshift( event );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
eventPath = [[ elem, special.bindType || type ]];
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;
for ( old = elem; cur; cur = cur.parentNode ) {
eventPath.push([ cur, bubbleType ]);
old = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( old === (elem.ownerDocument || document) ) {
eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
}
}
// Fire handlers on the event path
for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {
cur = eventPath[i][0];
event.type = eventPath[i][1];
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Note that this is a bare JS function and not a jQuery handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
// IE<9 dies on focus/blur to hidden element (#1486)
if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = elem[ ontype ];
if ( old ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( old ) {
elem[ ontype ] = old;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event || window.event );
var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related,
handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
delegateCount = handlers.delegateCount,
args = core_slice.call( arguments ),
run_all = !event.exclusive && !event.namespace,
special = jQuery.event.special[ event.type ] || {},
handlerQueue = [];
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers that should run if there are delegated events
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && !(event.button && event.type === "click") ) {
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
// Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
selMatch = {};
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
sel = handleObj.selector;
if ( selMatch[ sel ] === undefined ) {
selMatch[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( selMatch[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, matches: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( handlers.length > delegateCount ) {
handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
}
// Run delegates first; they may want to stop propagation beneath us
for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
matched = handlerQueue[ i ];
event.currentTarget = matched.elem;
for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
handleObj = matched.matches[ j ];
// Triggered event must either 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {
event.data = handleObj.data;
event.handleObj = handleObj;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
// Includes some event props shared by KeyEvent and MouseEvent
// *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 ***
props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop,
originalEvent = event,
fixHook = jQuery.event.fixHooks[ event.type ] || {},
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = jQuery.Event( originalEvent );
for ( i = copy.length; i; ) {
prop = copy[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary (#1925, IE 6/7/8 & Safari2)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Target should not be a text node (#504, Safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8)
event.metaKey = !!event.metaKey;
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
// Some plugins are using, but it's undocumented/deprecated and will be removed.
// The 1.7 special event interface should provide all the hooks needed now.
jQuery.event.handle = jQuery.event.dispatch;
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === "undefined" ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj,
selector = handleObj.selector;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "_submit_attached" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "_submit_attached", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "_change_attached", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) { // && selector != null
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
if ( rkeyEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
}
if ( rmouseEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://sizzlejs.com/
*/
(function( window, undefined ) {
var cachedruns,
assertGetIdNotName,
Expr,
getText,
isXML,
contains,
compile,
sortOrder,
hasDuplicate,
outermostContext,
baseHasDuplicate = true,
strundefined = "undefined",
expando = ( "sizcache" + Math.random() ).replace( ".", "" ),
Token = String,
document = window.document,
docElem = document.documentElement,
dirruns = 0,
done = 0,
pop = [].pop,
push = [].push,
slice = [].slice,
// Use a stripped-down indexOf if a native one is unavailable
indexOf = [].indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
// Augment a function for special use by Sizzle
markFunction = function( fn, value ) {
fn[ expando ] = value == null || value;
return fn;
},
createCache = function() {
var cache = {},
keys = [];
return markFunction(function( key, value ) {
// Only keep the most recent entries
if ( keys.push( key ) > Expr.cacheLength ) {
delete cache[ keys.shift() ];
}
// Retrieve with (key + " ") to avoid collision with native Object.prototype properties (see Issue #157)
return (cache[ key + " " ] = value);
}, cache );
},
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
// Regex
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors)
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
operators = "([*^$|!~]?=)",
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments not in parens/brackets,
// then attribute selectors and non-pseudos (denoted by :),
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)",
// For matchExpr.POS and matchExpr.needsContext
pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace +
"*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
rpseudo = new RegExp( pseudos ),
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,
rnot = /^:not/,
rsibling = /[\x20\t\r\n\f]*[+~]/,
rendsWithNot = /:not\($/,
rheader = /h\d/i,
rinputs = /input|select|textarea|button/i,
rbackslash = /\\(?!\\)/g,
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"POS": new RegExp( pos, "i" ),
"CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
// For use in libraries implementing .is()
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" )
},
// Support
// Used for testing something on an element
assert = function( fn ) {
var div = document.createElement("div");
try {
return fn( div );
} catch (e) {
return false;
} finally {
// release memory in IE
div = null;
}
},
// Check if getElementsByTagName("*") returns only elements
assertTagNameNoComments = assert(function( div ) {
div.appendChild( document.createComment("") );
return !div.getElementsByTagName("*").length;
}),
// Check if getAttribute returns normalized href attributes
assertHrefNotNormalized = assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
div.firstChild.getAttribute("href") === "#";
}),
// Check if attributes should be retrieved by attribute nodes
assertAttributes = assert(function( div ) {
div.innerHTML = "<select></select>";
var type = typeof div.lastChild.getAttribute("multiple");
// IE8 returns a string for some attributes even when not present
return type !== "boolean" && type !== "string";
}),
// Check if getElementsByClassName can be trusted
assertUsableClassName = assert(function( div ) {
// Opera can't find a second classname (in 9.6)
div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {
return false;
}
// Safari 3.2 caches class attributes and doesn't catch changes
div.lastChild.className = "e";
return div.getElementsByClassName("e").length === 2;
}),
// Check if getElementById returns elements by name
// Check if getElementsByName privileges form controls or returns elements by ID
assertUsableName = assert(function( div ) {
// Inject content
div.id = expando + 0;
div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
docElem.insertBefore( div, docElem.firstChild );
// Test
var pass = document.getElementsByName &&
// buggy browsers will return fewer than the correct 2
document.getElementsByName( expando ).length === 2 +
// buggy browsers will return more than the correct 0
document.getElementsByName( expando + 0 ).length;
assertGetIdNotName = !document.getElementById( expando );
// Cleanup
docElem.removeChild( div );
return pass;
});
// If slice is not available, provide a backup
try {
slice.call( docElem.childNodes, 0 )[0].nodeType;
} catch ( e ) {
slice = function( i ) {
var elem,
results = [];
for ( ; (elem = this[i]); i++ ) {
results.push( elem );
}
return results;
};
}
function Sizzle( selector, context, results, seed ) {
results = results || [];
context = context || document;
var match, elem, xml, m,
nodeType = context.nodeType;
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( nodeType !== 1 && nodeType !== 9 ) {
return [];
}
xml = isXML( context );
if ( !xml && !seed ) {
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) {
push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );
return results;
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed, xml );
}
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
return Sizzle( expr, null, null, [ elem ] ).length > 0;
};
// Returns a function to use in pseudos for input types
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
// Returns a function to use in pseudos for buttons
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
// Returns a function to use in pseudos for positionals
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( nodeType ) {
if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
} else {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
}
return ret;
};
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
// Element contains another
contains = Sizzle.contains = docElem.contains ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) );
} :
docElem.compareDocumentPosition ?
function( a, b ) {
return b && !!( a.compareDocumentPosition( b ) & 16 );
} :
function( a, b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
return false;
};
Sizzle.attr = function( elem, name ) {
var val,
xml = isXML( elem );
if ( !xml ) {
name = name.toLowerCase();
}
if ( (val = Expr.attrHandle[ name ]) ) {
return val( elem );
}
if ( xml || assertAttributes ) {
return elem.getAttribute( name );
}
val = elem.getAttributeNode( name );
return val ?
typeof elem[ name ] === "boolean" ?
elem[ name ] ? name : null :
val.specified ? val.value : null :
null;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
// IE6/7 return a modified href
attrHandle: assertHrefNotNormalized ?
{} :
{
"href": function( elem ) {
return elem.getAttribute( "href", 2 );
},
"type": function( elem ) {
return elem.getAttribute("type");
}
},
find: {
"ID": assertGetIdNotName ?
function( id, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
} :
function( id, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( id );
return m ?
m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
[m] :
undefined :
[];
}
},
"TAG": assertTagNameNoComments ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
var elem,
tmp = [],
i = 0;
for ( ; (elem = results[i]); i++ ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
},
"NAME": assertUsableName && function( tag, context ) {
if ( typeof context.getElementsByName !== strundefined ) {
return context.getElementsByName( name );
}
},
"CLASS": assertUsableClassName && function( className, context, xml ) {
if ( typeof context.getElementsByClassName !== strundefined && !xml ) {
return context.getElementsByClassName( className );
}
}
},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( rbackslash, "" );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
3 xn-component of xn+y argument ([+-]?\d*n|)
4 sign of xn-component
5 x of xn-component
6 sign of y-component
7 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1] === "nth" ) {
// nth-child requires argument
if ( !match[2] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) );
match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" );
// other types prohibit arguments
} else if ( match[2] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var unquoted, excess;
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
if ( match[3] ) {
match[2] = match[3];
} else if ( (unquoted = match[4]) ) {
// Only check arguments that contain a pseudo
if ( rpseudo.test(unquoted) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
unquoted = unquoted.slice( 0, excess );
match[0] = match[0].slice( 0, excess );
}
match[2] = unquoted;
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"ID": assertGetIdNotName ?
function( id ) {
id = id.replace( rbackslash, "" );
return function( elem ) {
return elem.getAttribute("id") === id;
};
} :
function( id ) {
id = id.replace( rbackslash, "" );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === id;
};
},
"TAG": function( nodeName ) {
if ( nodeName === "*" ) {
return function() { return true; };
}
nodeName = nodeName.replace( rbackslash, "" ).toLowerCase();
return function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ expando ][ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem, context ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.substr( result.length - check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, argument, first, last ) {
if ( type === "nth" ) {
return function( elem ) {
var node, diff,
parent = elem.parentNode;
if ( first === 1 && last === 0 ) {
return true;
}
if ( parent ) {
diff = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
diff++;
if ( elem === node ) {
break;
}
}
}
}
// Incorporate the offset (or cast to NaN), then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
};
}
return function( elem ) {
var node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
/* falls through */
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
var nodeType;
elem = elem.firstChild;
while ( elem ) {
if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) {
return false;
}
elem = elem.nextSibling;
}
return true;
},
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"text": function( elem ) {
var type, attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
(type = elem.type) === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type );
},
// Input types
"radio": createInputPseudo("radio"),
"checkbox": createInputPseudo("checkbox"),
"file": createInputPseudo("file"),
"password": createInputPseudo("password"),
"image": createInputPseudo("image"),
"submit": createButtonPseudo("submit"),
"reset": createButtonPseudo("reset"),
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"focus": function( elem ) {
var doc = elem.ownerDocument;
return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
"active": function( elem ) {
return elem === elem.ownerDocument.activeElement;
},
// Positional types
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
for ( var i = 0; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
for ( var i = 1; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
function siblingCheck( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
}
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
return ( !a.compareDocumentPosition || !b.compareDocumentPosition ?
a.compareDocumentPosition :
a.compareDocumentPosition(b) & 4
) ? -1 : 1;
} :
function( a, b ) {
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return a.sourceIndex - b.sourceIndex;
}
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// If the nodes are siblings (or identical) we can do a quick check
if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
// Always assume the presence of duplicates if sort doesn't
// pass them to our comparison function (as in Google Chrome).
[0, 0].sort( sortOrder );
baseHasDuplicate = !hasDuplicate;
// Document sorting and removing duplicates
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
i = 1,
j = 0;
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( ; (elem = results[i]); i++ ) {
if ( elem === results[ i - 1 ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ expando ][ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
tokens.push( matched = new Token( match.shift() ) );
soFar = soFar.slice( matched.length );
// Cast descendant combinators to space
matched.type = match[0].replace( rtrim, " " );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
tokens.push( matched = new Token( match.shift() ) );
soFar = soFar.slice( matched.length );
matched.type = type;
matched.matches = match;
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && combinator.dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( checkNonElements || elem.nodeType === 1 ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( !xml ) {
var cache,
dirkey = dirruns + " " + doneName + " ",
cachedkey = dirkey + cachedruns;
while ( (elem = elem[ dir ]) ) {
if ( checkNonElements || elem.nodeType === 1 ) {
if ( (cache = elem[ expando ]) === cachedkey ) {
return elem.sizset;
} else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) {
if ( elem.sizset ) {
return elem;
}
} else {
elem[ expando ] = cachedkey;
if ( matcher( elem, context, xml ) ) {
elem.sizset = true;
return elem;
}
elem.sizset = false;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( checkNonElements || elem.nodeType === 1 ) {
if ( matcher( elem, context, xml ) ) {
return elem;
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && tokens.join("")
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Nested matchers should use non-integer dirruns
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = superMatcher.el;
}
// Add elements passing elementMatchers directly to results
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
for ( j = 0; (matcher = elementMatchers[j]); j++ ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++superMatcher.el;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
for ( j = 0; (matcher = setMatchers[j]); j++ ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
superMatcher.el = 0;
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ expando ][ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed, xml ) {
var i, tokens, token, type, find,
match = tokenize( selector ),
j = match.length;
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
context.nodeType === 9 && !xml &&
Expr.relative[ tokens[1].type ] ) {
context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().length );
}
// Fetch a seed set for right-to-left matching
for ( i = matchExpr["POS"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( rbackslash, "" ),
rsibling.test( tokens[0].type ) && context.parentNode || context,
xml
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && tokens.join("");
if ( !selector ) {
push.apply( results, slice.call( seed, 0 ) );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
xml,
results,
rsibling.test( selector )
);
return results;
}
if ( document.querySelectorAll ) {
(function() {
var disconnectedMatch,
oldSelect = select,
rescape = /'|\\/g,
rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
// qSa(:focus) reports false when true (Chrome 21), no need to also add to buggyMatches since matches checks buggyQSA
// A support test would require too much code (would include document ready)
rbuggyQSA = [ ":focus" ],
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
// A support test would require too much code (would include document ready)
// just skip matchesSelector for :active
rbuggyMatches = [ ":active" ],
matches = docElem.matchesSelector ||
docElem.mozMatchesSelector ||
docElem.webkitMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector;
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explictly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// IE8 - Some boolean attributes are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here (do not put tests after this one)
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Opera 10-12/IE9 - ^= $= *= and empty values
// Should not select anything
div.innerHTML = "<p test=''></p>";
if ( div.querySelectorAll("[test^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here (do not put tests after this one)
div.innerHTML = "<input type='hidden'/>";
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push(":enabled", ":disabled");
}
});
// rbuggyQSA always contains :focus, so no need for a length check
rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") );
select = function( selector, context, results, seed, xml ) {
// Only use querySelectorAll when not filtering,
// when this is not xml,
// and when no QSA bugs apply
if ( !seed && !xml && !rbuggyQSA.test( selector ) ) {
var groups, i,
old = true,
nid = expando,
newContext = context,
newSelector = context.nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + groups[i].join("");
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results, slice.call( newContext.querySelectorAll(
newSelector
), 0 ) );
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
return oldSelect( selector, context, results, seed, xml );
};
if ( matches ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
try {
matches.call( div, "[test!='']:sizzle" );
rbuggyMatches.push( "!=", pseudos );
} catch ( e ) {}
});
// rbuggyMatches always contains :active and :focus, so no need for a length check
rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") );
Sizzle.matchesSelector = function( elem, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
// rbuggyMatches always contains :active, so no need for an existence check
if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && !rbuggyQSA.test( expr ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, null, null, [ elem ] ).length > 0;
};
}
})();
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Back-compat
function setFilters() {}
Expr.filters = setFilters.prototype = Expr.pseudos;
Expr.setFilters = new setFilters();
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
var runtil = /Until$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
isSimple = /^.[^:#\[\.,]*$/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i, l, length, n, r, ret,
self = this;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
ret = this.pushStack( "", "find", selector );
for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
rneedsContext.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
cur = this[i];
while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
}
cur = cur.parentNode;
}
}
ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
jQuery.fn.andSelf = jQuery.fn.addBack;
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( this.length > 1 && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, core_slice.call( arguments ).join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return ( elem === qualifier ) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem, i ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
rnocache = /<(?:script|object|embed|option|style)/i,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rcheckableType = /^(?:checkbox|radio)$/,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
area: [ 1, "<map>", "</map>" ],
_default: [ 0, "", "" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "X<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( set, this ), "before", this.selector );
}
},
after: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( this, set ), "after", this.selector );
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName( "*" ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function( value ) {
if ( !isDisconnected( this[0] ) ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
}
return this.length ?
this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
this;
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
// Flatten any nested arrays
args = [].concat.apply( [], args );
var results, first, fragment, iNoClone,
i = 0,
value = args[0],
scripts = [],
l = this.length;
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call( this, i, table ? self.html() : undefined );
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
results = jQuery.buildFragment( args, this, scripts );
fragment = results.fragment;
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
// Fragments from the fragment cache must always be cloned and never used in place.
for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) {
callback.call(
table && jQuery.nodeName( this[i], "table" ) ?
findOrAppend( this[i], "tbody" ) :
this[i],
i === iNoClone ?
fragment :
jQuery.clone( fragment, true, true )
);
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
if ( scripts.length ) {
jQuery.each( scripts, function( i, elem ) {
if ( elem.src ) {
if ( jQuery.ajax ) {
jQuery.ajax({
url: elem.src,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
} else {
jQuery.error("no ajax");
}
} else {
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
});
}
}
return this;
}
});
function findOrAppend( elem, tag ) {
return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) );
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function cloneFixAttributes( src, dest ) {
var nodeName;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
if ( dest.clearAttributes ) {
dest.clearAttributes();
}
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
nodeName = dest.nodeName.toLowerCase();
if ( nodeName === "object" ) {
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
// IE blanks contents when cloning scripts
} else if ( nodeName === "script" && dest.text !== src.text ) {
dest.text = src.text;
}
// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute( jQuery.expando );
}
jQuery.buildFragment = function( args, context, scripts ) {
var fragment, cacheable, cachehit,
first = args[ 0 ];
// Set context from what may come in as undefined or a jQuery collection or a node
// Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 &
// also doubles as fix for #8950 where plain objects caused createDocumentFragment exception
context = context || document;
context = !context.nodeType && context[0] || context;
context = context.ownerDocument || context;
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document &&
first.charAt(0) === "<" && !rnocache.test( first ) &&
(jQuery.support.checkClone || !rchecked.test( first )) &&
(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {
// Mark cacheable and look for a hit
cacheable = true;
fragment = jQuery.fragments[ first ];
cachehit = fragment !== undefined;
}
if ( !fragment ) {
fragment = context.createDocumentFragment();
jQuery.clean( args, context, fragment, scripts );
// Update the cache, but only store false
// unless this is a second parsing of the same content
if ( cacheable ) {
jQuery.fragments[ first ] = cachehit && fragment;
}
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
l = insert.length,
parent = this.length === 1 && this[0].parentNode;
if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( ; i < l; i++ ) {
elems = ( i > 0 ? this.clone(true) : this ).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
function getAll( elem ) {
if ( typeof elem.getElementsByTagName !== "undefined" ) {
return elem.getElementsByTagName( "*" );
} else if ( typeof elem.querySelectorAll !== "undefined" ) {
return elem.querySelectorAll( "*" );
} else {
return [];
}
}
// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var srcElements,
destElements,
i,
clone;
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName instead
srcElements = getAll( elem );
destElements = getAll( clone );
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents ) {
srcElements = getAll( elem );
destElements = getAll( clone );
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
srcElements = destElements = null;
// Return the cloned set
return clone;
},
clean: function( elems, context, fragment, scripts ) {
var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags,
safe = context === document && safeFragment,
ret = [];
// Ensure that context is a document
if ( !context || typeof context.createDocumentFragment === "undefined" ) {
context = document;
}
// Use the already-created safe fragment if context permits
for ( i = 0; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Ensure a safe container in which to render the html
safe = safe || createSafeFragment( context );
div = context.createElement("div");
safe.appendChild( div );
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Go to html and back, then peel off extra wrappers
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
depth = wrap[0];
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
hasBody = rtbody.test(elem);
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
// Take out of fragment container (we need a fresh div each time)
div.parentNode.removeChild( div );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
jQuery.merge( ret, elem );
}
}
// Fix #11356: Clear elements from safeFragment
if ( div ) {
elem = div = safe = null;
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
for ( i = 0; (elem = ret[i]) != null; i++ ) {
if ( jQuery.nodeName( elem, "input" ) ) {
fixDefaultChecked( elem );
} else if ( typeof elem.getElementsByTagName !== "undefined" ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
}
// Append elements to a provided document fragment
if ( fragment ) {
// Special handling of each script element
handleScript = function( elem ) {
// Check if we consider it executable
if ( !elem.type || rscriptType.test( elem.type ) ) {
// Detach the script and store it in the scripts array (if provided) or the fragment
// Return truthy to indicate that it has been handled
return scripts ?
scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) :
fragment.appendChild( elem );
}
};
for ( i = 0; (elem = ret[i]) != null; i++ ) {
// Check if we're done after handling an executable script
if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) {
// Append to fragment and handle embedded scripts
fragment.appendChild( elem );
if ( typeof elem.getElementsByTagName !== "undefined" ) {
// handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration
jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript );
// Splice the scripts into ret after their former ancestor and advance our index beyond them
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
i += jsTags.length;
}
}
}
}
return ret;
},
cleanData: function( elems, /* internal */ acceptData ) {
var data, id, elem, type,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
jQuery.deletedIds.push( id );
}
}
}
}
}
});
// Limit scope pollution from any deprecated API
(function() {
var matched, browser;
// Use of jQuery.browser is frowned upon.
// More details: http://api.jquery.com/jQuery.browser
// jQuery.uaMatch maintained for back-compat
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
matched = jQuery.uaMatch( navigator.userAgent );
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = browser;
jQuery.sub = function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
};
})();
var curCSS, iframe, iframeDoc,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ),
elemdisplay = { BODY: "block" },
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ],
eventsToggle = jQuery.fn.toggle;
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function isHidden( elem, el ) {
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
function showHide( elements, show ) {
var elem, display,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && elem.style.display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
display = curCSS( elem, "display" );
if ( !values[ index ] && display !== "none" ) {
jQuery._data( elem, "olddisplay", display );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.fn.extend({
css: function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state, fn2 ) {
var bool = typeof state === "boolean";
if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) {
return eventsToggle.apply( this, arguments );
}
return this.each(function() {
if ( bool ? state : isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, numeric, extra ) {
var val, num, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( numeric || extra !== undefined ) {
num = parseFloat( val );
return numeric || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
curCSS = function( elem, name ) {
var ret, width, minWidth, maxWidth,
computed = window.getComputedStyle( elem, null ),
style = elem.style;
if ( computed ) {
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed.getPropertyValue( name ) || computed[ name ];
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if ( document.documentElement.currentStyle ) {
curCSS = function( elem, name ) {
var left, rsLeft,
ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
// we use jQuery.css instead of curCSS here
// because of the reliableMarginRight CSS hook!
val += jQuery.css( elem, extra + cssExpand[ i ], true );
}
// From this point on we use curCSS for maximum performance (relevant in animations)
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
} else {
// at this point, extra isn't content, so add padding
val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
valueIsBorderBox = true,
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
if ( elemdisplay[ nodeName ] ) {
return elemdisplay[ nodeName ];
}
var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ),
display = elem.css("display");
elem.remove();
// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if ( display === "none" || display === "" ) {
// Use the already-created iframe if possible
iframe = document.body.appendChild(
iframe || jQuery.extend( document.createElement("iframe"), {
frameBorder: 0,
width: 0,
height: 0
})
);
// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
// document to it; WebKit & Firefox won't allow reusing the iframe document.
if ( !iframeDoc || !iframe.createElement ) {
iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
iframeDoc.write("<!doctype html><html><body>");
iframeDoc.close();
}
elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) );
display = curCSS( elem, "display" );
document.body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
return display;
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) {
return jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
});
} else {
return getWidthOrHeight( elem, name, extra );
}
}
},
set: function( elem, value, extra ) {
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"
) : 0
);
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there there is no filter style applied in a css rule, we are done
if ( currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" }, function() {
if ( computed ) {
return curCSS( elem, "marginRight" );
}
});
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
var ret = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i,
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ],
expanded = {};
for ( i = 0; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
rselectTextarea = /^(?:select|textarea)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
var
// Document location
ajaxLocParts,
ajaxLocation,
rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rts = /([?&])_=[^&]*/,
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = ["*/"] + ["*"];
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType, list, placeBefore,
dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ),
i = 0,
length = dataTypes.length;
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
for ( ; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
dataType /* internal */, inspected /* internal */ ) {
dataType = dataType || options.dataTypes[ 0 ];
inspected = inspected || {};
inspected[ dataType ] = true;
var selection,
list = structure[ dataType ],
i = 0,
length = list ? list.length : 0,
executeOnly = ( structure === prefilters );
for ( ; i < length && ( executeOnly || !selection ); i++ ) {
selection = list[ i ]( options, originalOptions, jqXHR );
// If we got redirected to another dataType
// we try there if executing only and not done already
if ( typeof selection === "string" ) {
if ( !executeOnly || inspected[ selection ] ) {
selection = undefined;
} else {
options.dataTypes.unshift( selection );
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, selection, inspected );
}
}
}
// If we're only executing or nothing was selected
// we try the catchall dataType if not done already
if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, "*", inspected );
}
// unnecessary when only executing (prefilters)
// but it'll be ignored by the caller in that case
return selection;
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
}
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
// Don't do a request if no elements are being requested
if ( !this.length ) {
return this;
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// Request the remote document
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params,
complete: function( jqXHR, status ) {
if ( callback ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
}
}
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append( responseText.replace( rscript, "" ) )
// Locate the specified elements
.find( selector ) :
// If not, just inject the full result
responseText );
});
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
jQuery.fn[ o ] = function( f ){
return this.on( o, f );
};
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
});
jQuery.extend({
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
if ( settings ) {
// Building a settings object
ajaxExtend( target, jQuery.ajaxSettings );
} else {
// Extending ajaxSettings
settings = target;
target = jQuery.ajaxSettings;
}
ajaxExtend( target, settings );
return target;
},
ajaxSettings: {
url: ajaxLocation,
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
processData: true,
async: true,
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": allTypes
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// List of data converters
// 1) key format is "source_type destination_type" (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
context: true,
url: true
}
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // ifModified key
ifModifiedKey,
// Response headers
responseHeadersString,
responseHeaders,
// transport
transport,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext = callbackContext !== s &&
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks( "once memory" ),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
var lname = name.toLowerCase();
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Cancel the request
abort: function( statusText ) {
statusText = statusText || strAbort;
if ( transport ) {
transport.abort( statusText );
}
done( 0, statusText );
return this;
}
};
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ ifModifiedKey ] = modified;
}
modified = jqXHR.getResponseHeader("Etag");
if ( modified ) {
jQuery.etag[ ifModifiedKey ] = modified;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
isSuccess = ajaxConvert( s, response );
statusText = isSuccess.state;
success = isSuccess.data;
error = isSuccess.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( !statusText || status ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Attach deferreds
deferred.promise( jqXHR );
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.add;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for ( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.always( tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace );
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey = s.url;
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
}
if ( jQuery.etag[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
}
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout( function(){
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch (e) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
return jqXHR;
},
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var ct, type, finalDataType, firstDataType,
contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields;
// Fill responseXXX fields
for ( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
var conv, conv2, current, tmp,
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice(),
prev = dataTypes[ 0 ],
converters = {},
i = 0;
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
// Convert to each sequential dataType, tolerating list modification
for ( ; (current = dataTypes[++i]); ) {
// There's only work to do if current dataType is non-auto
if ( current !== "*" ) {
// Convert response if prev dataType is non-auto and differs from current
if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split(" ");
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.splice( i--, 0, current );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s["throws"] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
// Update prev for next iteration
prev = current;
}
}
return { state: "success", data: response };
}
var oldCallbacks = [],
rquestion = /\?/,
rjsonp = /(=)\?(?=&|$)|\?\?/,
nonce = jQuery.now();
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
data = s.data,
url = s.url,
hasCallback = s.jsonp !== false,
replaceInUrl = hasCallback && rjsonp.test( url ),
replaceInData = hasCallback && !replaceInUrl && typeof data === "string" &&
!( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") &&
rjsonp.test( data );
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
overwritten = window[ callbackName ];
// Insert callback into url or form data
if ( replaceInUrl ) {
s.url = url.replace( rjsonp, "$1" + callbackName );
} else if ( replaceInData ) {
s.data = data.replace( rjsonp, "$1" + callbackName );
} else if ( hasCallback ) {
s.url += ( rquestion.test( url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = "async";
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( 0, 1 );
}
}
};
}
});
var xhrCallbacks,
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject ? function() {
// Abort all pending requests
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( 0, 1 );
}
} : false,
xhrId = 0;
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
(function( xhr ) {
jQuery.extend( jQuery.support, {
ajax: !!xhr,
cors: !!xhr && ( "withCredentials" in xhr )
});
})( jQuery.ajaxSettings.xhr() );
// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var handle, i,
xhr = s.xhr();
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( _ ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status,
statusText,
responseHeaders,
responses,
xml;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occurred
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {};
xml = xhr.responseXML;
// Construct response list
if ( xml && xml.documentElement /* #4958 */ ) {
responses.xml = xml;
}
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
try {
responses.text = xhr.responseText;
} catch( e ) {
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
if ( !s.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback, 0 );
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback(0,1);
}
}
};
}
});
}
var fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [function( prop, value ) {
var end, unit,
tween = this.createTween( prop, value ),
parts = rfxnum.exec( value ),
target = tween.cur(),
start = +target || 0,
scale = 1,
maxIterations = 20;
if ( parts ) {
end = +parts[2];
unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" && start ) {
// Iteratively approximate from a nonzero starting point
// Prefer the current property, because this process will be trivial if it uses the same units
// Fallback to end or a simple constant
start = jQuery.css( tween.elem, prop, true ) || end || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
tween.unit = unit;
tween.start = start;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end;
}
return tween;
}]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
}, 0 );
return ( fxNow = jQuery.now() );
}
function createTweens( animation, props ) {
jQuery.each( props, function( prop, value ) {
var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( collection[ index ].call( animation, prop, value ) ) {
// we're done with this property
return;
}
}
});
}
function Animation( elem, properties, options ) {
var result,
index = 0,
tweenerIndex = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end, easing ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
createTweens( animation, props );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
anim: animation,
queue: animation.opts.queue,
elem: elem
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
function defaultPrefilter( elem, props, opts ) {
var index, prop, value, length, dataShow, toggle, tween, hooks, oldfire,
anim = this,
style = elem.style,
orig = {},
handled = [],
hidden = elem.nodeType && isHidden( elem );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( elem, "display" ) === "inline" &&
jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !jQuery.support.shrinkWrapBlocks ) {
anim.done(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( index in props ) {
value = props[ index ];
if ( rfxtypes.exec( value ) ) {
delete props[ index ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
continue;
}
handled.push( index );
}
}
length = handled.length;
if ( length ) {
dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} );
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery.removeData( elem, "fxshow", true );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( index = 0 ; index < length ; index++ ) {
prop = handled[ index ];
tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 );
orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
}
}
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing any value as a 4th parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, false, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Remove in 2.0 - this supports IE8's panic based approach
// to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ||
// special check for .toggle( handler, handler, ... )
( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations resolve immediately
if ( empty ) {
anim.stop( true );
}
};
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
}
});
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth? 1 : 0;
for( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p*Math.PI ) / 2;
}
};
jQuery.timers = [];
jQuery.fx = Tween.prototype.init;
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
if ( timer() && jQuery.timers.push( timer ) && !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.interval = 13;
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Back Compat <1.8 extension point
jQuery.fx.step = {};
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
var rroot = /^(?:body|html)$/i;
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
if ( (body = doc.body) === elem ) {
return jQuery.offset.bodyOffset( elem );
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== "undefined" ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
clientTop = docElem.clientTop || body.clientTop || 0;
clientLeft = docElem.clientLeft || body.clientLeft || 0;
scrollTop = win.pageYOffset || docElem.scrollTop;
scrollLeft = win.pageXOffset || docElem.scrollLeft;
return {
top: box.top + scrollTop - clientTop,
left: box.left + scrollLeft - clientLeft
};
};
jQuery.offset = {
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[0] ) {
return;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || document.body;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return jQuery.access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, value, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
})( window );
/*! =========================================================
* bootstrap-modal.js v2.2.2
* http://twitter.github.com/bootstrap/javascript.html#modals
* =========================================================
* Twitter, Inc. require the following notice to accompany Bootstrap:
*
* Copyright (c) 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work
* except in compliance with the License. You may obtain a copy of the License in the LICENSE file, or at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing permissions and limitations under the License.
*
* ========================================================= */
!function ($) {
"use strict"; // jshint ;_;
/* MODAL CLASS DEFINITION
* ====================== */
var Modal = function (element, options) {
this.options = options
this.$element = $(element)
.delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this))
this.options.remote && this.$element.find('.modal-body').load(this.options.remote)
}
Modal.prototype = {
constructor: Modal
, toggle: function () {
return this[!this.isShown ? 'show' : 'hide']()
}
, show: function () {
var that = this
, e = $.Event('show')
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.escape()
this.backdrop(function () {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(document.body) //don't move modals dom position
}
that.$element
.show()
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element
.addClass('in')
.attr('aria-hidden', false)
that.enforceFocus()
transition ?
that.$element.one($.support.transition.end, function () { that.$element.focus().trigger('shown') }) :
that.$element.focus().trigger('shown')
})
}
, hide: function (e) {
e && e.preventDefault()
var that = this
e = $.Event('hide')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.escape()
$(document).off('focusin.modal')
this.$element
.removeClass('in')
.attr('aria-hidden', true)
$.support.transition && this.$element.hasClass('fade') ?
this.hideWithTransition() :
this.hideModal()
}
, enforceFocus: function () {
var that = this
$(document).on('focusin.modal', function (e) {
if (that.$element[0] !== e.target && !that.$element.has(e.target).length) {
that.$element.focus()
}
})
}
, escape: function () {
var that = this
if (this.isShown && this.options.keyboard) {
this.$element.on('keyup.dismiss.modal', function ( e ) {
e.which == 27 && that.hide()
})
} else if (!this.isShown) {
this.$element.off('keyup.dismiss.modal')
}
}
, hideWithTransition: function () {
var that = this
, timeout = setTimeout(function () {
that.$element.off($.support.transition.end)
that.hideModal()
}, 500)
this.$element.one($.support.transition.end, function () {
clearTimeout(timeout)
that.hideModal()
})
}
, hideModal: function (that) {
this.$element
.hide()
.trigger('hidden')
this.backdrop()
}
, removeBackdrop: function () {
this.$backdrop.remove()
this.$backdrop = null
}
, backdrop: function (callback) {
var that = this
, animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
.appendTo(document.body)
this.$backdrop.click(
this.options.backdrop == 'static' ?
$.proxy(this.$element[0].focus, this.$element[0])
: $.proxy(this.hide, this)
)
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
doAnimate ?
this.$backdrop.one($.support.transition.end, callback) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
$.support.transition && this.$element.hasClass('fade')?
this.$backdrop.one($.support.transition.end, $.proxy(this.removeBackdrop, this)) :
this.removeBackdrop()
} else if (callback) {
callback()
}
}
}
/* MODAL PLUGIN DEFINITION
* ======================= */
var old = $.fn.modal
$.fn.modal = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('modal')
, options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option]()
else if (options.show) data.show()
})
}
$.fn.modal.defaults = {
backdrop: true
, keyboard: true
, show: true
}
$.fn.modal.Constructor = Modal
/* MODAL NO CONFLICT
* ================= */
$.fn.modal.noConflict = function () {
$.fn.modal = old
return this
}
/* MODAL DATA-API
* ============== */
$(document).on('click.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
, href = $this.attr('href')
, $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7
, option = $target.data('modal') ? 'toggle' : $.extend({ remote:!/#/.test(href) && href }, $target.data(), $this.data())
e.preventDefault()
$target
.modal(option)
.one('hide', function () {
$this.focus()
})
})
}(window.jQuery);
/*!
* This file creates $ and jQuery variables within the F2 closure scope
*/
var $, jQuery = $ = window.jQuery.noConflict(true);
/*!
* Hij1nx requires the following notice to accompany EventEmitter:
*
* Copyright (c) 2011 hij1nx
*
* http://www.twitter.com/hij1nx
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the 'Software'), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
!function(exports, undefined) {
var isArray = Array.isArray ? Array.isArray : function _isArray(obj) {
return Object.prototype.toString.call(obj) === "[object Array]";
};
var defaultMaxListeners = 10;
function init() {
this._events = new Object;
}
function configure(conf) {
if (conf) {
conf.delimiter && (this.delimiter = conf.delimiter);
conf.wildcard && (this.wildcard = conf.wildcard);
if (this.wildcard) {
this.listenerTree = new Object;
}
}
}
function EventEmitter(conf) {
this._events = new Object;
configure.call(this, conf);
}
//
// Attention, function return type now is array, always !
// It has zero elements if no any matches found and one or more
// elements (leafs) if there are matches
//
function searchListenerTree(handlers, type, tree, i) {
if (!tree) {
return [];
}
var listeners=[], leaf, len, branch, xTree, xxTree, isolatedBranch, endReached,
typeLength = type.length, currentType = type[i], nextType = type[i+1];
if (i === typeLength && tree._listeners) {
//
// If at the end of the event(s) list and the tree has listeners
// invoke those listeners.
//
if (typeof tree._listeners === 'function') {
handlers && handlers.push(tree._listeners);
return [tree];
} else {
for (leaf = 0, len = tree._listeners.length; leaf < len; leaf++) {
handlers && handlers.push(tree._listeners[leaf]);
}
return [tree];
}
}
if ((currentType === '*' || currentType === '**') || tree[currentType]) {
//
// If the event emitted is '*' at this part
// or there is a concrete match at this patch
//
if (currentType === '*') {
for (branch in tree) {
if (branch !== '_listeners' && tree.hasOwnProperty(branch)) {
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+1));
}
}
return listeners;
} else if(currentType === '**') {
endReached = (i+1 === typeLength || (i+2 === typeLength && nextType === '*'));
if(endReached && tree._listeners) {
// The next element has a _listeners, add it to the handlers.
listeners = listeners.concat(searchListenerTree(handlers, type, tree, typeLength));
}
for (branch in tree) {
if (branch !== '_listeners' && tree.hasOwnProperty(branch)) {
if(branch === '*' || branch === '**') {
if(tree[branch]._listeners && !endReached) {
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], typeLength));
}
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i));
} else if(branch === nextType) {
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+2));
} else {
// No match on this one, shift into the tree but not in the type array.
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i));
}
}
}
return listeners;
}
listeners = listeners.concat(searchListenerTree(handlers, type, tree[currentType], i+1));
}
xTree = tree['*'];
if (xTree) {
//
// If the listener tree will allow any match for this part,
// then recursively explore all branches of the tree
//
searchListenerTree(handlers, type, xTree, i+1);
}
xxTree = tree['**'];
if(xxTree) {
if(i < typeLength) {
if(xxTree._listeners) {
// If we have a listener on a '**', it will catch all, so add its handler.
searchListenerTree(handlers, type, xxTree, typeLength);
}
// Build arrays of matching next branches and others.
for(branch in xxTree) {
if(branch !== '_listeners' && xxTree.hasOwnProperty(branch)) {
if(branch === nextType) {
// We know the next element will match, so jump twice.
searchListenerTree(handlers, type, xxTree[branch], i+2);
} else if(branch === currentType) {
// Current node matches, move into the tree.
searchListenerTree(handlers, type, xxTree[branch], i+1);
} else {
isolatedBranch = {};
isolatedBranch[branch] = xxTree[branch];
searchListenerTree(handlers, type, { '**': isolatedBranch }, i+1);
}
}
}
} else if(xxTree._listeners) {
// We have reached the end and still on a '**'
searchListenerTree(handlers, type, xxTree, typeLength);
} else if(xxTree['*'] && xxTree['*']._listeners) {
searchListenerTree(handlers, type, xxTree['*'], typeLength);
}
}
return listeners;
}
function growListenerTree(type, listener) {
type = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
//
// Looks for two consecutive '**', if so, don't add the event at all.
//
for(var i = 0, len = type.length; i+1 < len; i++) {
if(type[i] === '**' && type[i+1] === '**') {
return;
}
}
var tree = this.listenerTree;
var name = type.shift();
while (name) {
if (!tree[name]) {
tree[name] = new Object;
}
tree = tree[name];
if (type.length === 0) {
if (!tree._listeners) {
tree._listeners = listener;
}
else if(typeof tree._listeners === 'function') {
tree._listeners = [tree._listeners, listener];
}
else if (isArray(tree._listeners)) {
tree._listeners.push(listener);
if (!tree._listeners.warned) {
var m = defaultMaxListeners;
if (typeof this._events.maxListeners !== 'undefined') {
m = this._events.maxListeners;
}
if (m > 0 && tree._listeners.length > m) {
tree._listeners.warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
tree._listeners.length);
console.trace();
}
}
}
return true;
}
name = type.shift();
}
return true;
};
// By default EventEmitters will print a warning if more than
// 10 listeners are added to it. This is a useful default which
// helps finding memory leaks.
//
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.delimiter = '.';
EventEmitter.prototype.setMaxListeners = function(n) {
this._events || init.call(this);
this._events.maxListeners = n;
};
EventEmitter.prototype.event = '';
EventEmitter.prototype.once = function(event, fn) {
this.many(event, 1, fn);
return this;
};
EventEmitter.prototype.many = function(event, ttl, fn) {
var self = this;
if (typeof fn !== 'function') {
throw new Error('many only accepts instances of Function');
}
function listener() {
if (--ttl === 0) {
self.off(event, listener);
}
fn.apply(this, arguments);
};
listener._origin = fn;
this.on(event, listener);
return self;
};
EventEmitter.prototype.emit = function() {
this._events || init.call(this);
var type = arguments[0];
if (type === 'newListener') {
if (!this._events.newListener) { return false; }
}
// Loop through the *_all* functions and invoke them.
if (this._all) {
var l = arguments.length;
var args = new Array(l - 1);
for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
for (i = 0, l = this._all.length; i < l; i++) {
this.event = type;
this._all[i].apply(this, args);
}
}
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._all &&
!this._events.error &&
!(this.wildcard && this.listenerTree.error)) {
if (arguments[1] instanceof Error) {
throw arguments[1]; // Unhandled 'error' event
} else {
throw new Error("Uncaught, unspecified 'error' event.");
}
return false;
}
}
var handler;
if(this.wildcard) {
handler = [];
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
searchListenerTree.call(this, handler, ns, this.listenerTree, 0);
}
else {
handler = this._events[type];
}
if (typeof handler === 'function') {
this.event = type;
if (arguments.length === 1) {
handler.call(this);
}
else if (arguments.length > 1)
switch (arguments.length) {
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
var l = arguments.length;
var args = new Array(l - 1);
for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
handler.apply(this, args);
}
return true;
}
else if (handler) {
var l = arguments.length;
var args = new Array(l - 1);
for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
var listeners = handler.slice();
for (var i = 0, l = listeners.length; i < l; i++) {
this.event = type;
listeners[i].apply(this, args);
}
return (listeners.length > 0) || this._all;
}
else {
return this._all;
}
};
EventEmitter.prototype.on = function(type, listener) {
if (typeof type === 'function') {
this.onAny(type);
return this;
}
if (typeof listener !== 'function') {
throw new Error('on only accepts instances of Function');
}
this._events || init.call(this);
// To avoid recursion in the case that type == "newListeners"! Before
// adding it to the listeners, first emit "newListeners".
this.emit('newListener', type, listener);
if(this.wildcard) {
growListenerTree.call(this, type, listener);
return this;
}
if (!this._events[type]) {
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
}
else if(typeof this._events[type] === 'function') {
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
}
else if (isArray(this._events[type])) {
// If we've already got an array, just append.
this._events[type].push(listener);
// Check for listener leak
if (!this._events[type].warned) {
var m = defaultMaxListeners;
if (typeof this._events.maxListeners !== 'undefined') {
m = this._events.maxListeners;
}
if (m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.onAny = function(fn) {
if(!this._all) {
this._all = [];
}
if (typeof fn !== 'function') {
throw new Error('onAny only accepts instances of Function');
}
// Add the function to the event listener collection.
this._all.push(fn);
return this;
};
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
EventEmitter.prototype.off = function(type, listener) {
if (typeof listener !== 'function') {
throw new Error('removeListener only takes instances of Function');
}
var handlers,leafs=[];
if(this.wildcard) {
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0);
}
else {
// does not use listeners(), so no side effect of creating _events[type]
if (!this._events[type]) return this;
handlers = this._events[type];
leafs.push({_listeners:handlers});
}
for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) {
var leaf = leafs[iLeaf];
handlers = leaf._listeners;
if (isArray(handlers)) {
var position = -1;
for (var i = 0, length = handlers.length; i < length; i++) {
if (handlers[i] === listener ||
(handlers[i].listener && handlers[i].listener === listener) ||
(handlers[i]._origin && handlers[i]._origin === listener)) {
position = i;
break;
}
}
if (position < 0) {
return this;
}
if(this.wildcard) {
leaf._listeners.splice(position, 1)
}
else {
this._events[type].splice(position, 1);
}
if (handlers.length === 0) {
if(this.wildcard) {
delete leaf._listeners;
}
else {
delete this._events[type];
}
}
}
else if (handlers === listener ||
(handlers.listener && handlers.listener === listener) ||
(handlers._origin && handlers._origin === listener)) {
if(this.wildcard) {
delete leaf._listeners;
}
else {
delete this._events[type];
}
}
}
return this;
};
EventEmitter.prototype.offAny = function(fn) {
var i = 0, l = 0, fns;
if (fn && this._all && this._all.length > 0) {
fns = this._all;
for(i = 0, l = fns.length; i < l; i++) {
if(fn === fns[i]) {
fns.splice(i, 1);
return this;
}
}
} else {
this._all = [];
}
return this;
};
EventEmitter.prototype.removeListener = EventEmitter.prototype.off;
EventEmitter.prototype.removeAllListeners = function(type) {
if (arguments.length === 0) {
!this._events || init.call(this);
return this;
}
if(this.wildcard) {
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
var leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0);
for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) {
var leaf = leafs[iLeaf];
leaf._listeners = null;
}
}
else {
if (!this._events[type]) return this;
this._events[type] = null;
}
return this;
};
EventEmitter.prototype.listeners = function(type) {
if(this.wildcard) {
var handlers = [];
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
searchListenerTree.call(this, handlers, ns, this.listenerTree, 0);
return handlers;
}
this._events || init.call(this);
if (!this._events[type]) this._events[type] = [];
if (!isArray(this._events[type])) {
this._events[type] = [this._events[type]];
}
return this._events[type];
};
EventEmitter.prototype.listenersAny = function() {
if(this._all) {
return this._all;
}
else {
return [];
}
};
// if (typeof define === 'function' && define.amd) {
// define('EventEmitter2', [], function() {
// return EventEmitter;
// });
// } else {
exports.EventEmitter2 = EventEmitter;
// }
}(typeof process !== 'undefined' && typeof process.title !== 'undefined' && typeof exports !== 'undefined' ? exports : window);
/*!
* Øyvind Sean Kinsey and others require the following notice to accompany easyXDM:
*
* http://easyxdm.net/
* Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
(function (window, document, location, setTimeout, decodeURIComponent, encodeURIComponent) {
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global JSON, XMLHttpRequest, window, escape, unescape, ActiveXObject */
var global = this;
var channelId = Math.floor(Math.random() * 10000); // randomize the initial id in case of multiple closures loaded
var emptyFn = Function.prototype;
var reURI = /^((http.?:)\/\/([^:\/\s]+)(:\d+)*)/; // returns groups for protocol (2), domain (3) and port (4)
var reParent = /[\-\w]+\/\.\.\//; // matches a foo/../ expression
var reDoubleSlash = /([^:])\/\//g; // matches // anywhere but in the protocol
var namespace = ""; // stores namespace under which easyXDM object is stored on the page (empty if object is global)
var easyXDM = {};
var _easyXDM = window.easyXDM; // map over global easyXDM in case of overwrite
var IFRAME_PREFIX = "easyXDM_";
var HAS_NAME_PROPERTY_BUG;
var useHash = false; // whether to use the hash over the query
var flashVersion; // will be set if using flash
var HAS_FLASH_THROTTLED_BUG;
// http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting
function isHostMethod(object, property){
var t = typeof object[property];
return t == 'function' ||
(!!(t == 'object' && object[property])) ||
t == 'unknown';
}
function isHostObject(object, property){
return !!(typeof(object[property]) == 'object' && object[property]);
}
// end
// http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
function isArray(o){
return Object.prototype.toString.call(o) === '[object Array]';
}
// end
function hasFlash(){
try {
var activeX = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
flashVersion = Array.prototype.slice.call(activeX.GetVariable("$version").match(/(\d+),(\d+),(\d+),(\d+)/), 1);
HAS_FLASH_THROTTLED_BUG = parseInt(flashVersion[0], 10) > 9 && parseInt(flashVersion[1], 10) > 0;
activeX = null;
return true;
}
catch (notSupportedException) {
return false;
}
}
/*
* Cross Browser implementation for adding and removing event listeners.
*/
var on, un;
if (isHostMethod(window, "addEventListener")) {
on = function(target, type, listener){
target.addEventListener(type, listener, false);
};
un = function(target, type, listener){
target.removeEventListener(type, listener, false);
};
}
else if (isHostMethod(window, "attachEvent")) {
on = function(object, sEvent, fpNotify){
object.attachEvent("on" + sEvent, fpNotify);
};
un = function(object, sEvent, fpNotify){
object.detachEvent("on" + sEvent, fpNotify);
};
}
else {
throw new Error("Browser not supported");
}
/*
* Cross Browser implementation of DOMContentLoaded.
*/
var domIsReady = false, domReadyQueue = [], readyState;
if ("readyState" in document) {
// If browser is WebKit-powered, check for both 'loaded' (legacy browsers) and
// 'interactive' (HTML5 specs, recent WebKit builds) states.
// https://bugs.webkit.org/show_bug.cgi?id=45119
readyState = document.readyState;
domIsReady = readyState == "complete" || (~ navigator.userAgent.indexOf('AppleWebKit/') && (readyState == "loaded" || readyState == "interactive"));
}
else {
// If readyState is not supported in the browser, then in order to be able to fire whenReady functions apropriately
// when added dynamically _after_ DOM load, we have to deduce wether the DOM is ready or not.
// We only need a body to add elements to, so the existence of document.body is enough for us.
domIsReady = !!document.body;
}
function dom_onReady(){
if (domIsReady) {
return;
}
domIsReady = true;
for (var i = 0; i < domReadyQueue.length; i++) {
domReadyQueue[i]();
}
domReadyQueue.length = 0;
}
if (!domIsReady) {
if (isHostMethod(window, "addEventListener")) {
on(document, "DOMContentLoaded", dom_onReady);
}
else {
on(document, "readystatechange", function(){
if (document.readyState == "complete") {
dom_onReady();
}
});
if (document.documentElement.doScroll && window === top) {
var doScrollCheck = function(){
if (domIsReady) {
return;
}
// http://javascript.nwbox.com/IEContentLoaded/
try {
document.documentElement.doScroll("left");
}
catch (e) {
setTimeout(doScrollCheck, 1);
return;
}
dom_onReady();
};
doScrollCheck();
}
}
// A fallback to window.onload, that will always work
on(window, "load", dom_onReady);
}
/**
* This will add a function to the queue of functions to be run once the DOM reaches a ready state.
* If functions are added after this event then they will be executed immediately.
* @param {function} fn The function to add
* @param {Object} scope An optional scope for the function to be called with.
*/
function whenReady(fn, scope){
if (domIsReady) {
fn.call(scope);
return;
}
domReadyQueue.push(function(){
fn.call(scope);
});
}
/**
* Returns an instance of easyXDM from the parent window with
* respect to the namespace.
*
* @return An instance of easyXDM (in the parent window)
*/
function getParentObject(){
var obj = parent;
if (namespace !== "") {
for (var i = 0, ii = namespace.split("."); i < ii.length; i++) {
obj = obj[ii[i]];
}
}
return obj.easyXDM;
}
/**
* Removes easyXDM variable from the global scope. It also returns control
* of the easyXDM variable to whatever code used it before.
*
* @param {String} ns A string representation of an object that will hold
* an instance of easyXDM.
* @return An instance of easyXDM
*/
function noConflict(ns){
window.easyXDM = _easyXDM;
namespace = ns;
if (namespace) {
IFRAME_PREFIX = "easyXDM_" + namespace.replace(".", "_") + "_";
}
return easyXDM;
}
/*
* Methods for working with URLs
*/
/**
* Get the domain name from a url.
* @param {String} url The url to extract the domain from.
* @return The domain part of the url.
* @type {String}
*/
function getDomainName(url){
return url.match(reURI)[3];
}
/**
* Get the port for a given URL, or "" if none
* @param {String} url The url to extract the port from.
* @return The port part of the url.
* @type {String}
*/
function getPort(url){
return url.match(reURI)[4] || "";
}
/**
* Returns a string containing the schema, domain and if present the port
* @param {String} url The url to extract the location from
* @return {String} The location part of the url
*/
function getLocation(url){
var m = url.toLowerCase().match(reURI);
var proto = m[2], domain = m[3], port = m[4] || "";
if ((proto == "http:" && port == ":80") || (proto == "https:" && port == ":443")) {
port = "";
}
return proto + "//" + domain + port;
}
/**
* Resolves a relative url into an absolute one.
* @param {String} url The path to resolve.
* @return {String} The resolved url.
*/
function resolveUrl(url){
// replace all // except the one in proto with /
url = url.replace(reDoubleSlash, "$1/");
// If the url is a valid url we do nothing
if (!url.match(/^(http||https):\/\//)) {
// If this is a relative path
var path = (url.substring(0, 1) === "/") ? "" : location.pathname;
if (path.substring(path.length - 1) !== "/") {
path = path.substring(0, path.lastIndexOf("/") + 1);
}
url = location.protocol + "//" + location.host + path + url;
}
// reduce all 'xyz/../' to just ''
while (reParent.test(url)) {
url = url.replace(reParent, "");
}
return url;
}
/**
* Appends the parameters to the given url.<br/>
* The base url can contain existing query parameters.
* @param {String} url The base url.
* @param {Object} parameters The parameters to add.
* @return {String} A new valid url with the parameters appended.
*/
function appendQueryParameters(url, parameters){
var hash = "", indexOf = url.indexOf("#");
if (indexOf !== -1) {
hash = url.substring(indexOf);
url = url.substring(0, indexOf);
}
var q = [];
for (var key in parameters) {
if (parameters.hasOwnProperty(key)) {
q.push(key + "=" + encodeURIComponent(parameters[key]));
}
}
return url + (useHash ? "#" : (url.indexOf("?") == -1 ? "?" : "&")) + q.join("&") + hash;
}
// build the query object either from location.query, if it contains the xdm_e argument, or from location.hash
var query = (function(input){
input = input.substring(1).split("&");
var data = {}, pair, i = input.length;
while (i--) {
pair = input[i].split("=");
data[pair[0]] = decodeURIComponent(pair[1]);
}
return data;
}(/xdm_e=/.test(location.search) ? location.search : location.hash));
/*
* Helper methods
*/
/**
* Helper for checking if a variable/property is undefined
* @param {Object} v The variable to test
* @return {Boolean} True if the passed variable is undefined
*/
function undef(v){
return typeof v === "undefined";
}
/**
* A safe implementation of HTML5 JSON. Feature testing is used to make sure the implementation works.
* @return {JSON} A valid JSON conforming object, or null if not found.
*/
var getJSON = function(){
var cached = {};
var obj = {
a: [1, 2, 3]
}, json = "{\"a\":[1,2,3]}";
if (typeof JSON != "undefined" && typeof JSON.stringify === "function" && JSON.stringify(obj).replace((/\s/g), "") === json) {
// this is a working JSON instance
return JSON;
}
if (Object.toJSON) {
if (Object.toJSON(obj).replace((/\s/g), "") === json) {
// this is a working stringify method
cached.stringify = Object.toJSON;
}
}
if (typeof String.prototype.evalJSON === "function") {
obj = json.evalJSON();
if (obj.a && obj.a.length === 3 && obj.a[2] === 3) {
// this is a working parse method
cached.parse = function(str){
return str.evalJSON();
};
}
}
if (cached.stringify && cached.parse) {
// Only memoize the result if we have valid instance
getJSON = function(){
return cached;
};
return cached;
}
return null;
};
/**
* Applies properties from the source object to the target object.<br/>
* @param {Object} target The target of the properties.
* @param {Object} source The source of the properties.
* @param {Boolean} noOverwrite Set to True to only set non-existing properties.
*/
function apply(destination, source, noOverwrite){
var member;
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
if (prop in destination) {
member = source[prop];
if (typeof member === "object") {
apply(destination[prop], member, noOverwrite);
}
else if (!noOverwrite) {
destination[prop] = source[prop];
}
}
else {
destination[prop] = source[prop];
}
}
}
return destination;
}
// This tests for the bug in IE where setting the [name] property using javascript causes the value to be redirected into [submitName].
function testForNamePropertyBug(){
var form = document.body.appendChild(document.createElement("form")), input = form.appendChild(document.createElement("input"));
input.name = IFRAME_PREFIX + "TEST" + channelId; // append channelId in order to avoid caching issues
HAS_NAME_PROPERTY_BUG = input !== form.elements[input.name];
document.body.removeChild(form);
}
/**
* Creates a frame and appends it to the DOM.
* @param config {object} This object can have the following properties
* <ul>
* <li> {object} prop The properties that should be set on the frame. This should include the 'src' property.</li>
* <li> {object} attr The attributes that should be set on the frame.</li>
* <li> {DOMElement} container Its parent element (Optional).</li>
* <li> {function} onLoad A method that should be called with the frames contentWindow as argument when the frame is fully loaded. (Optional)</li>
* </ul>
* @return The frames DOMElement
* @type DOMElement
*/
function createFrame(config){
if (undef(HAS_NAME_PROPERTY_BUG)) {
testForNamePropertyBug();
}
var frame;
// This is to work around the problems in IE6/7 with setting the name property.
// Internally this is set as 'submitName' instead when using 'iframe.name = ...'
// This is not required by easyXDM itself, but is to facilitate other use cases
if (HAS_NAME_PROPERTY_BUG) {
frame = document.createElement("<iframe name=\"" + config.props.name + "\"/>");
}
else {
frame = document.createElement("IFRAME");
frame.name = config.props.name;
}
frame.id = frame.name = config.props.name;
delete config.props.name;
if (config.onLoad) {
on(frame, "load", config.onLoad);
}
if (typeof config.container == "string") {
config.container = document.getElementById(config.container);
}
if (!config.container) {
// This needs to be hidden like this, simply setting display:none and the like will cause failures in some browsers.
apply(frame.style, {
position: "absolute",
top: "-2000px"
});
config.container = document.body;
}
// HACK for some reason, IE needs the source set
// after the frame has been appended into the DOM
// so remove the src, and set it afterwards
var src = config.props.src;
delete config.props.src;
// transfer properties to the frame
apply(frame, config.props);
frame.border = frame.frameBorder = 0;
frame.allowTransparency = true;
config.container.appendChild(frame);
// HACK see above
frame.src = src;
config.props.src = src;
return frame;
}
/**
* Check whether a domain is allowed using an Access Control List.
* The ACL can contain * and ? as wildcards, or can be regular expressions.
* If regular expressions they need to begin with ^ and end with $.
* @param {Array/String} acl The list of allowed domains
* @param {String} domain The domain to test.
* @return {Boolean} True if the domain is allowed, false if not.
*/
function checkAcl(acl, domain){
// normalize into an array
if (typeof acl == "string") {
acl = [acl];
}
var re, i = acl.length;
while (i--) {
re = acl[i];
re = new RegExp(re.substr(0, 1) == "^" ? re : ("^" + re.replace(/(\*)/g, ".$1").replace(/\?/g, ".") + "$"));
if (re.test(domain)) {
return true;
}
}
return false;
}
/*
* Functions related to stacks
*/
/**
* Prepares an array of stack-elements suitable for the current configuration
* @param {Object} config The Transports configuration. See easyXDM.Socket for more.
* @return {Array} An array of stack-elements with the TransportElement at index 0.
*/
function prepareTransportStack(config){
var protocol = config.protocol, stackEls;
config.isHost = config.isHost || undef(query.xdm_p);
useHash = config.hash || false;
if (!config.props) {
config.props = {};
}
if (!config.isHost) {
config.channel = query.xdm_c;
config.secret = query.xdm_s;
config.remote = query.xdm_e;
protocol = query.xdm_p;
if (config.acl && !checkAcl(config.acl, config.remote)) {
throw new Error("Access denied for " + config.remote);
}
}
else {
config.remote = resolveUrl(config.remote);
config.channel = config.channel || "default" + channelId++;
config.secret = Math.random().toString(16).substring(2);
if (undef(protocol)) {
if (getLocation(location.href) == getLocation(config.remote)) {
/*
* Both documents has the same origin, lets use direct access.
*/
protocol = "4";
}
else if (isHostMethod(window, "postMessage") || isHostMethod(document, "postMessage")) {
/*
* This is supported in IE8+, Firefox 3+, Opera 9+, Chrome 2+ and Safari 4+
*/
protocol = "1";
}
else if (config.swf && isHostMethod(window, "ActiveXObject") && hasFlash()) {
/*
* The Flash transport superseedes the NixTransport as the NixTransport has been blocked by MS
*/
protocol = "6";
}
else if (navigator.product === "Gecko" && "frameElement" in window && navigator.userAgent.indexOf('WebKit') == -1) {
/*
* This is supported in Gecko (Firefox 1+)
*/
protocol = "5";
}
else if (config.remoteHelper) {
/*
* This is supported in all browsers that retains the value of window.name when
* navigating from one domain to another, and where parent.frames[foo] can be used
* to get access to a frame from the same domain
*/
config.remoteHelper = resolveUrl(config.remoteHelper);
protocol = "2";
}
else {
/*
* This is supported in all browsers where [window].location is writable for all
* The resize event will be used if resize is supported and the iframe is not put
* into a container, else polling will be used.
*/
protocol = "0";
}
}
}
config.protocol = protocol; // for conditional branching
switch (protocol) {
case "0":// 0 = HashTransport
apply(config, {
interval: 100,
delay: 2000,
useResize: true,
useParent: false,
usePolling: false
}, true);
if (config.isHost) {
if (!config.local) {
// If no local is set then we need to find an image hosted on the current domain
var domain = location.protocol + "//" + location.host, images = document.body.getElementsByTagName("img"), image;
var i = images.length;
while (i--) {
image = images[i];
if (image.src.substring(0, domain.length) === domain) {
config.local = image.src;
break;
}
}
if (!config.local) {
// If no local was set, and we are unable to find a suitable file, then we resort to using the current window
config.local = window;
}
}
var parameters = {
xdm_c: config.channel,
xdm_p: 0
};
if (config.local === window) {
// We are using the current window to listen to
config.usePolling = true;
config.useParent = true;
config.local = location.protocol + "//" + location.host + location.pathname + location.search;
parameters.xdm_e = config.local;
parameters.xdm_pa = 1; // use parent
}
else {
parameters.xdm_e = resolveUrl(config.local);
}
if (config.container) {
config.useResize = false;
parameters.xdm_po = 1; // use polling
}
config.remote = appendQueryParameters(config.remote, parameters);
}
else {
apply(config, {
channel: query.xdm_c,
remote: query.xdm_e,
useParent: !undef(query.xdm_pa),
usePolling: !undef(query.xdm_po),
useResize: config.useParent ? false : config.useResize
});
}
stackEls = [new easyXDM.stack.HashTransport(config), new easyXDM.stack.ReliableBehavior({}), new easyXDM.stack.QueueBehavior({
encode: true,
maxLength: 4000 - config.remote.length
}), new easyXDM.stack.VerifyBehavior({
initiate: config.isHost
})];
break;
case "1":
stackEls = [new easyXDM.stack.PostMessageTransport(config)];
break;
case "2":
stackEls = [new easyXDM.stack.NameTransport(config), new easyXDM.stack.QueueBehavior(), new easyXDM.stack.VerifyBehavior({
initiate: config.isHost
})];
break;
case "3":
stackEls = [new easyXDM.stack.NixTransport(config)];
break;
case "4":
stackEls = [new easyXDM.stack.SameOriginTransport(config)];
break;
case "5":
stackEls = [new easyXDM.stack.FrameElementTransport(config)];
break;
case "6":
if (!flashVersion) {
hasFlash();
}
stackEls = [new easyXDM.stack.FlashTransport(config)];
break;
}
// this behavior is responsible for buffering outgoing messages, and for performing lazy initialization
stackEls.push(new easyXDM.stack.QueueBehavior({
lazy: config.lazy,
remove: true
}));
return stackEls;
}
/**
* Chains all the separate stack elements into a single usable stack.<br/>
* If an element is missing a necessary method then it will have a pass-through method applied.
* @param {Array} stackElements An array of stack elements to be linked.
* @return {easyXDM.stack.StackElement} The last element in the chain.
*/
function chainStack(stackElements){
var stackEl, defaults = {
incoming: function(message, origin){
this.up.incoming(message, origin);
},
outgoing: function(message, recipient){
this.down.outgoing(message, recipient);
},
callback: function(success){
this.up.callback(success);
},
init: function(){
this.down.init();
},
destroy: function(){
this.down.destroy();
}
};
for (var i = 0, len = stackElements.length; i < len; i++) {
stackEl = stackElements[i];
apply(stackEl, defaults, true);
if (i !== 0) {
stackEl.down = stackElements[i - 1];
}
if (i !== len - 1) {
stackEl.up = stackElements[i + 1];
}
}
return stackEl;
}
/**
* This will remove a stackelement from its stack while leaving the stack functional.
* @param {Object} element The elment to remove from the stack.
*/
function removeFromStack(element){
element.up.down = element.down;
element.down.up = element.up;
element.up = element.down = null;
}
/*
* Export the main object and any other methods applicable
*/
/**
* @class easyXDM
* A javascript library providing cross-browser, cross-domain messaging/RPC.
* @version 2.4.15.118
* @singleton
*/
apply(easyXDM, {
/**
* The version of the library
* @type {string}
*/
version: "2.4.15.118",
/**
* This is a map containing all the query parameters passed to the document.
* All the values has been decoded using decodeURIComponent.
* @type {object}
*/
query: query,
/**
* @private
*/
stack: {},
/**
* Applies properties from the source object to the target object.<br/>
* @param {object} target The target of the properties.
* @param {object} source The source of the properties.
* @param {boolean} noOverwrite Set to True to only set non-existing properties.
*/
apply: apply,
/**
* A safe implementation of HTML5 JSON. Feature testing is used to make sure the implementation works.
* @return {JSON} A valid JSON conforming object, or null if not found.
*/
getJSONObject: getJSON,
/**
* This will add a function to the queue of functions to be run once the DOM reaches a ready state.
* If functions are added after this event then they will be executed immediately.
* @param {function} fn The function to add
* @param {object} scope An optional scope for the function to be called with.
*/
whenReady: whenReady,
/**
* Removes easyXDM variable from the global scope. It also returns control
* of the easyXDM variable to whatever code used it before.
*
* @param {String} ns A string representation of an object that will hold
* an instance of easyXDM.
* @return An instance of easyXDM
*/
noConflict: noConflict
});
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global console, _FirebugCommandLine, easyXDM, window, escape, unescape, isHostObject, undef, _trace, domIsReady, emptyFn, namespace */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, isHostObject, isHostMethod, un, on, createFrame, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.DomHelper
* Contains methods for dealing with the DOM
* @singleton
*/
easyXDM.DomHelper = {
/**
* Provides a consistent interface for adding eventhandlers
* @param {Object} target The target to add the event to
* @param {String} type The name of the event
* @param {Function} listener The listener
*/
on: on,
/**
* Provides a consistent interface for removing eventhandlers
* @param {Object} target The target to remove the event from
* @param {String} type The name of the event
* @param {Function} listener The listener
*/
un: un,
/**
* Checks for the presence of the JSON object.
* If it is not present it will use the supplied path to load the JSON2 library.
* This should be called in the documents head right after the easyXDM script tag.
* http://json.org/json2.js
* @param {String} path A valid path to json2.js
*/
requiresJSON: function(path){
if (!isHostObject(window, "JSON")) {
// we need to encode the < in order to avoid an illegal token error
// when the script is inlined in a document.
document.write('<' + 'script type="text/javascript" src="' + path + '"><' + '/script>');
}
}
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
(function(){
// The map containing the stored functions
var _map = {};
/**
* @class easyXDM.Fn
* This contains methods related to function handling, such as storing callbacks.
* @singleton
* @namespace easyXDM
*/
easyXDM.Fn = {
/**
* Stores a function using the given name for reference
* @param {String} name The name that the function should be referred by
* @param {Function} fn The function to store
* @namespace easyXDM.fn
*/
set: function(name, fn){
_map[name] = fn;
},
/**
* Retrieves the function referred to by the given name
* @param {String} name The name of the function to retrieve
* @param {Boolean} del If the function should be deleted after retrieval
* @return {Function} The stored function
* @namespace easyXDM.fn
*/
get: function(name, del){
var fn = _map[name];
if (del) {
delete _map[name];
}
return fn;
}
};
}());
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, chainStack, prepareTransportStack, getLocation, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.Socket
* This class creates a transport channel between two domains that is usable for sending and receiving string-based messages.<br/>
* The channel is reliable, supports queueing, and ensures that the message originates from the expected domain.<br/>
* Internally different stacks will be used depending on the browsers features and the available parameters.
* <h2>How to set up</h2>
* Setting up the provider:
* <pre><code>
* var socket = new easyXDM.Socket({
* local: "name.html",
* onReady: function(){
* // you need to wait for the onReady callback before using the socket
* socket.postMessage("foo-message");
* },
* onMessage: function(message, origin) {
* alert("received " + message + " from " + origin);
* }
* });
* </code></pre>
* Setting up the consumer:
* <pre><code>
* var socket = new easyXDM.Socket({
* remote: "http://remotedomain/page.html",
* remoteHelper: "http://remotedomain/name.html",
* onReady: function(){
* // you need to wait for the onReady callback before using the socket
* socket.postMessage("foo-message");
* },
* onMessage: function(message, origin) {
* alert("received " + message + " from " + origin);
* }
* });
* </code></pre>
* If you are unable to upload the <code>name.html</code> file to the consumers domain then remove the <code>remoteHelper</code> property
* and easyXDM will fall back to using the HashTransport instead of the NameTransport when not able to use any of the primary transports.
* @namespace easyXDM
* @constructor
* @cfg {String/Window} local The url to the local name.html document, a local static file, or a reference to the local window.
* @cfg {Boolean} lazy (Consumer only) Set this to true if you want easyXDM to defer creating the transport until really needed.
* @cfg {String} remote (Consumer only) The url to the providers document.
* @cfg {String} remoteHelper (Consumer only) The url to the remote name.html file. This is to support NameTransport as a fallback. Optional.
* @cfg {Number} delay The number of milliseconds easyXDM should try to get a reference to the local window. Optional, defaults to 2000.
* @cfg {Number} interval The interval used when polling for messages. Optional, defaults to 300.
* @cfg {String} channel (Consumer only) The name of the channel to use. Can be used to set consistent iframe names. Must be unique. Optional.
* @cfg {Function} onMessage The method that should handle incoming messages.<br/> This method should accept two arguments, the message as a string, and the origin as a string. Optional.
* @cfg {Function} onReady A method that should be called when the transport is ready. Optional.
* @cfg {DOMElement|String} container (Consumer only) The element, or the id of the element that the primary iframe should be inserted into. If not set then the iframe will be positioned off-screen. Optional.
* @cfg {Array/String} acl (Provider only) Here you can specify which '[protocol]://[domain]' patterns that should be allowed to act as the consumer towards this provider.<br/>
* This can contain the wildcards ? and *. Examples are 'http://example.com', '*.foo.com' and '*dom?.com'. If you want to use reqular expressions then you pattern needs to start with ^ and end with $.
* If none of the patterns match an Error will be thrown.
* @cfg {Object} props (Consumer only) Additional properties that should be applied to the iframe. This can also contain nested objects e.g: <code>{style:{width:"100px", height:"100px"}}</code>.
* Properties such as 'name' and 'src' will be overrided. Optional.
*/
easyXDM.Socket = function(config){
// create the stack
var stack = chainStack(prepareTransportStack(config).concat([{
incoming: function(message, origin){
config.onMessage(message, origin);
},
callback: function(success){
if (config.onReady) {
config.onReady(success);
}
}
}])), recipient = getLocation(config.remote);
// set the origin
this.origin = getLocation(config.remote);
/**
* Initiates the destruction of the stack.
*/
this.destroy = function(){
stack.destroy();
};
/**
* Posts a message to the remote end of the channel
* @param {String} message The message to send
*/
this.postMessage = function(message){
stack.outgoing(message, recipient);
};
stack.init();
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef,, chainStack, prepareTransportStack, debug, getLocation */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.Rpc
* Creates a proxy object that can be used to call methods implemented on the remote end of the channel, and also to provide the implementation
* of methods to be called from the remote end.<br/>
* The instantiated object will have methods matching those specified in <code>config.remote</code>.<br/>
* This requires the JSON object present in the document, either natively, using json.org's json2 or as a wrapper around library spesific methods.
* <h2>How to set up</h2>
* <pre><code>
* var rpc = new easyXDM.Rpc({
* // this configuration is equal to that used by the Socket.
* remote: "http://remotedomain/...",
* onReady: function(){
* // you need to wait for the onReady callback before using the proxy
* rpc.foo(...
* }
* },{
* local: {..},
* remote: {..}
* });
* </code></pre>
*
* <h2>Exposing functions (procedures)</h2>
* <pre><code>
* var rpc = new easyXDM.Rpc({
* ...
* },{
* local: {
* nameOfMethod: {
* method: function(arg1, arg2, success, error){
* ...
* }
* },
* // with shorthand notation
* nameOfAnotherMethod: function(arg1, arg2, success, error){
* }
* },
* remote: {...}
* });
* </code></pre>
* The function referenced by [method] will receive the passed arguments followed by the callback functions <code>success</code> and <code>error</code>.<br/>
* To send a successfull result back you can use
* <pre><code>
* return foo;
* </pre></code>
* or
* <pre><code>
* success(foo);
* </pre></code>
* To return an error you can use
* <pre><code>
* throw new Error("foo error");
* </code></pre>
* or
* <pre><code>
* error("foo error");
* </code></pre>
*
* <h2>Defining remotely exposed methods (procedures/notifications)</h2>
* The definition of the remote end is quite similar:
* <pre><code>
* var rpc = new easyXDM.Rpc({
* ...
* },{
* local: {...},
* remote: {
* nameOfMethod: {}
* }
* });
* </code></pre>
* To call a remote method use
* <pre><code>
* rpc.nameOfMethod("arg1", "arg2", function(value) {
* alert("success: " + value);
* }, function(message) {
* alert("error: " + message + );
* });
* </code></pre>
* Both the <code>success</code> and <code>errror</code> callbacks are optional.<br/>
* When called with no callback a JSON-RPC 2.0 notification will be executed.
* Be aware that you will not be notified of any errors with this method.
* <br/>
* <h2>Specifying a custom serializer</h2>
* If you do not want to use the JSON2 library for non-native JSON support, but instead capabilities provided by some other library
* then you can specify a custom serializer using <code>serializer: foo</code>
* <pre><code>
* var rpc = new easyXDM.Rpc({
* ...
* },{
* local: {...},
* remote: {...},
* serializer : {
* parse: function(string){ ... },
* stringify: function(object) {...}
* }
* });
* </code></pre>
* If <code>serializer</code> is set then the class will not attempt to use the native implementation.
* @namespace easyXDM
* @constructor
* @param {Object} config The underlying transports configuration. See easyXDM.Socket for available parameters.
* @param {Object} jsonRpcConfig The description of the interface to implement.
*/
easyXDM.Rpc = function(config, jsonRpcConfig){
// expand shorthand notation
if (jsonRpcConfig.local) {
for (var method in jsonRpcConfig.local) {
if (jsonRpcConfig.local.hasOwnProperty(method)) {
var member = jsonRpcConfig.local[method];
if (typeof member === "function") {
jsonRpcConfig.local[method] = {
method: member
};
}
}
}
}
// create the stack
var stack = chainStack(prepareTransportStack(config).concat([new easyXDM.stack.RpcBehavior(this, jsonRpcConfig), {
callback: function(success){
if (config.onReady) {
config.onReady(success);
}
}
}]));
// set the origin
this.origin = getLocation(config.remote);
/**
* Initiates the destruction of the stack.
*/
this.destroy = function(){
stack.destroy();
};
stack.init();
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, un, on, apply, whenReady, getParentObject, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.SameOriginTransport
* SameOriginTransport is a transport class that can be used when both domains have the same origin.<br/>
* This can be useful for testing and for when the main application supports both internal and external sources.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remote The remote document to communicate with.
*/
easyXDM.stack.SameOriginTransport = function(config){
var pub, frame, send, targetOrigin;
return (pub = {
outgoing: function(message, domain, fn){
send(message);
if (fn) {
fn();
}
},
destroy: function(){
if (frame) {
frame.parentNode.removeChild(frame);
frame = null;
}
},
onDOMReady: function(){
targetOrigin = getLocation(config.remote);
if (config.isHost) {
// set up the iframe
apply(config.props, {
src: appendQueryParameters(config.remote, {
xdm_e: location.protocol + "//" + location.host + location.pathname,
xdm_c: config.channel,
xdm_p: 4 // 4 = SameOriginTransport
}),
name: IFRAME_PREFIX + config.channel + "_provider"
});
frame = createFrame(config);
easyXDM.Fn.set(config.channel, function(sendFn){
send = sendFn;
setTimeout(function(){
pub.up.callback(true);
}, 0);
return function(msg){
pub.up.incoming(msg, targetOrigin);
};
});
}
else {
send = getParentObject().Fn.get(config.channel, true)(function(msg){
pub.up.incoming(msg, targetOrigin);
});
setTimeout(function(){
pub.up.callback(true);
}, 0);
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global global, easyXDM, window, getLocation, appendQueryParameters, createFrame, debug, apply, whenReady, IFRAME_PREFIX, namespace, resolveUrl, getDomainName, HAS_FLASH_THROTTLED_BUG, getPort, query*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.FlashTransport
* FlashTransport is a transport class that uses an SWF with LocalConnection to pass messages back and forth.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remote The remote domain to communicate with.
* @cfg {String} secret the pre-shared secret used to secure the communication.
* @cfg {String} swf The path to the swf file
* @cfg {Boolean} swfNoThrottle Set this to true if you want to take steps to avoid beeing throttled when hidden.
* @cfg {String || DOMElement} swfContainer Set this if you want to control where the swf is placed
*/
easyXDM.stack.FlashTransport = function(config){
var pub, // the public interface
frame, send, targetOrigin, swf, swfContainer;
function onMessage(message, origin){
setTimeout(function(){
pub.up.incoming(message, targetOrigin);
}, 0);
}
/**
* This method adds the SWF to the DOM and prepares the initialization of the channel
*/
function addSwf(domain){
// the differentiating query argument is needed in Flash9 to avoid a caching issue where LocalConnection would throw an error.
var url = config.swf + "?host=" + config.isHost;
var id = "easyXDM_swf_" + Math.floor(Math.random() * 10000);
// prepare the init function that will fire once the swf is ready
easyXDM.Fn.set("flash_loaded" + domain.replace(/[\-.]/g, "_"), function(){
easyXDM.stack.FlashTransport[domain].swf = swf = swfContainer.firstChild;
var queue = easyXDM.stack.FlashTransport[domain].queue;
for (var i = 0; i < queue.length; i++) {
queue[i]();
}
queue.length = 0;
});
if (config.swfContainer) {
swfContainer = (typeof config.swfContainer == "string") ? document.getElementById(config.swfContainer) : config.swfContainer;
}
else {
// create the container that will hold the swf
swfContainer = document.createElement('div');
// http://bugs.adobe.com/jira/browse/FP-4796
// http://tech.groups.yahoo.com/group/flexcoders/message/162365
// https://groups.google.com/forum/#!topic/easyxdm/mJZJhWagoLc
apply(swfContainer.style, HAS_FLASH_THROTTLED_BUG && config.swfNoThrottle ? {
height: "20px",
width: "20px",
position: "fixed",
right: 0,
top: 0
} : {
height: "1px",
width: "1px",
position: "absolute",
overflow: "hidden",
right: 0,
top: 0
});
document.body.appendChild(swfContainer);
}
// create the object/embed
var flashVars = "callback=flash_loaded" + domain.replace(/[\-.]/g, "_") + "&proto=" + global.location.protocol + "&domain=" + getDomainName(global.location.href) + "&port=" + getPort(global.location.href) + "&ns=" + namespace;
swfContainer.innerHTML = "<object height='20' width='20' type='application/x-shockwave-flash' id='" + id + "' data='" + url + "'>" +
"<param name='allowScriptAccess' value='always'></param>" +
"<param name='wmode' value='transparent'>" +
"<param name='movie' value='" +
url +
"'></param>" +
"<param name='flashvars' value='" +
flashVars +
"'></param>" +
"<embed type='application/x-shockwave-flash' FlashVars='" +
flashVars +
"' allowScriptAccess='always' wmode='transparent' src='" +
url +
"' height='1' width='1'></embed>" +
"</object>";
}
return (pub = {
outgoing: function(message, domain, fn){
swf.postMessage(config.channel, message.toString());
if (fn) {
fn();
}
},
destroy: function(){
try {
swf.destroyChannel(config.channel);
}
catch (e) {
}
swf = null;
if (frame) {
frame.parentNode.removeChild(frame);
frame = null;
}
},
onDOMReady: function(){
targetOrigin = config.remote;
// Prepare the code that will be run after the swf has been intialized
easyXDM.Fn.set("flash_" + config.channel + "_init", function(){
setTimeout(function(){
pub.up.callback(true);
});
});
// set up the omMessage handler
easyXDM.Fn.set("flash_" + config.channel + "_onMessage", onMessage);
config.swf = resolveUrl(config.swf); // reports have been made of requests gone rogue when using relative paths
var swfdomain = getDomainName(config.swf);
var fn = function(){
// set init to true in case the fn was called was invoked from a separate instance
easyXDM.stack.FlashTransport[swfdomain].init = true;
swf = easyXDM.stack.FlashTransport[swfdomain].swf;
// create the channel
swf.createChannel(config.channel, config.secret, getLocation(config.remote), config.isHost);
if (config.isHost) {
// if Flash is going to be throttled and we want to avoid this
if (HAS_FLASH_THROTTLED_BUG && config.swfNoThrottle) {
apply(config.props, {
position: "fixed",
right: 0,
top: 0,
height: "20px",
width: "20px"
});
}
// set up the iframe
apply(config.props, {
src: appendQueryParameters(config.remote, {
xdm_e: getLocation(location.href),
xdm_c: config.channel,
xdm_p: 6, // 6 = FlashTransport
xdm_s: config.secret
}),
name: IFRAME_PREFIX + config.channel + "_provider"
});
frame = createFrame(config);
}
};
if (easyXDM.stack.FlashTransport[swfdomain] && easyXDM.stack.FlashTransport[swfdomain].init) {
// if the swf is in place and we are the consumer
fn();
}
else {
// if the swf does not yet exist
if (!easyXDM.stack.FlashTransport[swfdomain]) {
// add the queue to hold the init fn's
easyXDM.stack.FlashTransport[swfdomain] = {
queue: [fn]
};
addSwf(swfdomain);
}
else {
easyXDM.stack.FlashTransport[swfdomain].queue.push(fn);
}
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, un, on, apply, whenReady, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.PostMessageTransport
* PostMessageTransport is a transport class that uses HTML5 postMessage for communication.<br/>
* <a href="http://msdn.microsoft.com/en-us/library/ms644944(VS.85).aspx">http://msdn.microsoft.com/en-us/library/ms644944(VS.85).aspx</a><br/>
* <a href="https://developer.mozilla.org/en/DOM/window.postMessage">https://developer.mozilla.org/en/DOM/window.postMessage</a>
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remote The remote domain to communicate with.
*/
easyXDM.stack.PostMessageTransport = function(config){
var pub, // the public interface
frame, // the remote frame, if any
callerWindow, // the window that we will call with
targetOrigin; // the domain to communicate with
/**
* Resolves the origin from the event object
* @private
* @param {Object} event The messageevent
* @return {String} The scheme, host and port of the origin
*/
function _getOrigin(event){
if (event.origin) {
// This is the HTML5 property
return getLocation(event.origin);
}
if (event.uri) {
// From earlier implementations
return getLocation(event.uri);
}
if (event.domain) {
// This is the last option and will fail if the
// origin is not using the same schema as we are
return location.protocol + "//" + event.domain;
}
throw "Unable to retrieve the origin of the event";
}
/**
* This is the main implementation for the onMessage event.<br/>
* It checks the validity of the origin and passes the message on if appropriate.
* @private
* @param {Object} event The messageevent
*/
function _window_onMessage(event){
var origin = _getOrigin(event);
if (origin == targetOrigin && event.data.substring(0, config.channel.length + 1) == config.channel + " ") {
pub.up.incoming(event.data.substring(config.channel.length + 1), origin);
}
}
return (pub = {
outgoing: function(message, domain, fn){
callerWindow.postMessage(config.channel + " " + message, domain || targetOrigin);
if (fn) {
fn();
}
},
destroy: function(){
un(window, "message", _window_onMessage);
if (frame) {
callerWindow = null;
frame.parentNode.removeChild(frame);
frame = null;
}
},
onDOMReady: function(){
targetOrigin = getLocation(config.remote);
if (config.isHost) {
// add the event handler for listening
var waitForReady = function(event){
if (event.data == config.channel + "-ready") {
// replace the eventlistener
callerWindow = ("postMessage" in frame.contentWindow) ? frame.contentWindow : frame.contentWindow.document;
un(window, "message", waitForReady);
on(window, "message", _window_onMessage);
setTimeout(function(){
pub.up.callback(true);
}, 0);
}
};
on(window, "message", waitForReady);
// set up the iframe
apply(config.props, {
src: appendQueryParameters(config.remote, {
xdm_e: getLocation(location.href),
xdm_c: config.channel,
xdm_p: 1 // 1 = PostMessage
}),
name: IFRAME_PREFIX + config.channel + "_provider"
});
frame = createFrame(config);
}
else {
// add the event handler for listening
on(window, "message", _window_onMessage);
callerWindow = ("postMessage" in window.parent) ? window.parent : window.parent.document;
callerWindow.postMessage(config.channel + "-ready", targetOrigin);
setTimeout(function(){
pub.up.callback(true);
}, 0);
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, apply, query, whenReady, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.FrameElementTransport
* FrameElementTransport is a transport class that can be used with Gecko-browser as these allow passing variables using the frameElement property.<br/>
* Security is maintained as Gecho uses Lexical Authorization to determine under which scope a function is running.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remote The remote document to communicate with.
*/
easyXDM.stack.FrameElementTransport = function(config){
var pub, frame, send, targetOrigin;
return (pub = {
outgoing: function(message, domain, fn){
send.call(this, message);
if (fn) {
fn();
}
},
destroy: function(){
if (frame) {
frame.parentNode.removeChild(frame);
frame = null;
}
},
onDOMReady: function(){
targetOrigin = getLocation(config.remote);
if (config.isHost) {
// set up the iframe
apply(config.props, {
src: appendQueryParameters(config.remote, {
xdm_e: getLocation(location.href),
xdm_c: config.channel,
xdm_p: 5 // 5 = FrameElementTransport
}),
name: IFRAME_PREFIX + config.channel + "_provider"
});
frame = createFrame(config);
frame.fn = function(sendFn){
delete frame.fn;
send = sendFn;
setTimeout(function(){
pub.up.callback(true);
}, 0);
// remove the function so that it cannot be used to overwrite the send function later on
return function(msg){
pub.up.incoming(msg, targetOrigin);
};
};
}
else {
// This is to mitigate origin-spoofing
if (document.referrer && getLocation(document.referrer) != query.xdm_e) {
window.top.location = query.xdm_e;
}
send = window.frameElement.fn(function(msg){
pub.up.incoming(msg, targetOrigin);
});
pub.up.callback(true);
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef, getLocation, appendQueryParameters, resolveUrl, createFrame, debug, un, apply, whenReady, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.NameTransport
* NameTransport uses the window.name property to relay data.
* The <code>local</code> parameter needs to be set on both the consumer and provider,<br/>
* and the <code>remoteHelper</code> parameter needs to be set on the consumer.
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remoteHelper The url to the remote instance of hash.html - this is only needed for the host.
* @namespace easyXDM.stack
*/
easyXDM.stack.NameTransport = function(config){
var pub; // the public interface
var isHost, callerWindow, remoteWindow, readyCount, callback, remoteOrigin, remoteUrl;
function _sendMessage(message){
var url = config.remoteHelper + (isHost ? "#_3" : "#_2") + config.channel;
callerWindow.contentWindow.sendMessage(message, url);
}
function _onReady(){
if (isHost) {
if (++readyCount === 2 || !isHost) {
pub.up.callback(true);
}
}
else {
_sendMessage("ready");
pub.up.callback(true);
}
}
function _onMessage(message){
pub.up.incoming(message, remoteOrigin);
}
function _onLoad(){
if (callback) {
setTimeout(function(){
callback(true);
}, 0);
}
}
return (pub = {
outgoing: function(message, domain, fn){
callback = fn;
_sendMessage(message);
},
destroy: function(){
callerWindow.parentNode.removeChild(callerWindow);
callerWindow = null;
if (isHost) {
remoteWindow.parentNode.removeChild(remoteWindow);
remoteWindow = null;
}
},
onDOMReady: function(){
isHost = config.isHost;
readyCount = 0;
remoteOrigin = getLocation(config.remote);
config.local = resolveUrl(config.local);
if (isHost) {
// Register the callback
easyXDM.Fn.set(config.channel, function(message){
if (isHost && message === "ready") {
// Replace the handler
easyXDM.Fn.set(config.channel, _onMessage);
_onReady();
}
});
// Set up the frame that points to the remote instance
remoteUrl = appendQueryParameters(config.remote, {
xdm_e: config.local,
xdm_c: config.channel,
xdm_p: 2
});
apply(config.props, {
src: remoteUrl + '#' + config.channel,
name: IFRAME_PREFIX + config.channel + "_provider"
});
remoteWindow = createFrame(config);
}
else {
config.remoteHelper = config.remote;
easyXDM.Fn.set(config.channel, _onMessage);
}
// Set up the iframe that will be used for the transport
callerWindow = createFrame({
props: {
src: config.local + "#_4" + config.channel
},
onLoad: function onLoad(){
// Remove the handler
var w = callerWindow || this;
un(w, "load", onLoad);
easyXDM.Fn.set(config.channel + "_load", _onLoad);
(function test(){
if (typeof w.contentWindow.sendMessage == "function") {
_onReady();
}
else {
setTimeout(test, 50);
}
}());
}
});
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, getLocation, createFrame, debug, un, on, apply, whenReady, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.HashTransport
* HashTransport is a transport class that uses the IFrame URL Technique for communication.<br/>
* <a href="http://msdn.microsoft.com/en-us/library/bb735305.aspx">http://msdn.microsoft.com/en-us/library/bb735305.aspx</a><br/>
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String/Window} local The url to the local file used for proxying messages, or the local window.
* @cfg {Number} delay The number of milliseconds easyXDM should try to get a reference to the local window.
* @cfg {Number} interval The interval used when polling for messages.
*/
easyXDM.stack.HashTransport = function(config){
var pub;
var me = this, isHost, _timer, pollInterval, _lastMsg, _msgNr, _listenerWindow, _callerWindow;
var useParent, _remoteOrigin;
function _sendMessage(message){
if (!_callerWindow) {
return;
}
var url = config.remote + "#" + (_msgNr++) + "_" + message;
((isHost || !useParent) ? _callerWindow.contentWindow : _callerWindow).location = url;
}
function _handleHash(hash){
_lastMsg = hash;
pub.up.incoming(_lastMsg.substring(_lastMsg.indexOf("_") + 1), _remoteOrigin);
}
/**
* Checks location.hash for a new message and relays this to the receiver.
* @private
*/
function _pollHash(){
if (!_listenerWindow) {
return;
}
var href = _listenerWindow.location.href, hash = "", indexOf = href.indexOf("#");
if (indexOf != -1) {
hash = href.substring(indexOf);
}
if (hash && hash != _lastMsg) {
_handleHash(hash);
}
}
function _attachListeners(){
_timer = setInterval(_pollHash, pollInterval);
}
return (pub = {
outgoing: function(message, domain){
_sendMessage(message);
},
destroy: function(){
window.clearInterval(_timer);
if (isHost || !useParent) {
_callerWindow.parentNode.removeChild(_callerWindow);
}
_callerWindow = null;
},
onDOMReady: function(){
isHost = config.isHost;
pollInterval = config.interval;
_lastMsg = "#" + config.channel;
_msgNr = 0;
useParent = config.useParent;
_remoteOrigin = getLocation(config.remote);
if (isHost) {
config.props = {
src: config.remote,
name: IFRAME_PREFIX + config.channel + "_provider"
};
if (useParent) {
config.onLoad = function(){
_listenerWindow = window;
_attachListeners();
pub.up.callback(true);
};
}
else {
var tries = 0, max = config.delay / 50;
(function getRef(){
if (++tries > max) {
throw new Error("Unable to reference listenerwindow");
}
try {
_listenerWindow = _callerWindow.contentWindow.frames[IFRAME_PREFIX + config.channel + "_consumer"];
}
catch (ex) {
}
if (_listenerWindow) {
_attachListeners();
pub.up.callback(true);
}
else {
setTimeout(getRef, 50);
}
}());
}
_callerWindow = createFrame(config);
}
else {
_listenerWindow = window;
_attachListeners();
if (useParent) {
_callerWindow = parent;
pub.up.callback(true);
}
else {
apply(config, {
props: {
src: config.remote + "#" + config.channel + new Date(),
name: IFRAME_PREFIX + config.channel + "_consumer"
},
onLoad: function(){
pub.up.callback(true);
}
});
_callerWindow = createFrame(config);
}
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.ReliableBehavior
* This is a behavior that tries to make the underlying transport reliable by using acknowledgements.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The behaviors configuration.
*/
easyXDM.stack.ReliableBehavior = function(config){
var pub, // the public interface
callback; // the callback to execute when we have a confirmed success/failure
var idOut = 0, idIn = 0, currentMessage = "";
return (pub = {
incoming: function(message, origin){
var indexOf = message.indexOf("_"), ack = message.substring(0, indexOf).split(",");
message = message.substring(indexOf + 1);
if (ack[0] == idOut) {
currentMessage = "";
if (callback) {
callback(true);
}
}
if (message.length > 0) {
pub.down.outgoing(ack[1] + "," + idOut + "_" + currentMessage, origin);
if (idIn != ack[1]) {
idIn = ack[1];
pub.up.incoming(message, origin);
}
}
},
outgoing: function(message, origin, fn){
currentMessage = message;
callback = fn;
pub.down.outgoing(idIn + "," + (++idOut) + "_" + message, origin);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, debug, undef, removeFromStack*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.QueueBehavior
* This is a behavior that enables queueing of messages. <br/>
* It will buffer incoming messages and dispach these as fast as the underlying transport allows.
* This will also fragment/defragment messages so that the outgoing message is never bigger than the
* set length.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The behaviors configuration. Optional.
* @cfg {Number} maxLength The maximum length of each outgoing message. Set this to enable fragmentation.
*/
easyXDM.stack.QueueBehavior = function(config){
var pub, queue = [], waiting = true, incoming = "", destroying, maxLength = 0, lazy = false, doFragment = false;
function dispatch(){
if (config.remove && queue.length === 0) {
removeFromStack(pub);
return;
}
if (waiting || queue.length === 0 || destroying) {
return;
}
waiting = true;
var message = queue.shift();
pub.down.outgoing(message.data, message.origin, function(success){
waiting = false;
if (message.callback) {
setTimeout(function(){
message.callback(success);
}, 0);
}
dispatch();
});
}
return (pub = {
init: function(){
if (undef(config)) {
config = {};
}
if (config.maxLength) {
maxLength = config.maxLength;
doFragment = true;
}
if (config.lazy) {
lazy = true;
}
else {
pub.down.init();
}
},
callback: function(success){
waiting = false;
var up = pub.up; // in case dispatch calls removeFromStack
dispatch();
up.callback(success);
},
incoming: function(message, origin){
if (doFragment) {
var indexOf = message.indexOf("_"), seq = parseInt(message.substring(0, indexOf), 10);
incoming += message.substring(indexOf + 1);
if (seq === 0) {
if (config.encode) {
incoming = decodeURIComponent(incoming);
}
pub.up.incoming(incoming, origin);
incoming = "";
}
}
else {
pub.up.incoming(message, origin);
}
},
outgoing: function(message, origin, fn){
if (config.encode) {
message = encodeURIComponent(message);
}
var fragments = [], fragment;
if (doFragment) {
// fragment into chunks
while (message.length !== 0) {
fragment = message.substring(0, maxLength);
message = message.substring(fragment.length);
fragments.push(fragment);
}
// enqueue the chunks
while ((fragment = fragments.shift())) {
queue.push({
data: fragments.length + "_" + fragment,
origin: origin,
callback: fragments.length === 0 ? fn : null
});
}
}
else {
queue.push({
data: message,
origin: origin,
callback: fn
});
}
if (lazy) {
pub.down.init();
}
else {
dispatch();
}
},
destroy: function(){
destroying = true;
pub.down.destroy();
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.VerifyBehavior
* This behavior will verify that communication with the remote end is possible, and will also sign all outgoing,
* and verify all incoming messages. This removes the risk of someone hijacking the iframe to send malicious messages.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The behaviors configuration.
* @cfg {Boolean} initiate If the verification should be initiated from this end.
*/
easyXDM.stack.VerifyBehavior = function(config){
var pub, mySecret, theirSecret, verified = false;
function startVerification(){
mySecret = Math.random().toString(16).substring(2);
pub.down.outgoing(mySecret);
}
return (pub = {
incoming: function(message, origin){
var indexOf = message.indexOf("_");
if (indexOf === -1) {
if (message === mySecret) {
pub.up.callback(true);
}
else if (!theirSecret) {
theirSecret = message;
if (!config.initiate) {
startVerification();
}
pub.down.outgoing(message);
}
}
else {
if (message.substring(0, indexOf) === theirSecret) {
pub.up.incoming(message.substring(indexOf + 1), origin);
}
}
},
outgoing: function(message, origin, fn){
pub.down.outgoing(mySecret + "_" + message, origin, fn);
},
callback: function(success){
if (config.initiate) {
startVerification();
}
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef, getJSON, debug, emptyFn, isArray */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.RpcBehavior
* This uses JSON-RPC 2.0 to expose local methods and to invoke remote methods and have responses returned over the the string based transport stack.<br/>
* Exposed methods can return values synchronous, asyncronous, or bet set up to not return anything.
* @namespace easyXDM.stack
* @constructor
* @param {Object} proxy The object to apply the methods to.
* @param {Object} config The definition of the local and remote interface to implement.
* @cfg {Object} local The local interface to expose.
* @cfg {Object} remote The remote methods to expose through the proxy.
* @cfg {Object} serializer The serializer to use for serializing and deserializing the JSON. Should be compatible with the HTML5 JSON object. Optional, will default to JSON.
*/
easyXDM.stack.RpcBehavior = function(proxy, config){
var pub, serializer = config.serializer || getJSON();
var _callbackCounter = 0, _callbacks = {};
/**
* Serializes and sends the message
* @private
* @param {Object} data The JSON-RPC message to be sent. The jsonrpc property will be added.
*/
function _send(data){
data.jsonrpc = "2.0";
pub.down.outgoing(serializer.stringify(data));
}
/**
* Creates a method that implements the given definition
* @private
* @param {Object} The method configuration
* @param {String} method The name of the method
* @return {Function} A stub capable of proxying the requested method call
*/
function _createMethod(definition, method){
var slice = Array.prototype.slice;
return function(){
var l = arguments.length, callback, message = {
method: method
};
if (l > 0 && typeof arguments[l - 1] === "function") {
//with callback, procedure
if (l > 1 && typeof arguments[l - 2] === "function") {
// two callbacks, success and error
callback = {
success: arguments[l - 2],
error: arguments[l - 1]
};
message.params = slice.call(arguments, 0, l - 2);
}
else {
// single callback, success
callback = {
success: arguments[l - 1]
};
message.params = slice.call(arguments, 0, l - 1);
}
_callbacks["" + (++_callbackCounter)] = callback;
message.id = _callbackCounter;
}
else {
// no callbacks, a notification
message.params = slice.call(arguments, 0);
}
if (definition.namedParams && message.params.length === 1) {
message.params = message.params[0];
}
// Send the method request
_send(message);
};
}
/**
* Executes the exposed method
* @private
* @param {String} method The name of the method
* @param {Number} id The callback id to use
* @param {Function} method The exposed implementation
* @param {Array} params The parameters supplied by the remote end
*/
function _executeMethod(method, id, fn, params){
if (!fn) {
if (id) {
_send({
id: id,
error: {
code: -32601,
message: "Procedure not found."
}
});
}
return;
}
var success, error;
if (id) {
success = function(result){
success = emptyFn;
_send({
id: id,
result: result
});
};
error = function(message, data){
error = emptyFn;
var msg = {
id: id,
error: {
code: -32099,
message: message
}
};
if (data) {
msg.error.data = data;
}
_send(msg);
};
}
else {
success = error = emptyFn;
}
// Call local method
if (!isArray(params)) {
params = [params];
}
try {
var result = fn.method.apply(fn.scope, params.concat([success, error]));
if (!undef(result)) {
success(result);
}
}
catch (ex1) {
error(ex1.message);
}
}
return (pub = {
incoming: function(message, origin){
var data = serializer.parse(message);
if (data.method) {
// A method call from the remote end
if (config.handle) {
config.handle(data, _send);
}
else {
_executeMethod(data.method, data.id, config.local[data.method], data.params);
}
}
else {
// A method response from the other end
var callback = _callbacks[data.id];
if (data.error) {
if (callback.error) {
callback.error(data.error);
}
}
else if (callback.success) {
callback.success(data.result);
}
delete _callbacks[data.id];
}
},
init: function(){
if (config.remote) {
// Implement the remote sides exposed methods
for (var method in config.remote) {
if (config.remote.hasOwnProperty(method)) {
proxy[method] = _createMethod(config.remote[method], method);
}
}
}
pub.down.init();
},
destroy: function(){
for (var method in config.remote) {
if (config.remote.hasOwnProperty(method) && proxy.hasOwnProperty(method)) {
delete proxy[method];
}
}
pub.down.destroy();
}
});
};
global.easyXDM = easyXDM;
})(window, document, location, window.setTimeout, decodeURIComponent, encodeURIComponent);
/*!
* F2 v1.3.0 09-16-2013
* Copyright (c) 2013 Markit On Demand, Inc. http://www.openf2.org
*
* "F2" is licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
* Please note that F2 ("Software") may contain third party material that Markit
* On Demand Inc. has a license to use and include within the Software (the
* "Third Party Material"). A list of the software comprising the Third Party Material
* and the terms and conditions under which such Third Party Material is distributed
* are reproduced in the ThirdPartyMaterial.md file available at:
*
* https://github.com/OpenF2/F2/blob/master/ThirdPartyMaterial.md
*
* The inclusion of the Third Party Material in the Software does not grant, provide
* nor result in you having acquiring any rights whatsoever, other than as stipulated
* in the terms and conditions related to the specific Third Party Material, if any.
*
*/
var F2;
/**
* Open F2
* @module f2
* @main f2
*/
F2 = (function() {
/**
* Abosolutizes a relative URL
* @method _absolutizeURI
* @private
* @param {e.g., location.href} base
* @param {URL to absolutize} href
* @returns {string} URL
* Source: https://gist.github.com/Yaffle/1088850
* Tests: http://skew.org/uri/uri_tests.html
*/
var _absolutizeURI = function(base, href) {// RFC 3986
function removeDotSegments(input) {
var output = [];
input.replace(/^(\.\.?(\/|$))+/, '')
.replace(/\/(\.(\/|$))+/g, '/')
.replace(/\/\.\.$/, '/../')
.replace(/\/?[^\/]*/g, function (p) {
if (p === '/..') {
output.pop();
} else {
output.push(p);
}
});
return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : '');
}
href = _parseURI(href || '');
base = _parseURI(base || '');
return !href || !base ? null : (href.protocol || base.protocol) +
(href.protocol || href.authority ? href.authority : base.authority) +
removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) +
(href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) +
href.hash;
};
/**
* Parses URI
* @method _parseURI
* @private
* @param {The URL to parse} url
* @returns {Parsed URL} string
* Source: https://gist.github.com/Yaffle/1088850
* Tests: http://skew.org/uri/uri_tests.html
*/
var _parseURI = function(url) {
var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);
// authority = '//' + user + ':' + pass '@' + hostname + ':' port
return (m ? {
href : m[0] || '',
protocol : m[1] || '',
authority: m[2] || '',
host : m[3] || '',
hostname : m[4] || '',
port : m[5] || '',
pathname : m[6] || '',
search : m[7] || '',
hash : m[8] || ''
} : null);
};
return {
/**
* A function to pass into F2.stringify which will prevent circular
* reference errors when serializing objects
* @method appConfigReplacer
*/
appConfigReplacer: function(key, value) {
if (key == 'root' || key == 'ui' || key == 'height') {
return undefined;
} else {
return value;
}
},
/**
* The apps namespace is a place for app developers to put the javascript
* class that is used to initialize their app. The javascript classes should
* be namepaced with the {{#crossLink "F2.AppConfig"}}{{/crossLink}}.appId.
* It is recommended that the code be placed in a closure to help keep the
* global namespace clean.
*
* If the class has an 'init' function, that function will be called
* automatically by F2.
* @property Apps
* @type object
* @example
* F2.Apps["com_example_helloworld"] = (function() {
* var App_Class = function(appConfig, appContent, root) {
* this._app = appConfig; // the F2.AppConfig object
* this._appContent = appContent // the F2.AppManifest.AppContent object
* this.$root = $(root); // the root DOM Element that contains this app
* }
*
* App_Class.prototype.init = function() {
* // perform init actions
* }
*
* return App_Class;
* })();
* @example
* F2.Apps["com_example_helloworld"] = function(appConfig, appContent, root) {
* return {
* init:function() {
* // perform init actions
* }
* };
* };
* @for F2
*/
Apps: {},
/**
* Creates a namespace on F2 and copies the contents of an object into
* that namespace optionally overwriting existing properties.
* @method extend
* @param {string} ns The namespace to create. Pass a falsy value to
* add properties to the F2 namespace directly.
* @param {object} obj The object to copy into the namespace.
* @param {bool} overwrite True if object properties should be overwritten
* @return {object} The created object
*/
extend: function (ns, obj, overwrite) {
var isFunc = typeof obj === 'function';
var parts = ns ? ns.split('.') : [];
var parent = this;
obj = obj || {};
// ignore leading global
if (parts[0] === 'F2') {
parts = parts.slice(1);
}
// create namespaces
for (var i = 0, len = parts.length; i < len; i++) {
if (!parent[parts[i]]) {
parent[parts[i]] = isFunc && i + 1 == len ? obj : {};
}
parent = parent[parts[i]];
}
// copy object into namespace
if (!isFunc) {
for (var prop in obj) {
if (typeof parent[prop] === 'undefined' || overwrite) {
parent[prop] = obj[prop];
}
}
}
return parent;
},
/**
* Generates a somewhat random id
* @method guid
* @return {string} A random id
* @for F2
*/
guid: function() {
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
return (S4()+S4()+'-'+S4()+'-'+S4()+'-'+S4()+'-'+S4()+S4()+S4());
},
/**
* Search for a value within an array.
* @method inArray
* @param {object} value The value to search for
* @param {Array} array The array to search
* @return {bool} True if the item is in the array
*/
inArray: function(value, array) {
return jQuery.inArray(value, array) > -1;
},
/**
* Tests a URL to see if it's on the same domain (local) or not
* @method isLocalRequest
* @param {URL to test} url
* @returns {bool} Whether the URL is local or not
* Derived from: https://github.com/jquery/jquery/blob/master/src/ajax.js
*/
isLocalRequest: function(url){
var rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
urlLower = url.toLowerCase(),
parts = rurl.exec( urlLower ),
ajaxLocation,
ajaxLocParts;
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement('a');
ajaxLocation.href = '';
ajaxLocation = ajaxLocation.href;
}
ajaxLocation = ajaxLocation.toLowerCase();
// uh oh, the url must be relative
// make it fully qualified and re-regex url
if (!parts){
urlLower = _absolutizeURI(ajaxLocation,urlLower).toLowerCase();
parts = rurl.exec( urlLower );
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation ) || [];
// do hostname and protocol and port of manifest URL match location.href? (a "local" request on the same domain)
var matched = !(parts &&
(parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
(parts[ 3 ] || (parts[ 1 ] === 'http:' ? '80' : '443')) !==
(ajaxLocParts[ 3 ] || (ajaxLocParts[ 1 ] === 'http:' ? '80' : '443'))));
return matched;
},
/**
* Utility method to determine whether or not the argument passed in is or is not a native dom node.
* @method isNativeDOMNode
* @param {object} testObject The object you want to check as native dom node.
* @return {bool} Returns true if the object passed is a native dom node.
*/
isNativeDOMNode: function(testObject) {
var bIsNode = (
typeof Node === 'object' ? testObject instanceof Node :
testObject && typeof testObject === 'object' && typeof testObject.nodeType === 'number' && typeof testObject.nodeName === 'string'
);
var bIsElement = (
typeof HTMLElement === 'object' ? testObject instanceof HTMLElement : //DOM2
testObject && typeof testObject === 'object' && testObject.nodeType === 1 && typeof testObject.nodeName === 'string'
);
return (bIsNode || bIsElement);
},
/**
* A utility logging function to write messages or objects to the browser console. This is a proxy for the [`console` API](https://developers.google.com/chrome-developer-tools/docs/console).
* @method log
* @param {object|string} Object/Method An object to be logged _or_ a `console` API method name, such as `warn` or `error`. All of the console method names are [detailed in the Chrome docs](https://developers.google.com/chrome-developer-tools/docs/console-api).
* @param {object} [obj2]* An object to be logged
* @example
//Pass any object (string, int, array, object, bool) to .log()
F2.log('foo');
F2.log(myArray);
//Use a console method name as the first argument.
F2.log('error', err);
F2.log('info', 'The session ID is ' + sessionId);
* Some code derived from [HTML5 Boilerplate console plugin](https://github.com/h5bp/html5-boilerplate/blob/master/js/plugins.js)
*/
log: function() {
var _log;
var _logMethod = 'log';
var method;
var noop = function () { };
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
var args;
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
//if first arg is a console function, use it.
//defaults to console.log()
if (arguments && arguments.length > 1 && arguments[0] == method){
_logMethod = method;
//remove console func from args
args = Array.prototype.slice.call(arguments, 1);
}
}
if (Function.prototype.bind) {
_log = Function.prototype.bind.call(console[_logMethod], console);
} else {
_log = function() {
Function.prototype.apply.call(console[_logMethod], console, (args || arguments));
};
}
_log.apply(this, (args || arguments));
},
/**
* Wrapper to convert a JSON string to an object
* @method parse
* @param {string} str The JSON string to convert
* @return {object} The parsed object
*/
parse: function(str) {
return JSON.parse(str);
},
/**
* Wrapper to convert an object to JSON
*
* **Note: When using F2.stringify on an F2.AppConfig object, it is
* recommended to pass F2.appConfigReplacer as the replacer function in
* order to prevent circular serialization errors.**
* @method stringify
* @param {object} value The object to convert
* @param {function|Array} replacer An optional parameter that determines
* how object values are stringified for objects. It can be a function or an
* array of strings.
* @param {int|string} space An optional parameter that specifies the
* indentation of nested structures. If it is omitted, the text will be
* packed without extra whitespace. If it is a number, it will specify the
* number of spaces to indent at each level. If it is a string (such as '\t'
* or ' '), it contains the characters used to indent at each level.
* @return {string} The JSON string
*/
stringify: function(value, replacer, space) {
return JSON.stringify(value, replacer, space);
},
/**
* Function to get the F2 version number
* @method version
* @return {string} F2 version number
*/
version: function() { return '{{sdk.version}}'; }
};
})();
/**
* The new `AppHandlers` functionality provides Container Developers a higher level of control over configuring app rendering and interaction.
*
*<p class="alert alert-block alert-warning">
*The addition of `F2.AppHandlers` replaces the previous {{#crossLink "F2.ContainerConfig"}}{{/crossLink}} properties `beforeAppRender`, `appRender`, and `afterAppRender`. These methods were deprecated—but not removed—in version 1.2. They will be permanently removed in a future version of F2.
*</p>
*
*<p class="alert alert-block alert-info">
*Starting with F2 version 1.2, `AppHandlers` is the preferred method for Container Developers to manage app layout.
*</p>
*
* ### Order of Execution
*
* **App Rendering**
*
* 0. {{#crossLink "F2/registerApps"}}F2.registerApps(){{/crossLink}} method is called by the Container Developer and the following methods are run for *each* {{#crossLink "F2.AppConfig"}}{{/crossLink}} passed.
* 1. **'appCreateRoot'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_CREATE\_ROOT*) handlers are fired in the order they were attached.
* 2. **'appRenderBefore'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER\_BEFORE*) handlers are fired in the order they were attached.
* 3. Each app's `manifestUrl` is requested asynchronously; on success the following methods are fired.
* 3. **'appRender'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER*) handlers are fired in the order they were attached.
* 4. **'appRenderAfter'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER\_AFTER*) handlers are fired in the order they were attached.
*
*
* **App Removal**
* 0. {{#crossLink "F2/removeApp"}}F2.removeApp(){{/crossLink}} with a specific {{#crossLink "F2.AppConfig/instanceId "}}{{/crossLink}} or {{#crossLink "F2/removeAllApps"}}F2.removeAllApps(){{/crossLink}} method is called by the Container Developer and the following methods are run.
* 1. **'appDestroyBefore'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY\_BEFORE*) handlers are fired in the order they were attached.
* 2. **'appDestroy'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY*) handlers are fired in the order they were attached.
* 3. **'appDestroyAfter'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY\_AFTER*) handlers are fired in the order they were attached.
* @class F2.AppHandlers
*/
F2.extend('AppHandlers', (function() {
// the hidden token that we will check against every time someone tries to add, remove, fire handler
var _ct = F2.guid();
var _f2t = F2.guid();
var _handlerCollection = {
appCreateRoot: [],
appRenderBefore: [],
appDestroyBefore: [],
appRenderAfter: [],
appDestroyAfter: [],
appRender: [],
appDestroy: []
};
var _defaultMethods = {
appRender: function(appConfig, appHtml)
{
var $root = null;
// if no app root is defined use the app's outer most node
if(!F2.isNativeDOMNode(appConfig.root))
{
appConfig.root = jQuery(appHtml).get(0);
// get a handle on the root in jQuery
$root = jQuery(appConfig.root);
}
else
{
// get a handle on the root in jQuery
$root = jQuery(appConfig.root);
// append the app html to the root
$root.append(appHtml);
}
// append the root to the body by default.
jQuery('body').append($root);
},
appDestroy: function(appInstance)
{
// call the apps destroy method, if it has one
if(appInstance && appInstance.app && appInstance.app.destroy && typeof(appInstance.app.destroy) == 'function')
{
appInstance.app.destroy();
}
// warn the Container and App Developer that even though they have a destroy method it hasn't been
else if(appInstance && appInstance.app && appInstance.app.destroy)
{
F2.log(appInstance.config.appId + ' has a destroy property, but destroy is not of type function and as such will not be executed.');
}
// fade out and remove the root
jQuery(appInstance.config.root).fadeOut(500, function() {
jQuery(this).remove();
});
}
};
var _createHandler = function(token, sNamespace, func_or_element, bDomNodeAppropriate)
{
// will throw an exception and stop execution if the token is invalid
_validateToken(token);
// create handler structure. Not all arguments properties will be populated/used.
var handler = {
func: (typeof(func_or_element)) ? func_or_element : null,
namespace: sNamespace,
domNode: (F2.isNativeDOMNode(func_or_element)) ? func_or_element : null
};
if(!handler.func && !handler.domNode)
{
throw ('Invalid or null argument passed. Handler will not be added to collection. A valid dom element or callback function is required.');
}
if(handler.domNode && !bDomNodeAppropriate)
{
throw ('Invalid argument passed. Handler will not be added to collection. A callback function is required for this event type.');
}
return handler;
};
var _validateToken = function(sToken)
{
// check token against F2 and container
if(_ct != sToken && _f2t != sToken) { throw ('Invalid token passed. Please verify that you have correctly received and stored token from F2.AppHandlers.getToken().'); }
};
var _removeHandler = function(sToken, eventKey, sNamespace)
{
// will throw an exception and stop execution if the token is invalid
_validateToken(sToken);
if(!sNamespace && !eventKey)
{
return;
}
// remove by event key
else if(!sNamespace && eventKey)
{
_handlerCollection[eventKey] = [];
}
// remove by namespace only
else if(sNamespace && !eventKey)
{
sNamespace = sNamespace.toLowerCase();
for(var currentEventKey in _handlerCollection)
{
var eventCollection = _handlerCollection[currentEventKey];
var newEvents = [];
for(var i = 0, ec = eventCollection.length; i < ec; i++)
{
var currentEventHandler = eventCollection[i];
if(currentEventHandler)
{
if(!currentEventHandler.namespace || currentEventHandler.namespace.toLowerCase() != sNamespace)
{
newEvents.push(currentEventHandler);
}
}
}
eventCollection = newEvents;
}
}
else if(sNamespace && _handlerCollection[eventKey])
{
sNamespace = sNamespace.toLowerCase();
var newHandlerCollection = [];
for(var iCounter = 0, hc = _handlerCollection[eventKey].length; iCounter < hc; iCounter++)
{
var currentHandler = _handlerCollection[eventKey][iCounter];
if(currentHandler)
{
if(!currentHandler.namespace || currentHandler.namespace.toLowerCase() != sNamespace)
{
newHandlerCollection.push(currentHandler);
}
}
}
_handlerCollection[eventKey] = newHandlerCollection;
}
};
return {
/**
* Allows Container Developer to retrieve a unique token which must be passed to
* all `on` and `off` methods. This function will self destruct and can only be called
* one time. Container Developers must store the return value inside of a closure.
* @method getToken
**/
getToken: function()
{
// delete this method for security that way only the container has access to the token 1 time.
// kind of Ethan Hunt-ish, this message will self destruct immediately.
delete this.getToken;
// return the token, which we validate against.
return _ct;
},
/**
* Allows F2 to get a token internally. Token is required to call {{#crossLink "F2.AppHandlers/\_\_trigger:method"}}{{/crossLink}}.
* This function will self destruct to eliminate other sources from using the {{#crossLink "F2.AppHandlers/\_\_trigger:method"}}{{/crossLink}}
* and additional internal methods.
* @method __f2GetToken
* @private
**/
__f2GetToken: function()
{
// delete this method for security that way only the F2 internally has access to the token 1 time.
// kind of Ethan Hunt-ish, this message will self destruct immediately.
delete this.__f2GetToken;
// return the token, which we validate against.
return _f2t;
},
/**
* Allows F2 to trigger specific events internally.
* @method __trigger
* @private
* @chainable
* @param {String} token The token received from {{#crossLink "F2.AppHandlers/\_\_f2GetToken:method"}}{{/crossLink}}.
* @param {String} eventKey The event to fire. The complete list of event keys is available in {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.
**/
__trigger: function(token, eventKey) // additional arguments will likely be passed
{
// will throw an exception and stop execution if the token is invalid
if(token != _f2t)
{
throw ('Token passed is invalid. Only F2 is allowed to call F2.AppHandlers.__trigger().');
}
if(_handlerCollection && _handlerCollection[eventKey])
{
// create a collection of arguments that are safe to pass to the callback.
var passableArgs = [];
// populate that collection with all arguments except token and eventKey
for(var i = 2, j = arguments.length; i < j; i++)
{
passableArgs.push(arguments[i]);
}
if(_handlerCollection[eventKey].length === 0 && _defaultMethods[eventKey])
{
_defaultMethods[eventKey].apply(F2, passableArgs);
return this;
}
else if(_handlerCollection[eventKey].length === 0 && !_handlerCollection[eventKey])
{
return this;
}
// fire all event listeners in the order that they were added.
for(var iCounter = 0, hcl = _handlerCollection[eventKey].length; iCounter < hcl; iCounter++)
{
var handler = _handlerCollection[eventKey][iCounter];
// appRender where root is already defined
if (handler.domNode && arguments[2] && arguments[2].root && arguments[3])
{
var $appRoot = jQuery(arguments[2].root).append(arguments[3]);
jQuery(handler.domNode).append($appRoot);
}
else if (handler.domNode && arguments[2] && !arguments[2].root && arguments[3])
{
// set the root to the actual HTML of the app
arguments[2].root = jQuery(arguments[3]).get(0);
// appends the root to the dom node specified
jQuery(handler.domNode).append(arguments[2].root);
}
else
{
handler.func.apply(F2, passableArgs);
}
}
}
else
{
throw ('Invalid EventKey passed. Check your inputs and try again.');
}
return this;
},
/**
* Allows Container Developer to easily tell all apps to render in a specific location. Only valid for eventType `appRender`.
* @method on
* @chainable
* @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}.
* @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. The namespace is useful for removal
* purposes. At this time it does not affect when an event is fired. Complete list of event keys available in
* {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.
* @params {HTMLElement} element Specific DOM element to which app gets appended.
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* 'appRender',
* document.getElementById('my_app')
* );
*
* Or:
* @example
* F2.AppHandlers.on(
* _token,
* 'appRender.myNamespace',
* document.getElementById('my_app')
* );
**/
/**
* Allows Container Developer to add listener method that will be triggered when a specific event occurs.
* @method on
* @chainable
* @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}.
* @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. The namespace is useful for removal
* purposes. At this time it does not affect when an event is fired. Complete list of event keys available in
* {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.
* @params {Function} listener A function that will be triggered when a specific event occurs. For detailed argument definition refer to {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* 'appRenderBefore'
* function() { F2.log('before app rendered!'); }
* );
*
* Or:
* @example
* F2.AppHandlers.on(
* _token,
* 'appRenderBefore.myNamespace',
* function() { F2.log('before app rendered!'); }
* );
**/
on: function(token, eventKey, func_or_element)
{
var sNamespace = null;
if(!eventKey)
{
throw ('eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.');
}
// we need to check the key for a namespace
if(eventKey.indexOf('.') > -1)
{
var arData = eventKey.split('.');
eventKey = arData[0];
sNamespace = arData[1];
}
if(_handlerCollection && _handlerCollection[eventKey])
{
_handlerCollection[eventKey].push(
_createHandler(
token,
sNamespace,
func_or_element,
(eventKey == 'appRender')
)
);
}
else
{
throw ('Invalid EventKey passed. Check your inputs and try again.');
}
return this;
},
/**
* Allows Container Developer to remove listener methods for specific events
* @method off
* @chainable
* @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}.
* @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. If no namespace is provided all
* listeners for the specified event type will be removed.
* Complete list available in {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.off(_token,'appRenderBefore');
*
**/
off: function(token, eventKey)
{
var sNamespace = null;
if(!eventKey)
{
throw ('eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.');
}
// we need to check the key for a namespace
if(eventKey.indexOf('.') > -1)
{
var arData = eventKey.split('.');
eventKey = arData[0];
sNamespace = arData[1];
}
if(_handlerCollection && _handlerCollection[eventKey])
{
_removeHandler(
token,
eventKey,
sNamespace
);
}
else
{
throw ('Invalid EventKey passed. Check your inputs and try again.');
}
return this;
}
};
})());
F2.extend('Constants', {
/**
* A convenient collection of all available appHandler events.
* @class F2.Constants.AppHandlers
**/
AppHandlers: (function()
{
return {
/**
* Equivalent to `appCreateRoot`. Identifies the create root method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} )
* @property APP_CREATE_ROOT
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_CREATE_ROOT,
* function(appConfig)
* {
* // If you want to create a custom root. By default F2 uses the app's outermost HTML element.
* // the app's html is not available until after the manifest is retrieved so this logic occurs in F2.Constants.AppHandlers.APP_RENDER
* appConfig.root = jQuery('<section></section>').get(0);
* }
* );
*/
APP_CREATE_ROOT: 'appCreateRoot',
/**
* Equivalent to `appRenderBefore`. Identifies the before app render method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} )
* @property APP_RENDER_BEFORE
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_RENDER_BEFORE,
* function(appConfig)
* {
* F2.log(appConfig);
* }
* );
*/
APP_RENDER_BEFORE: 'appRenderBefore',
/**
* Equivalent to `appRender`. Identifies the app render method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}}, [appHtml](../../app-development.html#app-design) )
* @property APP_RENDER
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_RENDER,
* function(appConfig, appHtml)
* {
* var $root = null;
*
* // if no app root is defined use the app's outer most node
* if(!F2.isNativeDOMNode(appConfig.root))
* {
* appConfig.root = jQuery(appHtml).get(0);
* // get a handle on the root in jQuery
* $root = jQuery(appConfig.root);
* }
* else
* {
* // get a handle on the root in jQuery
* $root = jQuery(appConfig.root);
*
* // append the app html to the root
* $root.append(appHtml);
* }
*
* // append the root to the body by default.
* jQuery('body').append($root);
* }
* );
*/
APP_RENDER: 'appRender',
/**
* Equivalent to `appRenderAfter`. Identifies the after app render method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} )
* @property APP_RENDER_AFTER
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_RENDER_AFTER,
* function(appConfig)
* {
* F2.log(appConfig);
* }
* );
*/
APP_RENDER_AFTER: 'appRenderAfter',
/**
* Equivalent to `appDestroyBefore`. Identifies the before app destroy method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( appInstance )
* @property APP_DESTROY_BEFORE
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_DESTROY_BEFORE,
* function(appInstance)
* {
* F2.log(appInstance);
* }
* );
*/
APP_DESTROY_BEFORE: 'appDestroyBefore',
/**
* Equivalent to `appDestroy`. Identifies the app destroy method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( appInstance )
* @property APP_DESTROY
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_DESTROY,
* function(appInstance)
* {
* // call the apps destroy method, if it has one
* if(appInstance && appInstance.app && appInstance.app.destroy && typeof(appInstance.app.destroy) == 'function')
* {
* appInstance.app.destroy();
* }
* else if(appInstance && appInstance.app && appInstance.app.destroy)
* {
* F2.log(appInstance.config.appId + ' has a destroy property, but destroy is not of type function and as such will not be executed.');
* }
*
* // fade out and remove the root
* jQuery(appInstance.config.root).fadeOut(500, function() {
* jQuery(this).remove();
* });
* }
* );
*/
APP_DESTROY: 'appDestroy',
/**
* Equivalent to `appDestroyAfter`. Identifies the after app destroy method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( appInstance )
* @property APP_DESTROY_AFTER
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_DESTROY_AFTER,
* function(appInstance)
* {
* F2.log(appInstance);
* }
* );
*/
APP_DESTROY_AFTER: 'appDestroyAfter'
};
})()
});
/**
* Class stubs for documentation purposes
* @main F2
*/
F2.extend('', {
/**
* The App Class is an optional class that can be namespaced onto the
* {{#crossLink "F2\Apps"}}{{/crossLink}} namespace. The
* [F2 Docs](../../app-development.html#app-class)
* has more information on the usage of the App Class.
* @class F2.App
* @constructor
* @param {F2.AppConfig} appConfig The F2.AppConfig object for the app
* @param {F2.AppManifest.AppContent} appContent The F2.AppManifest.AppContent
* object
* @param {Element} root The root DOM Element for the app
*/
App: function(appConfig, appContent, root) {
return {
/**
* An optional init function that will automatically be called when
* F2.{{#crossLink "F2\registerApps"}}{{/crossLink}} is called.
* @method init
* @optional
*/
init:function() {}
};
},
/**
* The AppConfig object represents an app's meta data
* @class F2.AppConfig
*/
AppConfig: {
/**
* The unique ID of the app. More information can be found
* [here](../../app-development.html#f2-appid)
* @property appId
* @type string
* @required
*/
appId: '',
/**
* An object that represents the context of an app
* @property context
* @type object
*/
context: {},
/**
* True if the app should be requested in a single request with other apps.
* @property enableBatchRequests
* @type bool
* @default false
*/
enableBatchRequests: false,
/**
* The height of the app. The initial height will be pulled from
* the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object, but later
* modified by calling
* F2.UI.{{#crossLink "F2.UI/updateHeight"}}{{/crossLink}}. This is used
* for secure apps to be able to set the initial height of the iframe.
* @property height
* @type int
*/
height: 0,
/**
* The unique runtime ID of the app.
*
* **This property is populated during the
* F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process**
* @property instanceId
* @type string
*/
instanceId: '',
/**
* True if the app will be loaded in an iframe. This property
* will be true if the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object
* sets isSecure = true. It will also be true if the
* [container](../../container-development.html) has made the decision to
* run apps in iframes.
* @property isSecure
* @type bool
* @default false
*/
isSecure: false,
/**
* The url to retrieve the {{#crossLink "F2.AppManifest"}}{{/crossLink}}
* object.
* @property manifestUrl
* @type string
* @required
*/
manifestUrl: '',
/**
* The recommended maximum width in pixels that this app should be run.
* **It is up to the [container](../../container-development.html) to
* implement the logic to prevent an app from being run when the maxWidth
* requirements are not met.**
* @property maxWidth
* @type int
*/
maxWidth: 0,
/**
* The recommended minimum grid size that this app should be run. This
* value corresponds to the 12-grid system that is used by the
* [container](../../container-development.html). This property should be
* set by apps that require a certain number of columns in their layout.
* @property minGridSize
* @type int
* @default 4
*/
minGridSize: 4,
/**
* The recommended minimum width in pixels that this app should be run. **It
* is up to the [container](../../container-development.html) to implement
* the logic to prevent an app from being run when the minWidth requirements
* are not met.
* @property minWidth
* @type int
* @default 300
*/
minWidth: 300,
/**
* The name of the app
* @property name
* @type string
* @required
*/
name: '',
/**
* The root DOM element that contains the app
*
* **This property is populated during the
* F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process**
* @property root
* @type Element
*/
root: undefined,
/**
* The instance of F2.UI providing easy access to F2.UI methods
*
* **This property is populated during the
* F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process**
* @property ui
* @type F2.UI
*/
ui: undefined,
/**
* The views that this app supports. Available views
* are defined in {{#crossLink "F2.Constants.Views"}}{{/crossLink}}. The
* presence of a view can be checked via
* F2.{{#crossLink "F2/inArray"}}{{/crossLink}}:
*
* F2.inArray(F2.Constants.Views.SETTINGS, app.views)
*
* @property views
* @type Array
*/
views: []
},
/**
* The assets needed to render an app on the page
* @class F2.AppManifest
*/
AppManifest: {
/**
* The array of {{#crossLink "F2.AppManifest.AppContent"}}{{/crossLink}}
* objects
* @property apps
* @type Array
* @required
*/
apps: [],
/**
* Any inline javascript tha should initially be run
* @property inlineScripts
* @type Array
* @optional
*/
inlineScripts: [],
/**
* Urls to javascript files required by the app
* @property scripts
* @type Array
* @optional
*/
scripts: [],
/**
* Urls to CSS files required by the app
* @property styles
* @type Array
* @optional
*/
styles: []
},
/**
* The AppContent object
* @class F2.AppManifest.AppContent
**/
AppContent: {
/**
* Arbitrary data to be passed along with the app
* @property data
* @type object
* @optional
*/
data: {},
/**
* The string of HTML representing the app
* @property html
* @type string
* @required
*/
html: '',
/**
* A status message
* @property status
* @type string
* @optional
*/
status: ''
},
/**
* An object containing configuration information for the
* [container](../../container-development.html)
* @class F2.ContainerConfig
*/
ContainerConfig: {
/**
* Allows the [container](../../container-development.html) to override how
* an app's html is inserted into the page. The function should accept an
* {{#crossLink "F2.AppConfig"}}{{/crossLink}} object and also a string of
* html
* @method afterAppRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {string} html The string of html representing the app
* @return {Element} The DOM Element surrounding the app
*/
afterAppRender: function(appConfig, html) {},
/**
* Allows the [container](../../container-development.html) to wrap an app
* in extra html. The function should accept an
* {{#crossLink "F2.AppConfig"}}{{/crossLink}} object and also a string of
* html. The extra html can provide links to edit app settings and remove an
* app from the container. See
* {{#crossLink "F2.Constants.Css"}}{{/crossLink}} for CSS classes that
* should be applied to elements.
* @method appRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {string} html The string of html representing the app
*/
appRender: function(appConfig, html) {},
/**
* Allows the container to render html for an app before the AppManifest for
* an app has loaded. This can be useful if the design calls for loading
* icons to appear for each app before each app is loaded and rendered to
* the page.
* @method beforeAppRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @return {Element} The DOM Element surrounding the app
*/
beforeAppRender: function(appConfig) {},
/**
* True to enable debug mode in F2.js. Adds additional logging, resource cache busting, etc.
* @property debugMode
* @type bool
* @default false
*/
debugMode: false,
/**
* Milliseconds before F2 fires callback on script resource load errors. Due to issue with the way Internet Explorer attaches load events to script elements, the error event doesn't fire.
* @property scriptErrorTimeout
* @type milliseconds
* @default 7000 (7 seconds)
*/
scriptErrorTimeout: 7000,
/**
* Tells the container that it is currently running within
* a secure app page
* @property isSecureAppPage
* @type bool
*/
isSecureAppPage: false,
/**
* Allows the container to specify which page is used when
* loading a secure app. The page must reside on a different domain than the
* container
* @property secureAppPagePath
* @type string
* @for F2.ContainerConfig
*/
secureAppPagePath: '',
/**
* Specifies what views a container will provide buttons
* or links to. Generally, the views will be switched via buttons or links
* in the app's header.
* @property supportedViews
* @type Array
* @required
*/
supportedViews: [],
/**
* An object containing configuration defaults for F2.UI
* @class F2.ContainerConfig.UI
*/
UI: {
/**
* An object containing configuration defaults for the
* F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} and
* F2.UI.{{#crossLink "F2.UI/hideMask"}}{{/crossLink}} methods.
* @class F2.ContainerConfig.UI.Mask
*/
Mask: {
/**
* The backround color of the overlay
* @property backgroundColor
* @type string
* @default #FFF
*/
backgroundColor: '#FFF',
/**
* The path to the loading icon
* @property loadingIcon
* @type string
*/
loadingIcon: '',
/**
* The opacity of the background overlay
* @property opacity
* @type int
* @default 0.6
*/
opacity: 0.6,
/**
* Do not use inline styles for mask functinality. Instead classes will
* be applied to the elements and it is up to the container provider to
* implement the class definitions.
* @property useClasses
* @type bool
* @default false
*/
useClasses: false,
/**
* The z-index to use for the overlay
* @property zIndex
* @type int
* @default 2
*/
zIndex: 2
}
},
/**
* Allows the container to fully override how the AppManifest request is
* made inside of F2.
*
* @method xhr
* @param {string} url The manifest url
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
* objects
* @param {function} success The function to be called if the request
* succeeds
* @param {function} error The function to be called if the request fails
* @param {function} complete The function to be called when the request
* finishes (after success and error callbacks have been executed)
* @return {XMLHttpRequest} The XMLHttpRequest object (or an object that has
* an `abort` function (such as the jqXHR object in jQuery) to abort the
* request)
*
* @example
* F2.init({
* xhr: function(url, appConfigs, success, error, complete) {
* $.ajax({
* url: url,
* type: 'POST',
* data: {
* params: F2.stringify(appConfigs, F2.appConfigReplacer)
* },
* jsonp: false, // do not put 'callback=' in the query string
* jsonpCallback: F2.Constants.JSONP_CALLBACK + appConfigs[0].appId, // Unique function name
* dataType: 'json',
* success: function(appManifest) {
* // custom success logic
* success(appManifest); // fire success callback
* },
* error: function() {
* // custom error logic
* error(); // fire error callback
* },
* complete: function() {
* // custom complete logic
* complete(); // fire complete callback
* }
* });
* }
* });
*
* @for F2.ContainerConfig
*/
//xhr: function(url, appConfigs, success, error, complete) {},
/**
* Allows the container to override individual parts of the AppManifest
* request. See properties and methods with the `xhr.` prefix.
* @property xhr
* @type Object
*
* @example
* F2.init({
* xhr: {
* url: function(url, appConfigs) {
* return 'http://example.com/proxy.php?url=' + encocdeURIComponent(url);
* }
* }
* });
*/
xhr: {
/**
* Allows the container to override the request data type (JSON or JSONP)
* that is used for the request
* @method xhr.dataType
* @param {string} url The manifest url
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
* objects
* @return {string} The request data type that should be used
*
* @example
* F2.init({
* xhr: {
* dataType: function(url) {
* return F2.isLocalRequest(url) ? 'json' : 'jsonp';
* },
* type: function(url) {
* return F2.isLocalRequest(url) ? 'POST' : 'GET';
* }
* }
* });
*/
dataType: function(url, appConfigs) {},
/**
* Allows the container to override the request method that is used (just
* like the `type` parameter to `jQuery.ajax()`.
* @method xhr.type
* @param {string} url The manifest url
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
* objects
* @return {string} The request method that should be used
*
* @example
* F2.init({
* xhr: {
* dataType: function(url) {
* return F2.isLocalRequest(url) ? 'json' : 'jsonp';
* },
* type: function(url) {
* return F2.isLocalRequest(url) ? 'POST' : 'GET';
* }
* }
* });
*/
type: function(url, appConfigs) {},
/**
* Allows the container to override the url that is used to request an
* app's F2.{{#crossLink "F2.AppManifest"}}{{/crossLink}}
* @method xhr.url
* @param {string} url The manifest url
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
* objects
* @return {string} The url that should be used for the request
*
* @example
* F2.init({
* xhr: {
* url: function(url, appConfigs) {
* return 'http://example.com/proxy.php?url=' + encocdeURIComponent(url);
* }
* }
* });
*/
url: function(url, appConfigs) {}
}
}
});
/**
* Constants used throughout the Open Financial Framework
* @class F2.Constants
* @static
*/
F2.extend('Constants', {
/**
* CSS class constants
* @class F2.Constants.Css
*/
Css: (function() {
/** @private */
var _PREFIX = 'f2-';
return {
/**
* The APP class should be applied to the DOM Element that surrounds the
* entire app, including any extra html that surrounds the APP\_CONTAINER
* that is inserted by the container. See the
* {{#crossLink "F2.ContainerConfig"}}{{/crossLink}} object.
* @property APP
* @type string
* @static
* @final
*/
APP: _PREFIX + 'app',
/**
* The APP\_CONTAINER class should be applied to the outermost DOM Element
* of the app.
* @property APP_CONTAINER
* @type string
* @static
* @final
*/
APP_CONTAINER: _PREFIX + 'app-container',
/**
* The APP\_TITLE class should be applied to the DOM Element that contains
* the title for an app. If this class is not present, then
* F2.UI.{{#crossLink "F2.UI/setTitle"}}{{/crossLink}} will not function.
* @property APP_TITLE
* @type string
* @static
* @final
*/
APP_TITLE: _PREFIX + 'app-title',
/**
* The APP\_VIEW class should be applied to the DOM Element that contains
* a view for an app. The DOM Element should also have a
* {{#crossLink "F2.Constants.Views"}}{{/crossLink}}.DATA_ATTRIBUTE
* attribute that specifies which
* {{#crossLink "F2.Constants.Views"}}{{/crossLink}} it is.
* @property APP_VIEW
* @type string
* @static
* @final
*/
APP_VIEW: _PREFIX + 'app-view',
/**
* APP\_VIEW\_TRIGGER class should be applied to the DOM Elements that
* trigger an
* {{#crossLink "F2.Constants.Events"}}{{/crossLink}}.APP\_VIEW\_CHANGE
* event. The DOM Element should also have a
* {{#crossLink "F2.Constants.Views"}}{{/crossLink}}.DATA_ATTRIBUTE
* attribute that specifies which
* {{#crossLink "F2.Constants.Views"}}{{/crossLink}} it will trigger.
* @property APP_VIEW_TRIGGER
* @type string
* @static
* @final
*/
APP_VIEW_TRIGGER: _PREFIX + 'app-view-trigger',
/**
* The MASK class is applied to the overlay element that is created
* when the F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} method is
* fired.
* @property MASK
* @type string
* @static
* @final
*/
MASK: _PREFIX + 'mask',
/**
* The MASK_CONTAINER class is applied to the Element that is passed into
* the F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} method.
* @property MASK_CONTAINER
* @type string
* @static
* @final
*/
MASK_CONTAINER: _PREFIX + 'mask-container'
};
})(),
/**
* Events constants
* @class F2.Constants.Events
*/
Events: (function() {
/** @private */
var _APP_EVENT_PREFIX = 'App.';
/** @private */
var _CONTAINER_EVENT_PREFIX = 'Container.';
return {
/**
* The APP\_SYMBOL\_CHANGE event is fired when the symbol is changed in an
* app. It is up to the app developer to fire this event.
* Returns an object with the symbol and company name:
*
* { symbol: 'MSFT', name: 'Microsoft Corp (NASDAQ)' }
*
* @property APP_SYMBOL_CHANGE
* @type string
* @static
* @final
*/
APP_SYMBOL_CHANGE: _APP_EVENT_PREFIX + 'symbolChange',
/**
* The APP\_WIDTH\_CHANGE event will be fired by the container when the
* width of an app is changed. The app's instanceId should be concatenated
* to this constant.
* Returns an object with the gridSize and width in pixels:
*
* { gridSize:8, width:620 }
*
* @property APP_WIDTH_CHANGE
* @type string
* @static
* @final
*/
APP_WIDTH_CHANGE: _APP_EVENT_PREFIX + 'widthChange.',
/**
* The CONTAINER\_SYMBOL\_CHANGE event is fired when the symbol is changed
* at the container level. This event should only be fired by the
* container or container provider.
* Returns an object with the symbol and company name:
*
* { symbol: 'MSFT', name: 'Microsoft Corp (NASDAQ)' }
*
* @property CONTAINER_SYMBOL_CHANGE
* @type string
* @static
* @final
*/
CONTAINER_SYMBOL_CHANGE: _CONTAINER_EVENT_PREFIX + 'symbolChange',
/**
* The CONTAINER\_WIDTH\_CHANGE event will be fired by the container when
* the width of the container has changed.
* @property CONTAINER_WIDTH_CHANGE
* @type string
* @static
* @final
*/
CONTAINER_WIDTH_CHANGE: _CONTAINER_EVENT_PREFIX + 'widthChange'
};
})(),
JSONP_CALLBACK: 'F2_jsonpCallback_',
/**
* Constants for use with cross-domain sockets
* @class F2.Constants.Sockets
* @protected
*/
Sockets: {
/**
* The EVENT message is sent whenever
* F2.Events.{{#crossLink "F2.Events/emit"}}{{/crossLink}} is fired
* @property EVENT
* @type string
* @static
* @final
*/
EVENT: '__event__',
/**
* The LOAD message is sent when an iframe socket initially loads.
* Returns a JSON string that represents:
*
* [ App, AppManifest]
*
* @property LOAD
* @type string
* @static
* @final
*/
LOAD: '__socketLoad__',
/**
* The RPC message is sent when a method is passed up from within a secure
* app page.
* @property RPC
* @type string
* @static
* @final
*/
RPC: '__rpc__',
/**
* The RPC\_CALLBACK message is sent when a call back from an RPC method is
* fired.
* @property RPC_CALLBACK
* @type string
* @static
* @final
*/
RPC_CALLBACK: '__rpcCallback__',
/**
* The UI\_RPC message is sent when a UI method called.
* @property UI_RPC
* @type string
* @static
* @final
*/
UI_RPC: '__uiRpc__'
},
/**
* The available view types to apps. The view should be specified by applying
* the {{#crossLink "F2.Constants.Css"}}{{/crossLink}}.APP\_VIEW class to the
* containing DOM Element. A DATA\_ATTRIBUTE attribute should be added to the
* Element as well which defines what view type is represented.
* The `hide` class can be applied to views that should be hidden by default.
* @class F2.Constants.Views
*/
Views: {
/**
* The DATA_ATTRIBUTE should be placed on the DOM Element that contains the
* view.
* @property DATA_ATTRIBUTE
* @type string
* @static
* @final
*/
DATA_ATTRIBUTE: 'data-f2-view',
/**
* The ABOUT view gives details about the app.
* @property ABOUT
* @type string
* @static
* @final
*/
ABOUT: 'about',
/**
* The HELP view provides users with help information for using an app.
* @property HELP
* @type string
* @static
* @final
*/
HELP: 'help',
/**
* The HOME view is the main view for an app. This view should always
* be provided by an app.
* @property HOME
* @type string
* @static
* @final
*/
HOME: 'home',
/**
* The REMOVE view is a special view that handles the removal of an app
* from the container.
* @property REMOVE
* @type string
* @static
* @final
*/
REMOVE: 'remove',
/**
* The SETTINGS view provides users the ability to modify advanced settings
* for an app.
* @property SETTINGS
* @type string
* @static
* @final
*/
SETTINGS: 'settings'
}
});
/**
* Handles [Context](../../app-development.html#context) passing from
* containers to apps and apps to apps.
* @class F2.Events
*/
F2.extend('Events', (function() {
// init EventEmitter
var _events = new EventEmitter2({
wildcard:true
});
// unlimited listeners, set to > 0 for debugging
_events.setMaxListeners(0);
return {
/**
* Same as F2.Events.emit except that it will not send the event
* to all sockets.
* @method _socketEmit
* @private
* @param {string} event The event name
* @param {object} [arg]* The arguments to be passed
*/
_socketEmit: function() {
return EventEmitter2.prototype.emit.apply(_events, [].slice.call(arguments));
},
/**
* Execute each of the listeners that may be listening for the specified
* event name in order with the list of arguments.
* @method emit
* @param {string} event The event name
* @param {object} [arg]* The arguments to be passed
*/
emit: function() {
F2.Rpc.broadcast(F2.Constants.Sockets.EVENT, [].slice.call(arguments));
return EventEmitter2.prototype.emit.apply(_events, [].slice.call(arguments));
},
/**
* Adds a listener that will execute n times for the event before being
* removed. The listener is invoked only the first time the event is
* fired, after which it is removed.
* @method many
* @param {string} event The event name
* @param {int} timesToListen The number of times to execute the event
* before being removed
* @param {function} listener The function to be fired when the event is
* emitted
*/
many: function(event, timesToListen, listener) {
return _events.many(event, timesToListen, listener);
},
/**
* Remove a listener for the specified event.
* @method off
* @param {string} event The event name
* @param {function} listener The function that will be removed
*/
off: function(event, listener) {
return _events.off(event, listener);
},
/**
* Adds a listener for the specified event
* @method on
* @param {string} event The event name
* @param {function} listener The function to be fired when the event is
* emitted
*/
on: function(event, listener){
return _events.on(event, listener);
},
/**
* Adds a one time listener for the event. The listener is invoked only
* the first time the event is fired, after which it is removed.
* @method once
* @param {string} event The event name
* @param {function} listener The function to be fired when the event is
* emitted
*/
once: function(event, listener) {
return _events.once(event, listener);
}
};
})());
/**
* Handles socket communication between the container and secure apps
* @class F2.Rpc
*/
F2.extend('Rpc', (function(){
var _callbacks = {};
var _secureAppPagePath = '';
var _apps = {};
var _rEvents = new RegExp('^' + F2.Constants.Sockets.EVENT);
var _rRpc = new RegExp('^' + F2.Constants.Sockets.RPC);
var _rRpcCallback = new RegExp('^' + F2.Constants.Sockets.RPC_CALLBACK);
var _rSocketLoad = new RegExp('^' + F2.Constants.Sockets.LOAD);
var _rUiCall = new RegExp('^' + F2.Constants.Sockets.UI_RPC);
/**
* Creates a socket connection from the app to the container using
* <a href="http://easyxdm.net" target="_blank">easyXDM</a>.
* @method _createAppToContainerSocket
* @private
*/
var _createAppToContainerSocket = function() {
var appConfig; // socket closure
var isLoaded = false;
// its possible for messages to be received before the socket load event has
// happened. We'll save off these messages and replay them once the socket
// is ready
var messagePlayback = [];
var socket = new easyXDM.Socket({
onMessage: function(message, origin){
// handle Socket Load
if (!isLoaded && _rSocketLoad.test(message)) {
message = message.replace(_rSocketLoad, '');
var appParts = F2.parse(message);
// make sure we have the AppConfig and AppManifest
if (appParts.length == 2) {
appConfig = appParts[0];
// save socket
_apps[appConfig.instanceId] = {
config:appConfig,
socket:socket
};
// register app
F2.registerApps([appConfig], [appParts[1]]);
// socket message playback
jQuery.each(messagePlayback, function(i, e) {
_onMessage(appConfig, message, origin);
});
isLoaded = true;
}
} else if (isLoaded) {
// pass everyting else to _onMessage
_onMessage(appConfig, message, origin);
} else {
//F2.log('socket not ready, queuing message', message);
messagePlayback.push(message);
}
}
});
};
/**
* Creates a socket connection from the container to the app using
* <a href="http://easyxdm.net" target="_blank">easyXDM</a>.
* @method _createContainerToAppSocket
* @private
* @param {appConfig} appConfig The F2.AppConfig object
* @param {F2.AppManifest} appManifest The F2.AppManifest object
*/
var _createContainerToAppSocket = function(appConfig, appManifest) {
var container = jQuery(appConfig.root);
if (!container.is('.' + F2.Constants.Css.APP_CONTAINER)) {
container.find('.' + F2.Constants.Css.APP_CONTAINER);
}
if (!container.length) {
F2.log('Unable to locate app in order to establish secure connection.');
return;
}
var iframeProps = {
scrolling:'no',
style:{
width:'100%'
}
};
if (appConfig.height) {
iframeProps.style.height = appConfig.height + 'px';
}
var socket = new easyXDM.Socket({
remote: _secureAppPagePath,
container: container.get(0),
props:iframeProps,
onMessage: function(message, origin) {
// pass everything to _onMessage
_onMessage(appConfig, message, origin);
},
onReady: function() {
socket.postMessage(F2.Constants.Sockets.LOAD + F2.stringify([appConfig, appManifest], F2.appConfigReplacer));
}
});
return socket;
};
/**
* @method _createRpcCallback
* @private
* @param {string} instanceId The app's Instance ID
* @param {function} callbackId The callback ID
* @return {function} A function to make the RPC call
*/
var _createRpcCallback = function(instanceId, callbackId) {
return function() {
F2.Rpc.call(
instanceId,
F2.Constants.Sockets.RPC_CALLBACK,
callbackId,
[].slice.call(arguments).slice(2)
);
};
};
/**
* Handles messages that come across the sockets
* @method _onMessage
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {string} message The socket message
* @param {string} origin The originator
*/
var _onMessage = function(appConfig, message, origin) {
var obj, func;
function parseFunction(parent, functionName) {
var path = String(functionName).split('.');
for (var i = 0; i < path.length; i++) {
if (parent[path[i]] === undefined) {
parent = undefined;
break;
}
parent = parent[path[i]];
}
return parent;
}
function parseMessage(regEx, message, instanceId) {
var o = F2.parse(message.replace(regEx, ''));
// if obj.callbacks
// for each callback
// for each params
// if callback matches param
// replace param with _createRpcCallback(app.instanceId, callback)
if (o.params && o.params.length && o.callbacks && o.callbacks.length) {
jQuery.each(o.callbacks, function(i, c) {
jQuery.each(o.params, function(i, p) {
if (c == p) {
o.params[i] = _createRpcCallback(instanceId, c);
}
});
});
}
return o;
}
// handle UI Call
if (_rUiCall.test(message)) {
obj = parseMessage(_rUiCall, message, appConfig.instanceId);
func = parseFunction(appConfig.ui, obj.functionName);
// if we found the function, call it
if (func !== undefined) {
func.apply(appConfig.ui, obj.params);
} else {
F2.log('Unable to locate UI RPC function: ' + obj.functionName);
}
// handle RPC
} else if (_rRpc.test(message)) {
obj = parseMessage(_rRpc, message, appConfig.instanceId);
func = parseFunction(window, obj.functionName);
if (func !== undefined) {
func.apply(func, obj.params);
} else {
F2.log('Unable to locate RPC function: ' + obj.functionName);
}
// handle RPC Callback
} else if (_rRpcCallback.test(message)) {
obj = parseMessage(_rRpcCallback, message, appConfig.instanceId);
if (_callbacks[obj.functionName] !== undefined) {
_callbacks[obj.functionName].apply(_callbacks[obj.functionName], obj.params);
delete _callbacks[obj.functionName];
}
// handle Events
} else if (_rEvents.test(message)) {
obj = parseMessage(_rEvents, message, appConfig.instanceId);
F2.Events._socketEmit.apply(F2.Events, obj);
}
};
/**
* Registers a callback function
* @method _registerCallback
* @private
* @param {function} callback The callback function
* @return {string} The callback ID
*/
var _registerCallback = function(callback) {
var callbackId = F2.guid();
_callbacks[callbackId] = callback;
return callbackId;
};
return {
/**
* Broadcast an RPC function to all sockets
* @method broadcast
* @param {string} messageType The message type
* @param {Array} params The parameters to broadcast
*/
broadcast: function(messageType, params) {
// check valid messageType
var message = messageType + F2.stringify(params);
jQuery.each(_apps, function(i, a) {
a.socket.postMessage(message);
});
},
/**
* Calls a remote function
* @method call
* @param {string} instanceId The app's Instance ID
* @param {string} messageType The message type
* @param {string} functionName The name of the remote function
* @param {Array} params An array of parameters to pass to the remote
* function. Any functions found within the params will be treated as a
* callback function.
*/
call: function(instanceId, messageType, functionName, params) {
// loop through params and find functions and convert them to callbacks
var callbacks = [];
jQuery.each(params, function(i, e) {
if (typeof e === 'function') {
var cid = _registerCallback(e);
params[i] = cid;
callbacks.push(cid);
}
});
// check valid messageType
_apps[instanceId].socket.postMessage(
messageType + F2.stringify({
functionName:functionName,
params:params,
callbacks:callbacks
})
);
},
/**
* Init function which tells F2.Rpc whether it is running at the container-
* level or the app-level. This method is generally called by
* F2.{{#crossLink "F2/init"}}{{/crossLink}}
* @method init
* @param {string} [secureAppPagePath] The
* {{#crossLink "F2.ContainerConfig"}}{{/crossLink}}.secureAppPagePath
* property
*/
init: function(secureAppPagePath) {
_secureAppPagePath = secureAppPagePath;
if (!_secureAppPagePath) {
_createAppToContainerSocket();
}
},
/**
* Determines whether the Instance ID is considered to be 'remote'. This is
* determined by checking if 1) the app has an open socket and 2) whether
* F2.Rpc is running inside of an iframe
* @method isRemote
* @param {string} instanceId The Instance ID
* @return {bool} True if there is an open socket
*/
isRemote: function(instanceId) {
return (
// we have an app
_apps[instanceId] !== undefined &&
// the app is secure
_apps[instanceId].config.isSecure &&
// we can't access the iframe
jQuery(_apps[instanceId].config.root).find('iframe').length === 0
);
},
/**
* Creates a container-to-app or app-to-container socket for communication
* @method register
* @param {F2.AppConfig} [appConfig] The F2.AppConfig object
* @param {F2.AppManifest} [appManifest] The F2.AppManifest object
*/
register: function(appConfig, appManifest) {
if (!!appConfig && !!appManifest) {
_apps[appConfig.instanceId] = {
config:appConfig,
socket:_createContainerToAppSocket(appConfig, appManifest)
};
} else {
F2.log('Unable to register socket connection. Please check container configuration.');
}
}
};
})());
F2.extend('UI', (function(){
var _containerConfig;
/**
* UI helper methods
* @class F2.UI
* @constructor
* @param {F2.AppConfig} appConfig The F2.AppConfig object
*/
var UI_Class = function(appConfig) {
var _appConfig = appConfig;
var $root = jQuery(appConfig.root);
var _updateHeight = function(height) {
height = height || jQuery(_appConfig.root).outerHeight();
if (F2.Rpc.isRemote(_appConfig.instanceId)) {
F2.Rpc.call(
_appConfig.instanceId,
F2.Constants.Sockets.UI_RPC,
'updateHeight',
[
height
]
);
} else {
_appConfig.height = height;
$root.find('iframe').height(_appConfig.height);
}
};
return {
/**
* Removes a overlay from an Element on the page
* @method hideMask
* @param {string|Element} selector The Element or selector to an Element
* that currently contains the loader
*/
hideMask: function(selector) {
F2.UI.hideMask(_appConfig.instanceId, selector);
},
/**
* Helper methods for creating and using Modals
* @class F2.UI.Modals
* @for F2.UI
*/
Modals: (function(){
var _renderAlert = function(message) {
return [
'<div class="modal">',
'<header class="modal-header">',
'<h3>Alert!</h3>',
'</header>',
'<div class="modal-body">',
'<p>',
message,
'</p>',
'</div>',
'<div class="modal-footer">',
'<button class="btn btn-primary btn-ok">OK</button>',
'</div>',
'</div>'
].join('');
};
var _renderConfirm = function(message) {
return [
'<div class="modal">',
'<header class="modal-header">',
'<h3>Confirm</h3>',
'</header>',
'<div class="modal-body">',
'<p>',
message,
'</p>',
'</div>',
'<div class="modal-footer">',
'<button type="button" class="btn btn-primary btn-ok">OK</button>',
'<button type="button" class="btn btn-cancel">Cancel</button">',
'</div>',
'</div>'
].join('');
};
return {
/**
* Display an alert message on the page
* @method alert
* @param {string} message The message to be displayed
* @param {function} [callback] The callback to be fired when the user
* closes the dialog
* @for F2.UI.Modals
*/
alert: function(message, callback) {
if (!F2.isInit()) {
F2.log('F2.init() must be called before F2.UI.Modals.alert()');
return;
}
if (F2.Rpc.isRemote(_appConfig.instanceId)) {
F2.Rpc.call(
_appConfig.instanceId,
F2.Constants.Sockets.UI_RPC,
'Modals.alert',
[].slice.call(arguments)
);
} else {
// display the alert
jQuery(_renderAlert(message))
.on('show', function() {
var modal = this;
jQuery(modal).find('.btn-primary').on('click', function() {
jQuery(modal).modal('hide').remove();
(callback || jQuery.noop)();
});
})
.modal({backdrop:true});
}
},
/**
* Display a confirm message on the page
* @method confirm
* @param {string} message The message to be displayed
* @param {function} okCallback The function that will be called when the OK
* button is pressed
* @param {function} cancelCallback The function that will be called when
* the Cancel button is pressed
* @for F2.UI.Modals
*/
confirm: function(message, okCallback, cancelCallback) {
if (!F2.isInit()) {
F2.log('F2.init() must be called before F2.UI.Modals.confirm()');
return;
}
if (F2.Rpc.isRemote(_appConfig.instanceId)) {
F2.Rpc.call(
_appConfig.instanceId,
F2.Constants.Sockets.UI_RPC,
'Modals.confirm',
[].slice.call(arguments)
);
} else {
// display the alert
jQuery(_renderConfirm(message))
.on('show', function() {
var modal = this;
jQuery(modal).find('.btn-ok').on('click', function() {
jQuery(modal).modal('hide').remove();
(okCallback || jQuery.noop)();
});
jQuery(modal).find('.btn-cancel').on('click', function() {
jQuery(modal).modal('hide').remove();
(cancelCallback || jQuery.noop)();
});
})
.modal({backdrop:true});
}
}
};
})(),
/**
* Sets the title of the app as shown in the browser. Depending on the
* container HTML, this method may do nothing if the container has not been
* configured properly or else the container provider does not allow Title's
* to be set.
* @method setTitle
* @params {string} title The title of the app
* @for F2.UI
*/
setTitle: function(title) {
if (F2.Rpc.isRemote(_appConfig.instanceId)) {
F2.Rpc.call(
_appConfig.instanceId,
F2.Constants.Sockets.UI_RPC,
'setTitle',
[
title
]
);
} else {
jQuery(_appConfig.root).find('.' + F2.Constants.Css.APP_TITLE).text(title);
}
},
/**
* Display an ovarlay over an Element on the page
* @method showMask
* @param {string|Element} selector The Element or selector to an Element
* over which to display the loader
* @param {bool} showLoading Display a loading icon
*/
showMask: function(selector, showLoader) {
F2.UI.showMask(_appConfig.instanceId, selector, showLoader);
},
/**
* For secure apps, this method updates the size of the iframe that
* contains the app. **Note: It is recommended that app developers call
* this method anytime Elements are added or removed from the DOM**
* @method updateHeight
* @params {int} height The height of the app
*/
updateHeight: _updateHeight,
/**
* Helper methods for creating and using Views
* @class F2.UI.Views
* @for F2.UI
*/
Views: (function(){
var _events = new EventEmitter2();
var _rValidEvents = /change/i;
// unlimited listeners, set to > 0 for debugging
_events.setMaxListeners(0);
var _isValid = function(eventName) {
if (_rValidEvents.test(eventName)) {
return true;
} else {
F2.log('"' + eventName + '" is not a valid F2.UI.Views event name');
return false;
}
};
return {
/**
* Change the current view for the app or add an event listener
* @method change
* @param {string|function} [input] If a string is passed in, the view
* will be changed for the app. If a function is passed in, a change
* event listener will be added.
* @for F2.UI.Views
*/
change: function(input) {
if (typeof input === 'function') {
this.on('change', input);
} else if (typeof input === 'string') {
if (_appConfig.isSecure && !F2.Rpc.isRemote(_appConfig.instanceId)) {
F2.Rpc.call(
_appConfig.instanceId,
F2.Constants.Sockets.UI_RPC,
'Views.change',
[].slice.call(arguments)
);
} else if (F2.inArray(input, _appConfig.views)) {
jQuery('.' + F2.Constants.Css.APP_VIEW, $root)
.addClass('hide')
.filter('[data-f2-view="' + input + '"]', $root)
.removeClass('hide');
_updateHeight();
_events.emit('change', input);
}
}
},
/**
* Removes a view event listener
* @method off
* @param {string} event The event name
* @param {function} listener The function that will be removed
* @for F2.UI.Views
*/
off: function(event, listener) {
if (_isValid(event)) {
_events.off(event, listener);
}
},
/**
* Adds a view event listener
* @method on
* @param {string} event The event name
* @param {function} listener The function to be fired when the event is
* emitted
* @for F2.UI.Views
*/
on: function(event, listener) {
if (_isValid(event)) {
_events.on(event, listener);
}
}
};
})()
};
};
/**
* Removes a overlay from an Element on the page
* @method hideMask
* @static
* @param {string} instanceId The Instance ID of the app
* @param {string|Element} selector The Element or selector to an Element
* that currently contains the loader
* @for F2.UI
*/
UI_Class.hideMask = function(instanceId, selector) {
if (!F2.isInit()) {
F2.log('F2.init() must be called before F2.UI.hideMask()');
return;
}
if (F2.Rpc.isRemote(instanceId) && !jQuery(selector).is('.' + F2.Constants.Css.APP)) {
F2.Rpc.call(
instanceId,
F2.Constants.Sockets.RPC,
'F2.UI.hideMask',
[
instanceId,
// must only pass the selector argument. if we pass an Element there
// will be F2.stringify() errors
jQuery(selector).selector
]
);
} else {
var container = jQuery(selector);
container.find('> .' + F2.Constants.Css.MASK).remove();
container.removeClass(F2.Constants.Css.MASK_CONTAINER);
// if the element contains this data property, we need to reset static
// position
if (container.data(F2.Constants.Css.MASK_CONTAINER)) {
container.css({'position':'static'});
}
}
};
/**
*
* @method init
* @static
* @param {F2.ContainerConfig} containerConfig The F2.ContainerConfig object
*/
UI_Class.init = function(containerConfig) {
_containerConfig = containerConfig;
// set defaults
_containerConfig.UI = jQuery.extend(true, {}, F2.ContainerConfig.UI, _containerConfig.UI || {});
};
/**
* Display an ovarlay over an Element on the page
* @method showMask
* @static
* @param {string} instanceId The Instance ID of the app
* @param {string|Element} selector The Element or selector to an Element
* over which to display the loader
* @param {bool} showLoading Display a loading icon
*/
UI_Class.showMask = function(instanceId, selector, showLoading) {
if (!F2.isInit()) {
F2.log('F2.init() must be called before F2.UI.showMask()');
return;
}
if (F2.Rpc.isRemote(instanceId) && jQuery(selector).is('.' + F2.Constants.Css.APP)) {
F2.Rpc.call(
instanceId,
F2.Constants.Sockets.RPC,
'F2.UI.showMask',
[
instanceId,
// must only pass the selector argument. if we pass an Element there
// will be F2.stringify() errors
jQuery(selector).selector,
showLoading
]
);
} else {
if (showLoading && !_containerConfig.UI.Mask.loadingIcon) {
F2.log('Unable to display loading icon. Please set F2.ContainerConfig.UI.Mask.loadingIcon when calling F2.init();');
}
var container = jQuery(selector).addClass(F2.Constants.Css.MASK_CONTAINER);
var mask = jQuery('<div>')
.height('100%' /*container.outerHeight()*/)
.width('100%' /*container.outerWidth()*/)
.addClass(F2.Constants.Css.MASK);
// set inline styles if useClasses is false
if (!_containerConfig.UI.Mask.useClasses) {
mask.css({
'background-color':_containerConfig.UI.Mask.backgroundColor,
'background-image': !!_containerConfig.UI.Mask.loadingIcon ? ('url(' + _containerConfig.UI.Mask.loadingIcon + ')') : '',
'background-position':'50% 50%',
'background-repeat':'no-repeat',
'display':'block',
'left':0,
'min-height':30,
'padding':0,
'position':'absolute',
'top':0,
'z-index':_containerConfig.UI.Mask.zIndex,
'filter':'alpha(opacity=' + (_containerConfig.UI.Mask.opacity * 100) + ')',
'opacity':_containerConfig.UI.Mask.opacity
});
}
// only set the position if the container is currently static
if (container.css('position') === 'static') {
container.css({'position':'relative'});
// setting this data property tells hideMask to set the position
// back to static
container.data(F2.Constants.Css.MASK_CONTAINER, true);
}
// add the mask to the container
container.append(mask);
}
};
return UI_Class;
})());
/**
* Root namespace of the F2 SDK
* @module f2
* @class F2
*/
F2.extend('', (function(){
var _apps = {};
var _config = false;
var _bUsesAppHandlers = false;
var _sAppHandlerToken = F2.AppHandlers.__f2GetToken();
/**
* Appends the app's html to the DOM
* @method _afterAppRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {string} html The string of html
* @return {Element} The DOM Element that contains the app
*/
var _afterAppRender = function(appConfig, html) {
var handler = _config.afterAppRender || function(appConfig, html) {
return jQuery(html).appendTo('body');
};
var appContainer = handler(appConfig, html);
if (!!_config.afterAppRender && !appContainer) {
F2.log('F2.ContainerConfig.afterAppRender() must return the DOM Element that contains the app');
return;
} else {
// apply APP class and Instance ID
jQuery(appContainer).addClass(F2.Constants.Css.APP);
return appContainer.get(0);
}
};
/**
* Renders the html for an app.
* @method _appRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {string} html The string of html
*/
var _appRender = function(appConfig, html) {
// apply APP_CONTAINER class
html = _outerHtml(jQuery(html).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfig.appId));
// optionally apply wrapper html
if (_config.appRender) {
html = _config.appRender(appConfig, html);
}
// apply APP class and instanceId
return _outerHtml(html);
};
/**
* Rendering hook to allow containers to render some html prior to an app
* loading
* @method _beforeAppRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @return {Element} The DOM Element surrounding the app
*/
var _beforeAppRender = function(appConfig) {
var handler = _config.beforeAppRender || jQuery.noop;
return handler(appConfig);
};
/**
* Adds properties to the AppConfig object
* @method _createAppConfig
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @return {F2.AppConfig} The new F2.AppConfig object, prepopulated with
* necessary properties
*/
var _createAppConfig = function(appConfig) {
// make a copy of the app config to ensure that the original is not modified
appConfig = jQuery.extend(true, {}, appConfig);
// create the instanceId for the app
appConfig.instanceId = appConfig.instanceId || F2.guid();
// default the views if not provided
appConfig.views = appConfig.views || [];
if (!F2.inArray(F2.Constants.Views.HOME, appConfig.views)) {
appConfig.views.push(F2.Constants.Views.HOME);
}
return appConfig;
};
/**
* Adds properties to the ContainerConfig object to take advantage of defaults
* @method _hydrateContainerConfig
* @private
* @param {F2.ContainerConfig} containerConfig The F2.ContainerConfig object
*/
var _hydrateContainerConfig = function(containerConfig) {
if (!containerConfig.scriptErrorTimeout){
containerConfig.scriptErrorTimeout = F2.ContainerConfig.scriptErrorTimeout;
}
if (containerConfig.debugMode !== true){
containerConfig.debugMode = F2.ContainerConfig.debugMode;
}
};
/**
* Attach app events
* @method _initAppEvents
* @private
*/
var _initAppEvents = function (appConfig) {
jQuery(appConfig.root).on('click', '.' + F2.Constants.Css.APP_VIEW_TRIGGER + '[' + F2.Constants.Views.DATA_ATTRIBUTE + ']', function(event) {
event.preventDefault();
var view = jQuery(this).attr(F2.Constants.Views.DATA_ATTRIBUTE).toLowerCase();
// handle the special REMOVE view
if (view == F2.Constants.Views.REMOVE) {
F2.removeApp(appConfig.instanceId);
} else {
appConfig.ui.Views.change(view);
}
});
};
/**
* Attach container Events
* @method _initContainerEvents
* @private
*/
var _initContainerEvents = function() {
var resizeTimeout;
var resizeHandler = function() {
F2.Events.emit(F2.Constants.Events.CONTAINER_WIDTH_CHANGE);
};
jQuery(window).on('resize', function() {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(resizeHandler, 100);
});
};
/**
* Has the container been init?
* @method _isInit
* @private
* @return {bool} True if the container has been init
*/
var _isInit = function() {
return !!_config;
};
/**
* Instantiates each app from it's appConfig and stores that in a local private collection
* @method _createAppInstance
* @private
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} objects
*/
var _createAppInstance = function(appConfig, appContent){
// instantiate F2.UI
appConfig.ui = new F2.UI(appConfig);
// instantiate F2.App
if (F2.Apps[appConfig.appId] !== undefined) {
if (typeof F2.Apps[appConfig.appId] === 'function') {
// IE
setTimeout(function() {
_apps[appConfig.instanceId].app = new F2.Apps[appConfig.appId](appConfig, appContent, appConfig.root);
if (_apps[appConfig.instanceId].app['init'] !== undefined) {
_apps[appConfig.instanceId].app.init();
}
}, 0);
} else {
F2.log('app initialization class is defined but not a function. (' + appConfig.appId + ')');
}
}
};
/**
* Loads the app's html/css/javascript
* @method loadApp
* @private
* @param {Array} appConfigs An array of
* {{#crossLink "F2.AppConfig"}}{{/crossLink}} objects
* @param {F2.AppManifest} [appManifest] The AppManifest object
*/
var _loadApps = function(appConfigs, appManifest) {
appConfigs = [].concat(appConfigs);
// check for secure app
if (appConfigs.length == 1 && appConfigs[0].isSecure && !_config.isSecureAppPage) {
_loadSecureApp(appConfigs[0], appManifest);
return;
}
// check that the number of apps in manifest matches the number requested
if (appConfigs.length != appManifest.apps.length) {
F2.log('The number of apps defined in the AppManifest do not match the number requested.', appManifest);
return;
}
var scripts = appManifest.scripts || [];
var styles = appManifest.styles || [];
var inlines = appManifest.inlineScripts || [];
var scriptCount = scripts.length;
var scriptsLoaded = 0;
var appInit = function() {
jQuery.each(appConfigs, function(i, a) {
_createAppInstance(a, appManifest.apps[i]);
});
};
//Check to see if any of the ways a file can be ready are available as properties on the file's element (borrowed from yepnope)
var isFileReady = function(readyState) {
return ( !readyState || readyState == 'loaded' || readyState == 'complete' || readyState == 'uninitialized' );
};
var _onload = function(e){
if ( e.type == 'load' || isFileReady((e.currentTarget || e.srcElement).readyState) ){
//done, cleanup
var script = e.currentTarget || e.srcElement;
if (script.detachEvent){
script.detachEvent('onreadystatechange', _onload);//IE
} else {
removeEventListener(script, _onload, 'load');
removeEventListener(script, _error, 'error');
}
}
//are we done loading all scripts for this app?
if (++scriptsLoaded == scriptCount) {
evalInlines();
appInit();
}
};
var _error = function(e){
//log and emit event for the failed (400,500) scripts
setTimeout(function(){
var evtData = {
src: e.target.src,
appId: appConfigs[0].appId
};
//send error to console
F2.log('Script defined in \'' + evtData.appId + '\' failed to load \'' + evtData.src + '\'');
//emit event
F2.Events.emit('RESOURCE_FAILED_TO_LOAD', evtData);
}, _config.scriptErrorTimeout);//defaults to 7000
};
//eval inlines
var evalInlines = function(){
jQuery.each(inlines, function(i, e) {
try {
eval(e);
} catch (exception) {
F2.log('Error loading inline script: ' + exception + '\n\n' + e);
}
});
};
// load styles, see #101
var stylesFragment = null,
useCreateStyleSheet = !!document.createStyleSheet;
jQuery.each(styles, function(i, e) {
if (useCreateStyleSheet) {
document.createStyleSheet(e);
} else {
stylesFragment = stylesFragment || [];
stylesFragment.push('<link rel="stylesheet" type="text/css" href="' + e + '"/>');
}
});
if (stylesFragment){
jQuery('head').append(stylesFragment.join(''));
}
// load html
jQuery.each(appManifest.apps, function(i, a) {
if(!_bUsesAppHandlers) {
// load html and save the root node
appConfigs[i].root = _afterAppRender(appConfigs[i], _appRender(appConfigs[i], a.html));
} else {
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_RENDER,
appConfigs[i], // the app config
_outerHtml(a.html)
);
var appId = appConfigs[i].appId;
if (!appConfigs[i].root) {
throw('Root for ' +appId+ ' must be a native DOM element and cannot be null or undefined. Check your AppHandler callbacks to ensure you have set App root to a native DOM element.');
}
var $root = jQuery(appConfigs[i].root);
if ($root.parents('body:first').length === 0) {
throw('App root for ' +appId+ ' was not appended to the DOM. Check your AppHandler callbacks to ensure you have rendered the app root to the DOM.');
}
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_RENDER_AFTER,
appConfigs[i] // the app config
);
if(!F2.isNativeDOMNode(appConfigs[i].root)) {
throw('App root for ' +appId+ ' must be a native DOM element. Check your AppHandler callbacks to ensure you have set app root to a native DOM element.');
}
$root.addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appId);
}
// init events
_initAppEvents(appConfigs[i]);
});
// load scripts and eval inlines once complete
jQuery.each(scripts, function(i, e) {
var doc = document,
script = doc.createElement('script'),
resourceUrl = e;
//if in debugMode, add cache buster to each script URL
if (_config.debugMode){
resourceUrl += '?cachebuster=' + new Date().getTime();
}
//scripts needed to be loaded in order they're defined in the AppManifest
script.async = false;
//add other attrs
script.src = resourceUrl;
script.type = 'text/javascript';
script.charset = 'utf-8';
//attach load event to script to evaluate inline scripts and init the AppClass
if (script.attachEvent && !(script.attachEvent.toString && script.attachEvent.toString().indexOf('[native code') < 0)){//for IE, from requirejs
script.attachEvent('onreadystatechange', _onload);
} else {
script.addEventListener('load', _onload, false);
//attach error event for 400s and 500s
script.addEventListener('error', _error, false);
}
doc.body.appendChild(script);
});
// if no scripts were to be processed, fire the appInit event
if (!scriptCount) {
evalInlines();
appInit();
}
};
/**
* Loads the app's html/css/javascript into an iframe
* @method loadSecureApp
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {F2.AppManifest} appManifest The app's html/css/js to be loaded into the
* page.
*/
var _loadSecureApp = function(appConfig, appManifest) {
// make sure the container is configured for secure apps
if (_config.secureAppPagePath) {
if(!_bUsesAppHandlers) {
// create the html container for the iframe
appConfig.root = _afterAppRender(appConfig, _appRender(appConfig, '<div></div>'));
} else {
var $root = jQuery(appConfig.root);
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_RENDER,
appConfig, // the app config
appManifest.html
);
if ($root.parents('body:first').length === 0) {
throw('App was never rendered on the page. Please check your AppHandler callbacks to ensure you have rendered the app root to the DOM.');
}
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_RENDER_AFTER,
appConfig // the app config
);
if (!appConfig.root) {
throw('App Root must be a native dom node and can not be null or undefined. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.');
}
if (!F2.isNativeDOMNode(appConfig.root)) {
throw('App Root must be a native dom node. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.');
}
jQuery(appConfig.root).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfig.appId);
}
// instantiate F2.UI
appConfig.ui = new F2.UI(appConfig);
// init events
_initAppEvents(appConfig);
// create RPC socket
F2.Rpc.register(appConfig, appManifest);
} else {
F2.log('Unable to load secure app: "secureAppPagePath" is not defined in F2.ContainerConfig.');
}
};
var _outerHtml = function(html) {
return jQuery('<div></div>').append(html).html();
};
/**
* Checks if the app is valid
* @method _validateApp
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @returns {bool} True if the app is valid
*/
var _validateApp = function(appConfig) {
// check for valid app configurations
if (!appConfig.appId) {
F2.log('"appId" missing from app object');
return false;
} else if (!appConfig.root && !appConfig.manifestUrl) {
F2.log('"manifestUrl" missing from app object');
return false;
}
return true;
};
/**
* Checks if the ContainerConfig is valid
* @method _validateContainerConfig
* @private
* @returns {bool} True if the config is valid
*/
var _validateContainerConfig = function() {
if (_config) {
if (_config.xhr) {
if (!(typeof _config.xhr === 'function' || typeof _config.xhr === 'object')) {
throw('ContainerConfig.xhr should be a function or an object');
}
if (_config.xhr.dataType && typeof _config.xhr.dataType !== 'function') {
throw('ContainerConfig.xhr.dataType should be a function');
}
if (_config.xhr.type && typeof _config.xhr.type !== 'function') {
throw('ContainerConfig.xhr.type should be a function');
}
if (_config.xhr.url && typeof _config.xhr.url !== 'function') {
throw('ContainerConfig.xhr.url should be a function');
}
}
}
return true;
};
return {
/**
* Gets the current list of apps in the container
* @method getContainerState
* @returns {Array} An array of objects containing the appId
*/
getContainerState: function() {
if (!_isInit()) {
F2.log('F2.init() must be called before F2.getContainerState()');
return;
}
return jQuery.map(_apps, function(app) {
return { appId: app.config.appId };
});
},
/**
* Initializes the container. This method must be called before performing
* any other actions in the container.
* @method init
* @param {F2.ContainerConfig} config The configuration object
*/
init: function(config) {
_config = config || {};
_validateContainerConfig();
_hydrateContainerConfig(_config);
// dictates whether we use the old logic or the new logic.
// TODO: Remove in v2.0
_bUsesAppHandlers = (!_config.beforeAppRender && !_config.appRender && !_config.afterAppRender);
// only establish RPC connection if the container supports the secure app page
if (!!_config.secureAppPagePath || _config.isSecureAppPage) {
F2.Rpc.init(!!_config.secureAppPagePath ? _config.secureAppPagePath : false);
}
F2.UI.init(_config);
if (!_config.isSecureAppPage) {
_initContainerEvents();
}
},
/**
* Has the container been init?
* @method isInit
* @return {bool} True if the container has been init
*/
isInit: _isInit,
/**
* Begins the loading process for all apps and/or initialization process for pre-loaded apps.
* The app will be passed the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object which will
* contain the app's unique instanceId within the container. If the
* {{#crossLink "F2.AppConfig"}}{{/crossLink}}.root property is populated the app is considered
* to be a pre-loaded app and will be handled accordingly. Optionally, the
* {{#crossLink "F2.AppManifest"}}{{/crossLink}} can be passed in and those
* assets will be used instead of making a request.
* @method registerApps
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
* objects
* @param {Array} [appManifests] An array of
* {{#crossLink "F2.AppManifest"}}{{/crossLink}}
* objects. This array must be the same length as the apps array that is
* objects. This array must be the same length as the apps array that is
* passed in. This can be useful if apps are loaded on the server-side and
* passed down to the client.
* @example
* Traditional App requests.
*
* // Traditional f2 app configs
* var arConfigs = [
* {
* appId: 'com_externaldomain_example_app',
* context: {},
* manifestUrl: 'http://www.externaldomain.com/F2/AppManifest'
* },
* {
* appId: 'com_externaldomain_example_app',
* context: {},
* manifestUrl: 'http://www.externaldomain.com/F2/AppManifest'
* },
* {
* appId: 'com_externaldomain_example_app2',
* context: {},
* manifestUrl: 'http://www.externaldomain.com/F2/AppManifest'
* }
* ];
*
* F2.init();
* F2.registerApps(arConfigs);
*
* @example
* Pre-loaded and tradition apps mixed.
*
* // Pre-loaded apps and traditional f2 app configs
* // you can preload the same app multiple times as long as you have a unique root for each
* var arConfigs = [
* {
* appId: 'com_mydomain_example_app',
* context: {},
* root: 'div#example-app-1',
* manifestUrl: ''
* },
* {
* appId: 'com_mydomain_example_app',
* context: {},
* root: 'div#example-app-2',
* manifestUrl: ''
* },
* {
* appId: 'com_externaldomain_example_app',
* context: {},
* manifestUrl: 'http://www.externaldomain.com/F2/AppManifest'
* }
* ];
*
* F2.init();
* F2.registerApps(arConfigs);
*
* @example
* Apps with predefined manifests.
*
* // Traditional f2 app configs
* var arConfigs = [
* {appId: 'com_externaldomain_example_app', context: {}},
* {appId: 'com_externaldomain_example_app', context: {}},
* {appId: 'com_externaldomain_example_app2', context: {}}
* ];
*
* // Pre requested manifest responses
* var arManifests = [
* {
* apps: ['<div>Example App!</div>'],
* inlineScripts: [],
* scripts: ['http://www.domain.com/js/AppClass.js'],
* styles: ['http://www.domain.com/css/AppStyles.css']
* },
* {
* apps: ['<div>Example App!</div>'],
* inlineScripts: [],
* scripts: ['http://www.domain.com/js/AppClass.js'],
* styles: ['http://www.domain.com/css/AppStyles.css']
* },
* {
* apps: ['<div>Example App 2!</div>'],
* inlineScripts: [],
* scripts: ['http://www.domain.com/js/App2Class.js'],
* styles: ['http://www.domain.com/css/App2Styles.css']
* }
* ];
*
* F2.init();
* F2.registerApps(arConfigs, arManifests);
*/
registerApps: function(appConfigs, appManifests) {
if (!_isInit()) {
F2.log('F2.init() must be called before F2.registerApps()');
return;
} else if (!appConfigs) {
F2.log('At least one AppConfig must be passed when calling F2.registerApps()');
return;
}
var appStack = [];
var batches = {};
var callbackStack = {};
var haveManifests = false;
appConfigs = [].concat(appConfigs);
appManifests = [].concat(appManifests || []);
haveManifests = !!appManifests.length;
// appConfigs must have a length
if (!appConfigs.length) {
F2.log('At least one AppConfig must be passed when calling F2.registerApps()');
return;
// ensure that the array of apps and manifests are qual
} else if (appConfigs.length && haveManifests && appConfigs.length != appManifests.length) {
F2.log('The length of "apps" does not equal the length of "appManifests"');
return;
}
// validate each app and assign it an instanceId
// then determine which apps can be batched together
jQuery.each(appConfigs, function(i, a) {
// add properties and methods
a = _createAppConfig(a);
// Will set to itself, for preloaded apps, or set to null for apps that aren't already
// on the page.
a.root = a.root || null;
// we validate the app after setting the root property because pre-load apps do no require
// manifest url
if (!_validateApp(a)) {
return; // move to the next app
}
// save app
_apps[a.instanceId] = { config:a };
// If the root property is defined then this app is considered to be preloaded and we will
// run it through that logic.
if(a.root)
{
if((!a.root && typeof(a.root) != 'string') && !F2.isNativeDOMNode(a.root))
{
F2.log('AppConfig invalid for pre-load, not a valid string and not dom node');
F2.log('AppConfig instance:', a);
throw('Preloaded appConfig.root property must be a native dom node or a string representing a sizzle selector. Please check your inputs and try again.');
}
else if(jQuery(a.root).length != 1)
{
F2.log('AppConfig invalid for pre-load, root not unique');
F2.log('AppConfig instance:', a);
F2.log('Number of dom node instances:', jQuery(a.root).length);
throw('Preloaded appConfig.root property must map to a unique dom node. Please check your inputs and try again.');
}
// instantiate F2.App
_createAppInstance(a);
// init events
_initAppEvents(a);
// Continue on in the .each loop, no need to continue because the app is on the page
// the js in initialized, and it is ready to role.
return; // equivalent to continue in .each
}
if(!_bUsesAppHandlers)
{
// fire beforeAppRender
a.root = _beforeAppRender(a);
}
else
{
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_CREATE_ROOT,
a // the app config
);
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_RENDER_BEFORE,
a // the app config
);
}
// if we have the manifest, go ahead and load the app
if (haveManifests) {
_loadApps(a, appManifests[i]);
} else {
// check if this app can be batched
if (a.enableBatchRequests && !a.isSecure) {
batches[a.manifestUrl.toLowerCase()] = batches[a.manifestUrl.toLowerCase()] || [];
batches[a.manifestUrl.toLowerCase()].push(a);
} else {
appStack.push({
apps:[a],
url:a.manifestUrl
});
}
}
});
// we don't have the manifests, go ahead and load them
if (!haveManifests) {
// add the batches to the appStack
jQuery.each(batches, function(i, b) {
appStack.push({ url:i, apps:b });
});
// if an app is being loaded more than once on the page, there is the
// potential that the jsonp callback will be clobbered if the request
// for the AppManifest for the app comes back at the same time as
// another request for the same app. We'll create a callbackStack
// that will ensure that requests for the same app are loaded in order
// rather than at the same time
jQuery.each(appStack, function(i, req) {
// define the callback function based on the first app's App ID
var jsonpCallback = F2.Constants.JSONP_CALLBACK + req.apps[0].appId;
// push the request onto the callback stack
callbackStack[jsonpCallback] = callbackStack[jsonpCallback] || [];
callbackStack[jsonpCallback].push(req);
});
// loop through each item in the callback stack and make the request
// for the AppManifest. When the request is complete, pop the next
// request off the stack and make the request.
jQuery.each(callbackStack, function(i, requests) {
var manifestRequest = function(jsonpCallback, req) {
if (!req) { return; }
// setup defaults and callbacks
var url = req.url,
type = 'GET',
dataType = 'jsonp',
completeFunc = function() {
manifestRequest(i, requests.pop());
},
errorFunc = function() {
jQuery.each(req.apps, function(idx,item){
F2.log('Removed failed ' +item.name+ ' app', item);
F2.removeApp(item.instanceId);
});
},
successFunc = function(appManifest) {
_loadApps(req.apps, appManifest);
};
// optionally fire xhr overrides
if (_config.xhr && _config.xhr.dataType) {
dataType = _config.xhr.dataType(req.url, req.apps);
if (typeof dataType !== 'string') {
throw('ContainerConfig.xhr.dataType should return a string');
}
}
if (_config.xhr && _config.xhr.type) {
type = _config.xhr.type(req.url, req.apps);
if (typeof type !== 'string') {
throw('ContainerConfig.xhr.type should return a string');
}
}
if (_config.xhr && _config.xhr.url) {
url = _config.xhr.url(req.url, req.apps);
if (typeof url !== 'string') {
throw('ContainerConfig.xhr.url should return a string');
}
}
// setup the default request function if an override is not present
var requestFunc = _config.xhr;
if (typeof requestFunc !== 'function') {
requestFunc = function(url, appConfigs, successCallback, errorCallback, completeCallback) {
jQuery.ajax({
url: url,
type: type,
data: {
params: F2.stringify(req.apps, F2.appConfigReplacer)
},
jsonp: false, // do not put 'callback=' in the query string
jsonpCallback: jsonpCallback, // Unique function name
dataType: dataType,
success: successCallback,
error: function(jqxhr, settings, exception) {
F2.log('Failed to load app(s)', exception.toString(), req.apps);
errorCallback();
},
complete: completeCallback
});
};
}
requestFunc(url, req.apps, successFunc, errorFunc, completeFunc);
};
manifestRequest(i, requests.pop());
});
}
},
/**
* Removes all apps from the container
* @method removeAllApps
*/
removeAllApps: function() {
if (!_isInit()) {
F2.log('F2.init() must be called before F2.removeAllApps()');
return;
}
jQuery.each(_apps, function(i, a) {
F2.removeApp(a.config.instanceId);
});
},
/**
* Removes an app from the container
* @method removeApp
* @param {string} instanceId The app's instanceId
*/
removeApp: function(instanceId) {
if (!_isInit()) {
F2.log('F2.init() must be called before F2.removeApp()');
return;
}
if (_apps[instanceId]) {
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_DESTROY_BEFORE,
_apps[instanceId] // the app instance
);
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_DESTROY,
_apps[instanceId] // the app instance
);
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_DESTROY_AFTER,
_apps[instanceId] // the app instance
);
delete _apps[instanceId];
}
}
};
})());
exports.F2 = F2;
if (typeof define !== 'undefined' && define.amd) {
define(function() {
return F2;
});
}
})(typeof exports !== 'undefined' ? exports : window);
|
src/components/Forms/EventForm.js
|
nikolay-radkov/EBudgie
|
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import {
View,
TouchableWithoutFeedback,
Picker,
} from 'react-native';
import {
FormLabel,
FormInput,
Button,
FormValidationMessage,
} from 'react-native-elements';
import _ from 'lodash';
import dismissKeyboard from 'dismissKeyboard';
import UUIDGenerator from 'react-native-uuid-generator';
import moment from 'moment';
import DatePicker from 'react-native-datepicker';
import i18n from 'react-native-i18n';
import theme from '../../themes/ApplicationStyles';
import colors from '../../themes/Colors';
import { popRoute } from '../../boundActionCreators/navigation';
import { translateMany } from '../../services/translator';
import { CATEGORY_PROP, ITEM_PROP } from '../../constants/TranslationProps';
class EventForm extends Component {
constructor(props) {
super(props);
this.state = {
defaultInputValue: props.eventForm.value ? `${props.eventForm.value}` : '',
errorMessage: null,
};
}
componentWillUnmount = () => {
const { resetEventForm } = this.props;
resetEventForm();
}
componentDidMount = () => {
const { setEventDate } = this.props;
const { date } = this.props.eventForm;
if (!date) {
setEventDate(moment().format('YYYY-MM-DD'));
}
}
validateValue = (value) => {
if (!value) {
this.setState({
errorMessage: i18n.t('INVALID_VALUE'),
});
return false;
} else {
this.setState({
errorMessage: null
});
return true;
}
}
onChange = (newValue) => {
const { setEventValue } = this.props;
const value = parseFloat(newValue);
if (!this.validateValue(value)) {
return;
}
setEventValue(value);
}
saveItem = async () => {
const {
newEvent,
pop,
categories,
items,
} = this.props;
const {
id,
categoryId,
itemId,
value,
date,
} = this.props.eventForm;
if (!this.validateValue(value)) {
return;
}
const selectedCategoryId = categoryId ? categoryId : categories[0].id;
const selectedItemId = itemId ? itemId : items[0].id;
let uuid = id;
if (!id) {
uuid = await UUIDGenerator.getRandomUUID();
}
newEvent({
id: uuid,
value: parseFloat(value),
categoryId: selectedCategoryId,
itemId: selectedItemId,
date: moment(date),
});
pop();
}
render() {
const {
eventForm,
setEventCategory,
setEventItem,
categories,
items,
setEventDate,
buttonText,
buttonIcon
} = this.props;
const { errorMessage, defaultInputValue } = this.state;
const categoryOptions = categories.map((category) => (
<Picker.Item key={category.id} label={category.title} value={category.id} />
));
const itemOptions = items.map((item) => (
<Picker.Item key={item.id} label={item.name} value={item.id} />
));
return (
<TouchableWithoutFeedback onPress={() => dismissKeyboard()}>
<View style={[theme.container,]}>
<FormLabel>{i18n.t('VALUE')}</FormLabel>
<FormInput
defaultValue={defaultInputValue}
keyboardType="numeric"
onChangeText={this.onChange}
onSubmitEditing={() => dismissKeyboard()} />
{errorMessage && <FormValidationMessage>{errorMessage}</FormValidationMessage>}
<FormLabel>{i18n.t('CATEGORY')}</FormLabel>
<Picker
onValueChange={setEventCategory}
selectedValue={eventForm.categoryId}>
{categoryOptions}
</Picker>
<FormLabel>{i18n.t('ITEM')}</FormLabel>
<Picker
onValueChange={setEventItem}
selectedValue={eventForm.itemId}>
{itemOptions}
</Picker>
<FormLabel>{i18n.t('DATE')}</FormLabel>
<DatePicker
// style={{ width: 200 }}
cancelBtnText={i18n.t('CANCEL')}
confirmBtnText={i18n.t('CONFIRM')}
customStyles={{
dateIcon: {
position: 'absolute',
left: 0,
top: 4,
marginLeft: 0
},
dateInput: {
marginLeft: 36
}
}}
date={eventForm.date}
format="YYYY-MM-DD"
mode="date"
onDateChange={setEventDate}
placeholder={i18n.t('SELECT_DATE')}
/>
<View style={{
flexDirection: 'row-reverse'
}}>
<Button
backgroundColor={colors.main}
borderRadius={10}
color={!errorMessage ? colors.snow : colors.error}
disabled={!!errorMessage}
disabledStyle={{
backgroundColor: colors.frost,
}}
icon={{
name: buttonIcon,
color: !errorMessage ? colors.snow : colors.error
}}
iconRight
onPress={this.saveItem}
title={buttonText} />
</View>
</View>
</TouchableWithoutFeedback>
);
}
}
EventForm.propTypes = {
setEventValue: PropTypes.func.isRequired,
setEventCategory: PropTypes.func.isRequired,
setEventItem: PropTypes.func.isRequired,
setEventDate: PropTypes.func.isRequired,
resetEventForm: PropTypes.func.isRequired,
eventForm: PropTypes.object.isRequired,
newEvent: PropTypes.func.isRequired,
pop: PropTypes.func.isRequired,
categories: PropTypes.array.isRequired,
items: PropTypes.array.isRequired,
buttonIcon: PropTypes.string,
buttonText: PropTypes.string,
};
function mapStateToProps(state, ownProps) {
const { ebudgie } = state;
const categories = _.filter(ebudgie.categories, (c) => {
return (_.findIndex(ebudgie.items, (i) => i.categoryId === c.id) !== -1);
});
const items = _.filter(ebudgie.items, (item) => {
return ownProps.eventForm.categoryId ?
item.categoryId === ownProps.eventForm.categoryId
: item.categoryId === ebudgie.categories[0].id;
});
return {
categories: translateMany(categories, CATEGORY_PROP),
items: translateMany(items, ITEM_PROP),
};
}
function mapDispatchToProps(dispatch) {
return {
pop: bindActionCreators(popRoute, dispatch)
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(EventForm);
|
packages/material-ui-icons/src/Filter3TwoTone.js
|
Kagami/material-ui
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M7 17h14V3H7v14zm4-4h4v-2h-2V9h2V7h-4V5h4c1.1 0 2 .89 2 2v1.5c0 .83-.67 1.5-1.5 1.5.83 0 1.5.67 1.5 1.5V13c0 1.11-.9 2-2 2h-4v-2z" opacity=".3" /><path d="M21 1H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14z" /><path d="M17 13v-1.5c0-.83-.67-1.5-1.5-1.5.83 0 1.5-.67 1.5-1.5V7c0-1.11-.9-2-2-2h-4v2h4v2h-2v2h2v2h-4v2h4c1.1 0 2-.89 2-2z" /><path d="M19 23v-2H3V5H1v16c0 1.1.9 2 2 2h16z" /></g></React.Fragment>
, 'Filter3TwoTone');
|
ajax/libs/angular.js/0.10.2/angular.js
|
LorenzoBoccaccia/cdnjs
|
/**
* @license AngularJS v0.10.2
* (c) 2010-2011 AngularJS http://angularjs.org
* License: MIT
*/
'use strict';
(function(window, document, undefined){
////////////////////////////////////
if (typeof document.getAttribute == $undefined)
document.getAttribute = function() {};
/**
* @ngdoc function
* @name angular.lowercase
* @function
*
* @description Converts the specified string to lowercase.
* @param {string} string String to be converted to lowercase.
* @returns {string} Lowercased string.
*/
var lowercase = function (string){ return isString(string) ? string.toLowerCase() : string; };
/**
* @ngdoc function
* @name angular.uppercase
* @function
*
* @description Converts the specified string to uppercase.
* @param {string} string String to be converted to uppercase.
* @returns {string} Uppercased string.
*/
var uppercase = function (string){ return isString(string) ? string.toUpperCase() : string; };
var manualLowercase = function (s) {
return isString(s)
? s.replace(/[A-Z]/g, function (ch) {return fromCharCode(ch.charCodeAt(0) | 32); })
: s;
};
var manualUppercase = function (s) {
return isString(s)
? s.replace(/[a-z]/g, function (ch) {return fromCharCode(ch.charCodeAt(0) & ~32); })
: s;
};
// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
// with correct but slower alternatives.
if ('i' !== 'I'.toLowerCase()) {
lowercase = manualLowercase;
uppercase = manualUppercase;
}
function fromCharCode(code) { return String.fromCharCode(code); }
var _undefined = undefined,
_null = null,
$$scope = '$scope',
$$validate = '$validate',
$angular = 'angular',
$array = 'array',
$boolean = 'boolean',
$console = 'console',
$date = 'date',
$length = 'length',
$name = 'name',
$noop = 'noop',
$null = 'null',
$number = 'number',
$object = 'object',
$string = 'string',
$value = 'value',
$selected = 'selected',
$undefined = 'undefined',
NG_EXCEPTION = 'ng-exception',
NG_VALIDATION_ERROR = 'ng-validation-error',
NOOP = 'noop',
Error = window.Error,
/** holds major version number for IE or NaN for real browsers */
msie = parseInt((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1], 10),
jqLite, // delay binding since jQuery could be loaded after us.
jQuery, // delay binding
slice = [].slice,
push = [].push,
error = window[$console]
? bind(window[$console], window[$console]['error'] || noop)
: noop,
/** @name angular */
angular = window[$angular] || (window[$angular] = {}),
/** @name angular.markup */
angularTextMarkup = extensionMap(angular, 'markup'),
/** @name angular.attrMarkup */
angularAttrMarkup = extensionMap(angular, 'attrMarkup'),
/** @name angular.directive */
angularDirective = extensionMap(angular, 'directive'),
/** @name angular.widget */
angularWidget = extensionMap(angular, 'widget', lowercase),
/** @name angular.validator */
angularValidator = extensionMap(angular, 'validator'),
/** @name angular.fileter */
angularFilter = extensionMap(angular, 'filter'),
/** @name angular.formatter */
angularFormatter = extensionMap(angular, 'formatter'),
/** @name angular.service */
angularService = extensionMap(angular, 'service'),
angularCallbacks = extensionMap(angular, 'callbacks'),
nodeName_,
rngScript = /^(|.*\/)angular(-.*?)?(\.min)?.js(\?[^#]*)?(#(.*))?$/,
uid = ['0', '0', '0'],
DATE_ISOSTRING_LN = 24;
/**
* @ngdoc function
* @name angular.forEach
* @function
*
* @description
* Invokes the `iterator` function once for each item in `obj` collection, which can be either an
* object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value`
* is the value of an object property or an array element and `key` is the object property key or
* array element index. Specifying a `context` for the function is optional.
*
* Note: this function was previously known as `angular.foreach`.
*
<pre>
var values = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(values, function(value, key){
this.push(key + ': ' + value);
}, log);
expect(log).toEqual(['name: misko', 'gender:male']);
</pre>
*
* @param {Object|Array} obj Object to iterate over.
* @param {function()} iterator Iterator function.
* @param {Object=} context Object to become context (`this`) for the iterator function.
* @returns {Object|Array} Reference to `obj`.
*/
function forEach(obj, iterator, context) {
var key;
if (obj) {
if (isFunction(obj)){
for (key in obj) {
if (key != 'prototype' && key != $length && key != $name && obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key);
}
}
} else if (obj.forEach && obj.forEach !== forEach) {
obj.forEach(iterator, context);
} else if (isObject(obj) && isNumber(obj.length)) {
for (key = 0; key < obj.length; key++)
iterator.call(context, obj[key], key);
} else {
for (key in obj)
iterator.call(context, obj[key], key);
}
}
return obj;
}
function forEachSorted(obj, iterator, context) {
var keys = [];
for (var key in obj) keys.push(key);
keys.sort();
for ( var i = 0; i < keys.length; i++) {
iterator.call(context, obj[keys[i]], keys[i]);
}
return keys;
}
function formatError(arg) {
if (arg instanceof Error) {
if (arg.stack) {
arg = (arg.message && arg.stack.indexOf(arg.message) === -1) ?
'Error: ' + arg.message + '\n' + arg.stack : arg.stack;
} else if (arg.sourceURL) {
arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
}
}
return arg;
}
/**
* @description
* A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric
* characters such as '012ABC'. The reason why we are not using simply a number counter is that
* the number string gets longer over time, and it can also overflow, where as the the nextId
* will grow much slower, it is a string, and it will never overflow.
*
* @returns an unique alpha-numeric string
*/
function nextUid() {
var index = uid.length;
var digit;
while(index) {
index--;
digit = uid[index].charCodeAt(0);
if (digit == 57 /*'9'*/) {
uid[index] = 'A';
return uid.join('');
}
if (digit == 90 /*'Z'*/) {
uid[index] = '0';
} else {
uid[index] = String.fromCharCode(digit + 1);
return uid.join('');
}
}
uid.unshift('0');
return uid.join('');
}
/**
* @ngdoc function
* @name angular.extend
* @function
*
* @description
* Extends the destination object `dst` by copying all of the properties from the `src` object(s)
* to `dst`. You can specify multiple `src` objects.
*
* @param {Object} dst Destination object.
* @param {...Object} src Source object(s).
*/
function extend(dst) {
forEach(arguments, function(obj){
if (obj !== dst) {
forEach(obj, function(value, key){
dst[key] = value;
});
}
});
return dst;
}
function inherit(parent, extra) {
return extend(new (extend(function(){}, {prototype:parent}))(), extra);
}
/**
* @ngdoc function
* @name angular.noop
* @function
*
* @description
* A function that performs no operations. This function can be useful when writing code in the
* functional style.
<pre>
function foo(callback) {
var result = calculateResult();
(callback || angular.noop)(result);
}
</pre>
*/
function noop() {}
/**
* @ngdoc function
* @name angular.identity
* @function
*
* @description
* A function that returns its first argument. This function is useful when writing code in the
* functional style.
*
<pre>
function transformer(transformationFn, value) {
return (transformationFn || identity)(value);
};
</pre>
*/
function identity($) {return $;}
function valueFn(value) {return function(){ return value; };}
function extensionMap(angular, name, transform) {
var extPoint;
return angular[name] || (extPoint = angular[name] = function (name, fn, prop){
name = (transform || identity)(name);
if (isDefined(fn)) {
extPoint[name] = extend(fn, prop || {});
}
return extPoint[name];
});
}
/**
* @ngdoc function
* @name angular.isUndefined
* @function
*
* @description
* Determines if a reference is undefined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is undefined.
*/
function isUndefined(value){ return typeof value == $undefined; }
/**
* @ngdoc function
* @name angular.isDefined
* @function
*
* @description
* Determines if a reference is defined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is defined.
*/
function isDefined(value){ return typeof value != $undefined; }
/**
* @ngdoc function
* @name angular.isObject
* @function
*
* @description
* Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
* considered to be objects.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Object` but not `null`.
*/
function isObject(value){ return value!=null && typeof value == $object;}
/**
* @ngdoc function
* @name angular.isString
* @function
*
* @description
* Determines if a reference is a `String`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `String`.
*/
function isString(value){ return typeof value == $string;}
/**
* @ngdoc function
* @name angular.isNumber
* @function
*
* @description
* Determines if a reference is a `Number`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Number`.
*/
function isNumber(value){ return typeof value == $number;}
/**
* @ngdoc function
* @name angular.isDate
* @function
*
* @description
* Determines if a value is a date.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Date`.
*/
function isDate(value){ return value instanceof Date; }
/**
* @ngdoc function
* @name angular.isArray
* @function
*
* @description
* Determines if a reference is an `Array`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Array`.
*/
function isArray(value) { return value instanceof Array; }
/**
* @ngdoc function
* @name angular.isFunction
* @function
*
* @description
* Determines if a reference is a `Function`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Function`.
*/
function isFunction(value){ return typeof value == 'function';}
/**
* Checks if `obj` is a window object.
*
* @private
* @param {*} obj Object to check
* @returns {boolean} True if `obj` is a window obj.
*/
function isWindow(obj) {
return obj && obj.document && obj.location && obj.alert && obj.setInterval;
}
function isBoolean(value) { return typeof value == $boolean; }
function isTextNode(node) { return nodeName_(node) == '#text'; }
function trim(value) {
return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value;
}
function isElement(node) {
return node &&
(node.nodeName // we are a direct element
|| (node.bind && node.find)); // we have a bind and find method part of jQuery API
}
/**
* @param str 'key1,key2,...'
* @returns {object} in the form of {key1:true, key2:true, ...}
*/
function makeMap(str){
var obj = {}, items = str.split(","), i;
for ( i = 0; i < items.length; i++ )
obj[ items[i] ] = true;
return obj;
}
/**
* HTML class which is the only class which can be used in ng:bind to inline HTML for security
* reasons.
*
* @constructor
* @param html raw (unsafe) html
* @param {string=} option If set to 'usafe', get method will return raw (unsafe/unsanitized) html
*/
function HTML(html, option) {
this.html = html;
this.get = lowercase(option) == 'unsafe'
? valueFn(html)
: function htmlSanitize() {
var buf = [];
htmlParser(html, htmlSanitizeWriter(buf));
return buf.join('');
};
}
if (msie < 9) {
nodeName_ = function(element) {
element = element.nodeName ? element : element[0];
return (element.scopeName && element.scopeName != 'HTML')
? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName;
};
} else {
nodeName_ = function(element) {
return element.nodeName ? element.nodeName : element[0].nodeName;
};
}
function isVisible(element) {
var rect = element[0].getBoundingClientRect(),
width = (rect.width || (rect.right||0 - rect.left||0)),
height = (rect.height || (rect.bottom||0 - rect.top||0));
return width>0 && height>0;
}
function map(obj, iterator, context) {
var results = [];
forEach(obj, function(value, index, list) {
results.push(iterator.call(context, value, index, list));
});
return results;
}
/**
* @ngdoc function
* @name angular.Object.size
* @function
*
* @description
* Determines the number of elements in an array, the number of properties an object has, or
* the length of a string.
*
* Note: This function is used to augment the Object type in Angular expressions. See
* {@link angular.Object} for more information about Angular arrays.
*
* @param {Object|Array|string} obj Object, array, or string to inspect.
* @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object
* @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array.
*
* @example
* <doc:example>
* <doc:source>
* <script>
* function SizeCtrl() {
* this.fooStringLength = angular.Object.size('foo');
* }
* </script>
* <div ng:controller="SizeCtrl">
* Number of items in array: {{ [1,2].$size() }}<br/>
* Number of items in object: {{ {a:1, b:2, c:3}.$size() }}<br/>
* String length: {{fooStringLength}}
* </div>
* </doc:source>
* <doc:scenario>
* it('should print correct sizes for an array and an object', function() {
* expect(binding('[1,2].$size()')).toBe('2');
* expect(binding('{a:1, b:2, c:3}.$size()')).toBe('3');
* expect(binding('fooStringLength')).toBe('3');
* });
* </doc:scenario>
* </doc:example>
*/
function size(obj, ownPropsOnly) {
var size = 0, key;
if (isArray(obj) || isString(obj)) {
return obj.length;
} else if (isObject(obj)){
for (key in obj)
if (!ownPropsOnly || obj.hasOwnProperty(key))
size++;
}
return size;
}
function includes(array, obj) {
for ( var i = 0; i < array.length; i++) {
if (obj === array[i]) return true;
}
return false;
}
function indexOf(array, obj) {
for ( var i = 0; i < array.length; i++) {
if (obj === array[i]) return i;
}
return -1;
}
function isLeafNode (node) {
if (node) {
switch (node.nodeName) {
case "OPTION":
case "PRE":
case "TITLE":
return true;
}
}
return false;
}
/**
* @ngdoc function
* @name angular.copy
* @function
*
* @description
* Alias for {@link angular.Object.copy}
*/
/**
* @ngdoc function
* @name angular.Object.copy
* @function
*
* @description
* Creates a deep copy of `source`, which should be an object or an array.
*
* * If no destination is supplied, a copy of the object or array is created.
* * If a destination is provided, all of its elements (for array) or properties (for objects)
* are deleted and then all elements/properties from the source are copied to it.
* * If `source` is not an object or array, `source` is returned.
*
* Note: this function is used to augment the Object type in Angular expressions. See
* {@link angular.Array} for more information about Angular arrays.
*
* @param {*} source The source that will be used to make a copy.
* Can be any type, including primitives, `null`, and `undefined`.
* @param {(Object|Array)=} destination Destination into which the source is copied. If
* provided, must be of the same type as `source`.
* @returns {*} The copy or updated `destination`, if `destination` was specified.
*
* @example
* <doc:example>
* <doc:source>
Salutation: <input type="text" name="master.salutation" value="Hello" /><br/>
Name: <input type="text" name="master.name" value="world"/><br/>
<button ng:click="form = master.$copy()">copy</button>
<hr/>
The master object is <span ng:hide="master.$equals(form)">NOT</span> equal to the form object.
<pre>master={{master}}</pre>
<pre>form={{form}}</pre>
* </doc:source>
* <doc:scenario>
it('should print that initialy the form object is NOT equal to master', function() {
expect(element('.doc-example-live input[name="master.salutation"]').val()).toBe('Hello');
expect(element('.doc-example-live input[name="master.name"]').val()).toBe('world');
expect(element('.doc-example-live span').css('display')).toBe('inline');
});
it('should make form and master equal when the copy button is clicked', function() {
element('.doc-example-live button').click();
expect(element('.doc-example-live span').css('display')).toBe('none');
});
* </doc:scenario>
* </doc:example>
*/
function copy(source, destination){
if (!destination) {
destination = source;
if (source) {
if (isArray(source)) {
destination = copy(source, []);
} else if (isDate(source)) {
destination = new Date(source.getTime());
} else if (isObject(source)) {
destination = copy(source, {});
}
}
} else {
if (isArray(source)) {
while(destination.length) {
destination.pop();
}
for ( var i = 0; i < source.length; i++) {
destination.push(copy(source[i]));
}
} else {
forEach(destination, function(value, key){
delete destination[key];
});
for ( var key in source) {
destination[key] = copy(source[key]);
}
}
}
return destination;
}
/**
* @ngdoc function
* @name angular.equals
* @function
*
* @description
* Alias for {@link angular.Object.equals}
*/
/**
* @ngdoc function
* @name angular.Object.equals
* @function
*
* @description
* Determines if two objects or two values are equivalent. Supports value types, arrays and
* objects.
*
* Two objects or values are considered equivalent if at least one of the following is true:
*
* * Both objects or values pass `===` comparison.
* * Both objects or values are of the same type and all of their properties pass `===` comparison.
*
* During a property comparision, properties of `function` type and properties with names
* that begin with `$` are ignored.
*
* Note: This function is used to augment the Object type in Angular expressions. See
* {@link angular.Array} for more information about Angular arrays.
*
* @param {*} o1 Object or value to compare.
* @param {*} o2 Object or value to compare.
* @returns {boolean} True if arguments are equal.
*
* @example
* <doc:example>
* <doc:source>
Salutation: <input type="text" name="greeting.salutation" value="Hello" /><br/>
Name: <input type="text" name="greeting.name" value="world"/><br/>
<hr/>
The <code>greeting</code> object is
<span ng:hide="greeting.$equals({salutation:'Hello', name:'world'})">NOT</span> equal to
<code>{salutation:'Hello', name:'world'}</code>.
<pre>greeting={{greeting}}</pre>
* </doc:source>
* <doc:scenario>
it('should print that initialy greeting is equal to the hardcoded value object', function() {
expect(element('.doc-example-live input[name="greeting.salutation"]').val()).toBe('Hello');
expect(element('.doc-example-live input[name="greeting.name"]').val()).toBe('world');
expect(element('.doc-example-live span').css('display')).toBe('none');
});
it('should say that the objects are not equal when the form is modified', function() {
input('greeting.name').enter('kitty');
expect(element('.doc-example-live span').css('display')).toBe('inline');
});
* </doc:scenario>
* </doc:example>
*/
function equals(o1, o2) {
if (o1 === o2) return true;
if (o1 === null || o2 === null) return false;
var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
if (t1 == t2 && t1 == 'object') {
if (o1 instanceof Array) {
if ((length = o1.length) == o2.length) {
for(key=0; key<length; key++) {
if (!equals(o1[key], o2[key])) return false;
}
return true;
}
} else {
keySet = {};
for(key in o1) {
if (key.charAt(0) !== '$' && !isFunction(o1[key]) && !equals(o1[key], o2[key])) {
return false;
}
keySet[key] = true;
}
for(key in o2) {
if (!keySet[key] && key.charAt(0) !== '$' && !isFunction(o2[key])) return false;
}
return true;
}
}
return false;
}
function setHtml(node, html) {
if (isLeafNode(node)) {
if (msie) {
node.innerText = html;
} else {
node.textContent = html;
}
} else {
node.innerHTML = html;
}
}
function isRenderableElement(element) {
var name = element && element[0] && element[0].nodeName;
return name && name.charAt(0) != '#' &&
!includes(['TR', 'COL', 'COLGROUP', 'TBODY', 'THEAD', 'TFOOT'], name);
}
function elementError(element, type, error) {
var parent;
while (!isRenderableElement(element)) {
parent = element.parent();
if (parent.length) {
element = element.parent();
} else {
return;
}
}
if (element[0]['$NG_ERROR'] !== error) {
element[0]['$NG_ERROR'] = error;
if (error) {
element.addClass(type);
element.attr(type, error.message || error);
} else {
element.removeClass(type);
element.removeAttr(type);
}
}
}
function concat(array1, array2, index) {
return array1.concat(slice.call(array2, index));
}
function sliceArgs(args, startIndex) {
return slice.call(args, startIndex || 0);
}
/**
* @ngdoc function
* @name angular.bind
* @function
*
* @description
* Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
* `fn`). You can supply optional `args` that are are prebound to the function. This feature is also
* known as [function currying](http://en.wikipedia.org/wiki/Currying).
*
* @param {Object} self Context which `fn` should be evaluated in.
* @param {function()} fn Function to be bound.
* @param {...*} args Optional arguments to be prebound to the `fn` function call.
* @returns {function()} Function that wraps the `fn` with all the specified bindings.
*/
function bind(self, fn) {
var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
if (isFunction(fn) && !(fn instanceof RegExp)) {
return curryArgs.length
? function() {
return arguments.length
? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
: fn.apply(self, curryArgs);
}
: function() {
return arguments.length
? fn.apply(self, arguments)
: fn.call(self);
};
} else {
// in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
return fn;
}
}
function toBoolean(value) {
if (value && value.length !== 0) {
var v = lowercase("" + value);
value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');
} else {
value = false;
}
return value;
}
/** @name angular.compile */
function compile(element) {
return new Compiler(angularTextMarkup, angularAttrMarkup, angularDirective, angularWidget)
.compile(element);
}
/////////////////////////////////////////////////
/**
* Parses an escaped url query string into key-value pairs.
* @returns Object.<(string|boolean)>
*/
function parseKeyValue(/**string*/keyValue) {
var obj = {}, key_value, key;
forEach((keyValue || "").split('&'), function(keyValue){
if (keyValue) {
key_value = keyValue.split('=');
key = decodeURIComponent(key_value[0]);
obj[key] = isDefined(key_value[1]) ? decodeURIComponent(key_value[1]) : true;
}
});
return obj;
}
function toKeyValue(obj) {
var parts = [];
forEach(obj, function(value, key) {
parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true)));
});
return parts.length ? parts.join('&') : '';
}
/**
* We need our custom mehtod because encodeURIComponent is too agressive and doesn't follow
* http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
* segments:
* segment = *pchar
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* pct-encoded = "%" HEXDIG HEXDIG
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=').
replace(/%2B/gi, '+');
}
/**
* This method is intended for encoding *key* or *value* parts of query component. We need a custom
* method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be
* encoded per http://tools.ietf.org/html/rfc3986:
* query = *( pchar / "/" / "?" )
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriQuery(val, pctEncodeSpaces) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace((pctEncodeSpaces ? null : /%20/g), '+');
}
/**
* @ngdoc directive
* @name angular.directive.ng:autobind
* @element script
*
* @TODO ng:autobind is not a directive!! it should be documented as bootstrap parameter in a
* separate bootstrap section.
* @TODO rename to ng:autobind to ng:autoboot
*
* @description
* Technically, ng:autobind is not a directive; it is an Angular bootstrap parameter that can act
* as a directive. It must exist in the script used to boot Angular and can be used only one time.
* For details on bootstrapping Angular, see {@link guide/dev_guide.bootstrap Initializing Angular}
* in the Angular Developer Guide.
*
* `ng:autobind` with no parameters tells Angular to compile and manage the whole page.
*
* `ng:autobind="[root element ID]"` tells Angular to compile and manage part of the document,
* starting at "root element ID".
*
*/
function angularInit(config, document){
var autobind = config.autobind;
if (autobind) {
var element = isString(autobind) ? document.getElementById(autobind) : document,
scope = compile(element)(createScope()),
$browser = scope.$service('$browser');
if (config.css)
$browser.addCss(config.base_url + config.css);
else if(msie<8)
$browser.addJs(config.ie_compat, config.ie_compat_id);
scope.$apply();
}
}
function angularJsConfig(document, config) {
bindJQuery();
var scripts = document.getElementsByTagName("script"),
match;
config = extend({
ie_compat_id: 'ng-ie-compat'
}, config);
for(var j = 0; j < scripts.length; j++) {
match = (scripts[j].src || "").match(rngScript);
if (match) {
config.base_url = match[1];
config.ie_compat = match[1] + 'angular-ie-compat' + (match[2] || '') + '.js';
extend(config, parseKeyValue(match[6]));
eachAttribute(jqLite(scripts[j]), function(value, name){
if (/^ng:/.exec(name)) {
name = name.substring(3).replace(/-/g, '_');
value = value || true;
config[name] = value;
}
});
}
}
return config;
}
function bindJQuery(){
// bind to jQuery if present;
jQuery = window.jQuery;
// reset to jQuery or default to us.
if (jQuery) {
jqLite = jQuery;
extend(jQuery.fn, {
scope: JQLitePrototype.scope
});
} else {
jqLite = jqLiteWrap;
}
angular.element = jqLite;
}
/**
* throw error of the argument is falsy.
*/
function assertArg(arg, name, reason) {
if (!arg) {
var error = new Error("Argument '" + (name||'?') + "' is " +
(reason || "required"));
throw error;
}
}
function assertArgFn(arg, name) {
assertArg(isFunction(arg), name, 'not a function, got ' +
(typeof arg == 'object' ? arg.constructor.name : typeof arg));
}
/**
* @ngdoc property
* @name angular.version
* @description
* An object that contains information about the current AngularJS version. This object has the
* following properties:
*
* - `full` – `{string}` – Full version string, such as "0.9.18".
* - `major` – `{number}` – Major version number, such as "0".
* - `minor` – `{number}` – Minor version number, such as "9".
* - `dot` – `{number}` – Dot version number, such as "18".
* - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
*/
var version = {
full: '0.10.2', // all of these placeholder strings will be replaced by rake's
major: 0, // compile task
minor: 10,
dot: 2,
codeName: 'sneaky-seagull'
};
var array = [].constructor;
/**
* @ngdoc function
* @name angular.toJson
* @function
*
* @description
* Serializes input into a JSON-formatted string.
*
* @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
* @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
* @returns {string} Jsonified string representing `obj`.
*/
function toJson(obj, pretty) {
var buf = [];
toJsonArray(buf, obj, pretty ? "\n " : null, []);
return buf.join('');
}
/**
* @ngdoc function
* @name angular.fromJson
* @function
*
* @description
* Deserializes a JSON string.
*
* @param {string} json JSON string to deserialize.
* @param {boolean} [useNative=false] Use native JSON parser, if available.
* @returns {Object|Array|Date|string|number} Deserialized thingy.
*/
function fromJson(json, useNative) {
if (!isString(json)) return json;
var obj;
try {
if (useNative && window.JSON && window.JSON.parse) {
obj = JSON.parse(json);
return transformDates(obj);
}
return parser(json, true).primary()();
} catch (e) {
error("fromJson error: ", json, e);
throw e;
}
// TODO make forEach optionally recursive and remove this function
function transformDates(obj) {
if (isString(obj) && obj.length === DATE_ISOSTRING_LN) {
return angularString.toDate(obj);
} else if (isArray(obj) || isObject(obj)) {
forEach(obj, function(val, name) {
obj[name] = transformDates(val);
});
}
return obj;
}
}
angular.toJson = toJson;
angular.fromJson = fromJson;
function toJsonArray(buf, obj, pretty, stack) {
if (isObject(obj)) {
if (obj === window) {
buf.push('WINDOW');
return;
}
if (obj === document) {
buf.push('DOCUMENT');
return;
}
if (includes(stack, obj)) {
buf.push('RECURSION');
return;
}
stack.push(obj);
}
if (obj === null) {
buf.push($null);
} else if (obj instanceof RegExp) {
buf.push(angularString.quoteUnicode(obj.toString()));
} else if (isFunction(obj)) {
return;
} else if (isBoolean(obj)) {
buf.push('' + obj);
} else if (isNumber(obj)) {
if (isNaN(obj)) {
buf.push($null);
} else {
buf.push('' + obj);
}
} else if (isString(obj)) {
return buf.push(angularString.quoteUnicode(obj));
} else if (isObject(obj)) {
if (isArray(obj)) {
buf.push("[");
var len = obj.length;
var sep = false;
for(var i=0; i<len; i++) {
var item = obj[i];
if (sep) buf.push(",");
if (!(item instanceof RegExp) && (isFunction(item) || isUndefined(item))) {
buf.push($null);
} else {
toJsonArray(buf, item, pretty, stack);
}
sep = true;
}
buf.push("]");
} else if (isElement(obj)) {
// TODO(misko): maybe in dev mode have a better error reporting?
buf.push('DOM_ELEMENT');
} else if (isDate(obj)) {
buf.push(angularString.quoteUnicode(angular.Date.toString(obj)));
} else {
buf.push("{");
if (pretty) buf.push(pretty);
var comma = false;
var childPretty = pretty ? pretty + " " : false;
var keys = [];
for(var k in obj) {
if (obj.hasOwnProperty(k) && obj[k] !== undefined) {
keys.push(k);
}
}
keys.sort();
for ( var keyIndex = 0; keyIndex < keys.length; keyIndex++) {
var key = keys[keyIndex];
var value = obj[key];
if (!isFunction(value)) {
if (comma) {
buf.push(",");
if (pretty) buf.push(pretty);
}
buf.push(angularString.quote(key));
buf.push(":");
toJsonArray(buf, value, childPretty, stack);
comma = true;
}
}
buf.push("}");
}
}
if (isObject(obj)) {
stack.pop();
}
}
/**
* Template provides directions an how to bind to a given element.
* It contains a list of init functions which need to be called to
* bind to a new instance of elements. It also provides a list
* of child paths which contain child templates
*/
function Template() {
this.paths = [];
this.children = [];
this.linkFns = [];
this.newScope = false;
}
Template.prototype = {
link: function(element, scope) {
var childScope = scope;
if (this.newScope) {
childScope = isFunction(this.newScope) ? scope.$new(this.newScope(scope)) : scope.$new();
element.data($$scope, childScope);
}
forEach(this.linkFns, function(fn) {
try {
childScope.$service.invoke(childScope, fn, [element]);
} catch (e) {
childScope.$service('$exceptionHandler')(e);
}
});
var i,
childNodes = element[0].childNodes,
children = this.children,
paths = this.paths,
length = paths.length;
for (i = 0; i < length; i++) {
children[i].link(jqLite(childNodes[paths[i]]), childScope);
}
},
addLinkFn:function(linkingFn) {
if (linkingFn) {
if (!linkingFn.$inject)
linkingFn.$inject = [];
this.linkFns.push(linkingFn);
}
},
addChild: function(index, template) {
if (template) {
this.paths.push(index);
this.children.push(template);
}
},
empty: function() {
return this.linkFns.length === 0 && this.paths.length === 0;
}
};
///////////////////////////////////
//Compiler
//////////////////////////////////
/**
* @workInProgress
* @ngdoc function
* @name angular.compile
* @function
*
* @description
* Compiles a piece of HTML string or DOM into a template and produces a template function, which
* can then be used to link {@link angular.scope scope} and the template together.
*
* The compilation is a process of walking the DOM tree and trying to match DOM elements to
* {@link angular.markup markup}, {@link angular.attrMarkup attrMarkup},
* {@link angular.widget widgets}, and {@link angular.directive directives}. For each match it
* executes corresponding markup, attrMarkup, widget or directive template function and collects the
* instance functions into a single template function which is then returned.
*
* The template function can then be used once to produce the view or as it is the case with
* {@link angular.widget.@ng:repeat repeater} many-times, in which case each call results in a view
* that is a DOM clone of the original template.
*
<pre>
// compile the entire window.document and give me the scope bound to this template.
var rootScope = angular.compile(window.document)();
// compile a piece of html
var rootScope2 = angular.compile('<div ng:click="clicked = true">click me</div>')();
// compile a piece of html and retain reference to both the dom and scope
var template = angular.element('<div ng:click="clicked = true">click me</div>'),
scope = angular.compile(template)();
// at this point template was transformed into a view
</pre>
*
*
* @param {string|DOMElement} element Element or HTML to compile into a template function.
* @returns {function([scope][, cloneAttachFn])} a template function which is used to bind template
* (a DOM element/tree) to a scope. Where:
*
* * `scope` - A {@link angular.scope Scope} to bind to. If none specified, then a new
* root scope is created.
* * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
* `template` and call the `cloneAttachFn` function allowing the caller to attach the
* cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
* called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
*
* * `clonedElement` - is a clone of the original `element` passed into the compiler.
* * `scope` - is the current scope with which the linking function is working with.
*
* Calling the template function returns the scope to which the element is bound to. It is either
* the same scope as the one passed into the template function, or if none were provided it's the
* newly create scope.
*
* If you need access to the bound view, there are two ways to do it:
*
* - If you are not asking the linking function to clone the template, create the DOM element(s)
* before you send them to the compiler and keep this reference around.
* <pre>
* var view = angular.element('<p>{{total}}</p>'),
* scope = angular.compile(view)();
* </pre>
*
* - if on the other hand, you need the element to be cloned, the view reference from the original
* example would not point to the clone, but rather to the original template that was cloned. In
* this case, you can access the clone via the cloneAttachFn:
* <pre>
* var original = angular.element('<p>{{total}}</p>'),
* scope = someParentScope.$new(),
* clone;
*
* angular.compile(original)(scope, function(clonedElement, scope) {
* clone = clonedElement;
* //attach the clone to DOM document at the right place
* });
*
* //now we have reference to the cloned DOM via `clone`
* </pre>
*
*
* Compiler Methods For Widgets and Directives:
*
* The following methods are available for use when you write your own widgets, directives,
* and markup. (Recall that the compile function's this is a reference to the compiler.)
*
* `compile(element)` - returns linker -
* Invoke a new instance of the compiler to compile a DOM element and return a linker function.
* You can apply the linker function to the original element or a clone of the original element.
* The linker function returns a scope.
*
* * `comment(commentText)` - returns element - Create a comment element.
*
* * `element(elementName)` - returns element - Create an element by name.
*
* * `text(text)` - returns element - Create a text element.
*
* * `descend([set])` - returns descend state (true or false). Get or set the current descend
* state. If true the compiler will descend to children elements.
*
* * `directives([set])` - returns directive state (true or false). Get or set the current
* directives processing state. The compiler will process directives only when directives set to
* true.
*
* For information on how the compiler works, see the
* {@link guide/dev_guide.compiler Angular HTML Compiler} section of the Developer Guide.
*/
function Compiler(markup, attrMarkup, directives, widgets){
this.markup = markup;
this.attrMarkup = attrMarkup;
this.directives = directives;
this.widgets = widgets;
}
Compiler.prototype = {
compile: function(templateElement) {
templateElement = jqLite(templateElement);
var index = 0,
template,
parent = templateElement.parent();
if (templateElement.length > 1) {
// https://github.com/angular/angular.js/issues/338
throw Error("Cannot compile multiple element roots: " +
jqLite('<div>').append(templateElement.clone()).html());
}
if (parent && parent[0]) {
parent = parent[0];
for(var i = 0; i < parent.childNodes.length; i++) {
if (parent.childNodes[i] == templateElement[0]) {
index = i;
}
}
}
template = this.templatize(templateElement, index) || new Template();
return function(scope, cloneConnectFn){
// important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
// and sometimes changes the structure of the DOM.
var element = cloneConnectFn
? JQLitePrototype.clone.call(templateElement) // IMPORTANT!!!
: templateElement;
scope = scope || createScope();
element.data($$scope, scope);
scope.$element = element;
(cloneConnectFn||noop)(element, scope);
template.link(element, scope);
return scope;
};
},
templatize: function(element, elementIndex){
var self = this,
widget,
fn,
directiveFns = self.directives,
descend = true,
directives = true,
elementName = nodeName_(element),
elementNamespace = elementName.indexOf(':') > 0 ? lowercase(elementName).replace(':', '-') : '',
template,
selfApi = {
compile: bind(self, self.compile),
descend: function(value){ if(isDefined(value)) descend = value; return descend;},
directives: function(value){ if(isDefined(value)) directives = value; return directives;},
scope: function(value){ if(isDefined(value)) template.newScope = template.newScope || value; return template.newScope;}
};
element.addClass(elementNamespace);
template = new Template();
eachAttribute(element, function(value, name){
if (!widget) {
if ((widget = self.widgets('@' + name))) {
element.addClass('ng-attr-widget');
widget = bind(selfApi, widget, value, element);
}
}
});
if (!widget) {
if ((widget = self.widgets(elementName))) {
if (elementNamespace)
element.addClass('ng-widget');
widget = bind(selfApi, widget, element);
}
}
if (widget) {
descend = false;
directives = false;
var parent = element.parent();
template.addLinkFn(widget.call(selfApi, element));
if (parent && parent[0]) {
element = jqLite(parent[0].childNodes[elementIndex]);
}
}
if (descend){
// process markup for text nodes only
for(var i=0, child=element[0].childNodes;
i<child.length; i++) {
if (isTextNode(child[i])) {
forEach(self.markup, function(markup){
if (i<child.length) {
var textNode = jqLite(child[i]);
markup.call(selfApi, textNode.text(), textNode, element);
}
});
}
}
}
if (directives) {
// Process attributes/directives
eachAttribute(element, function(value, name){
forEach(self.attrMarkup, function(markup){
markup.call(selfApi, value, name, element);
});
});
eachAttribute(element, function(value, name){
fn = directiveFns[name];
if (fn) {
element.addClass('ng-directive');
template.addLinkFn((directiveFns[name]).call(selfApi, value, element));
}
});
}
// Process non text child nodes
if (descend) {
eachNode(element, function(child, i){
template.addChild(i, self.templatize(child, i));
});
}
return template.empty() ? null : template;
}
};
function eachNode(element, fn){
var i, chldNodes = element[0].childNodes || [], chld;
for (i = 0; i < chldNodes.length; i++) {
if(!isTextNode(chld = chldNodes[i])) {
fn(jqLite(chld), i);
}
}
}
function eachAttribute(element, fn){
var i, attrs = element[0].attributes || [], chld, attr, name, value, attrValue = {};
for (i = 0; i < attrs.length; i++) {
attr = attrs[i];
name = attr.name;
value = attr.value;
if (msie && name == 'href') {
value = decodeURIComponent(element[0].getAttribute(name, 2));
}
attrValue[name] = value;
}
forEachSorted(attrValue, fn);
}
/**
* DESIGN NOTES
*
* The design decisions behind the scope ware heavily favored for speed and memory consumption.
*
* The typical use of scope is to watch the expressions, which most of the time return the same
* value as last time so we optimize the operation.
*
* Closures construction is expensive from speed as well as memory:
* - no closures, instead ups prototypical inheritance for API
* - Internal state needs to be stored on scope directly, which means that private state is
* exposed as $$____ properties
*
* Loop operations are optimized by using while(count--) { ... }
* - this means that in order to keep the same order of execution as addition we have to add
* items to the array at the begging (shift) instead of at the end (push)
*
* Child scopes are created and removed often
* - Using array would be slow since inserts in meddle are expensive so we use linked list
*
* There are few watches then a lot of observers. This is why you don't want the observer to be
* implemented in the same way as watch. Watch requires return of initialization function which
* are expensive to construct.
*/
function createScope(providers, instanceCache) {
var scope = new Scope();
(scope.$service = createInjector(scope, providers, instanceCache)).eager();
return scope;
}
/**
* @ngdoc function
* @name angular.scope
*
* @description
* A root scope can be created by calling {@link angular.scope angular.scope()}. Child scopes
* are created using the {@link angular.scope.$new $new()} method.
* (Most scopes are created automatically when compiled HTML template is executed.)
*
* Here is a simple scope snippet to show how you can interact with the scope.
* <pre>
var scope = angular.scope();
scope.salutation = 'Hello';
scope.name = 'World';
expect(scope.greeting).toEqual(undefined);
scope.$watch('name', function(){
this.greeting = this.salutation + ' ' + this.name + '!';
}); // initialize the watch
expect(scope.greeting).toEqual(undefined);
scope.name = 'Misko';
// still old value, since watches have not been called yet
expect(scope.greeting).toEqual(undefined);
scope.$digest(); // fire all the watches
expect(scope.greeting).toEqual('Hello Misko!');
* </pre>
*
* # Inheritance
* A scope can inherit from a parent scope, as in this example:
* <pre>
var parent = angular.scope();
var child = parent.$new();
parent.salutation = "Hello";
child.name = "World";
expect(child.salutation).toEqual('Hello');
child.salutation = "Welcome";
expect(child.salutation).toEqual('Welcome');
expect(parent.salutation).toEqual('Hello');
* </pre>
*
* # Dependency Injection
* See {@link guide/dev_guide.di dependency injection}.
*
*
* @param {Object.<string, function()>=} providers Map of service factory which need to be provided
* for the current scope. Defaults to {@link angular.service}.
* @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
* append/override services provided by `providers`. This is handy when unit-testing and having
* the need to override a default service.
* @returns {Object} Newly created scope.
*
*/
function Scope() {
this.$id = nextUid();
this.$$phase = this.$parent = this.$$watchers =
this.$$nextSibling = this.$$prevSibling =
this.$$childHead = this.$$childTail = null;
this.$destructor = noop;
this['this'] = this.$root = this;
this.$$asyncQueue = [];
this.$$listeners = {};
}
/**
* @ngdoc property
* @name angular.scope.$id
* @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for
* debugging.
*/
/**
* @ngdoc property
* @name angular.scope.$service
* @function
*
* @description
* Provides reference to an instance of {@link angular.injector injector} which can be used to
* retrieve {@link angular.service services}. In general the use of this api is discouraged,
* in favor of proper {@link guide/dev_guide.di dependency injection}.
*
* @returns {function} {@link angular.injector injector}
*/
/**
* @ngdoc property
* @name angular.scope.$root
* @returns {Scope} The root scope of the current scope hierarchy.
*/
/**
* @ngdoc property
* @name angular.scope.$parent
* @returns {Scope} The parent scope of the current scope.
*/
Scope.prototype = {
/**
* @ngdoc function
* @name angular.scope.$new
* @function
*
* @description
* Creates a new child {@link angular.scope scope}. The new scope can optionally behave as a
* controller. The parent scope will propagate the {@link angular.scope.$digest $digest()} and
* {@link angular.scope.$digest $digest()} events. The scope can be removed from the scope
* hierarchy using {@link angular.scope.$destroy $destroy()}.
*
* {@link angular.scope.$destroy $destroy()} must be called on a scope when it is desired for
* the scope and its child scopes to be permanently detached from the parent and thus stop
* participating in model change detection and listener notification by invoking.
*
* @param {function()=} Class Constructor function which the scope should be applied to the scope.
* @param {...*} curryArguments Any additional arguments which are curried into the constructor.
* See {@link guide/dev_guide.di dependency injection}.
* @returns {Object} The newly created child scope.
*
*/
$new: function(Class, curryArguments) {
var Child = function() {}; // should be anonymous; This is so that when the minifier munges
// the name it does not become random set of chars. These will then show up as class
// name in the debugger.
var child;
Child.prototype = this;
child = new Child();
child['this'] = child;
child.$$listeners = {};
child.$parent = this;
child.$id = nextUid();
child.$$asyncQueue = [];
child.$$phase = child.$$watchers =
child.$$nextSibling = child.$$childHead = child.$$childTail = null;
child.$$prevSibling = this.$$childTail;
if (this.$$childHead) {
this.$$childTail.$$nextSibling = child;
this.$$childTail = child;
} else {
this.$$childHead = this.$$childTail = child;
}
// short circuit if we have no class
if (Class) {
// can't use forEach, we need speed!
var ClassPrototype = Class.prototype;
for(var key in ClassPrototype) {
child[key] = bind(child, ClassPrototype[key]);
}
this.$service.invoke(child, Class, curryArguments);
}
return child;
},
/**
* @ngdoc function
* @name angular.scope.$watch
* @function
*
* @description
* Registers a `listener` callback to be executed whenever the `watchExpression` changes.
*
* - The `watchExpression` is called on every call to {@link angular.scope.$digest $digest()} and
* should return the value which will be watched. (Since {@link angular.scope.$digest $digest()}
* reruns when it detects changes the `watchExpression` can execute multiple times per
* {@link angular.scope.$digest $digest()} and should be idempotent.)
* - The `listener` is called only when the value from the current `watchExpression` and the
* previous call to `watchExpression' are not equal. The inequality is determined according to
* {@link angular.equals} function. To save the value of the object for later comparison
* {@link angular.copy} function is used. It also means that watching complex options will
* have adverse memory and performance implications.
* - The watch `listener` may change the model, which may trigger other `listener`s to fire. This
* is achieved by rerunning the watchers until no changes are detected. The rerun iteration
* limit is 100 to prevent infinity loop deadlock.
*
*
* If you want to be notified whenever {@link angular.scope.$digest $digest} is called,
* you can register an `watchExpression` function with no `listener`. (Since `watchExpression`,
* can execute multiple times per {@link angular.scope.$digest $digest} cycle when a change is
* detected, be prepared for multiple calls to your listener.)
*
*
* # Example
<pre>
var scope = angular.scope();
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(scope, newValue, oldValue) { counter = counter + 1; });
expect(scope.counter).toEqual(0);
scope.$digest();
// no variable change
expect(scope.counter).toEqual(0);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(1);
</pre>
*
*
*
* @param {(function()|string)} watchExpression Expression that is evaluated on each
* {@link angular.scope.$digest $digest} cycle. A change in the return value triggers a
* call to the `listener`.
*
* - `string`: Evaluated as {@link guide/dev_guide.expressions expression}
* - `function(scope)`: called with current `scope` as a parameter.
* @param {(function()|string)=} listener Callback called whenever the return value of
* the `watchExpression` changes.
*
* - `string`: Evaluated as {@link guide/dev_guide.expressions expression}
* - `function(scope, newValue, oldValue)`: called with current `scope` an previous and
* current values as parameters.
* @returns {function()} Returns a deregistration function for this listener.
*/
$watch: function(watchExp, listener) {
var scope = this,
get = compileToFn(watchExp, 'watch'),
listenFn = compileToFn(listener || noop, 'listener'),
array = scope.$$watchers,
watcher = {
fn: listenFn,
last: Number.NaN, // NaN !== NaN. We used this to force $watch to fire on first run.
get: get
};
if (!array) {
array = scope.$$watchers = [];
}
// we use unshift since we use a while loop in $digest for speed.
// the while loop reads in reverse order.
array.unshift(watcher);
return function() {
angularArray.remove(array, watcher);
};
},
/**
* @ngdoc function
* @name angular.scope.$digest
* @function
*
* @description
* Process all of the {@link angular.scope.$watch watchers} of the current scope and its children.
* Because a {@link angular.scope.$watch watcher}'s listener can change the model, the
* `$digest()` keeps calling the {@link angular.scope.$watch watchers} until no more listeners are
* firing. This means that it is possible to get into an infinite loop. This function will throw
* `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 100.
*
* Usually you don't call `$digest()` directly in
* {@link angular.directive.ng:controller controllers} or in {@link angular.directive directives}.
* Instead a call to {@link angular.scope.$apply $apply()} (typically from within a
* {@link angular.directive directive}) will force a `$digest()`.
*
* If you want to be notified whenever `$digest()` is called,
* you can register a `watchExpression` function with {@link angular.scope.$watch $watch()}
* with no `listener`.
*
* You may have a need to call `$digest()` from within unit-tests, to simulate the scope
* life-cycle.
*
* # Example
<pre>
var scope = angular.scope();
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$digest('name', function(scope, newValue, oldValue) { counter = counter + 1; });
expect(scope.counter).toEqual(0);
scope.$digest();
// no variable change
expect(scope.counter).toEqual(0);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(1);
</pre>
*
*/
$digest: function() {
var watch, value, last,
watchers,
asyncQueue,
length,
dirty, ttl = 100,
next, current, target = this;
if (target.$$phase) {
throw Error(target.$$phase + ' already in progress');
}
do {
dirty = false;
current = target;
do {
current.$$phase = '$digest';
asyncQueue = current.$$asyncQueue;
while(asyncQueue.length) {
try {
current.$eval(asyncQueue.shift());
} catch (e) {
current.$service('$exceptionHandler')(e);
}
}
if ((watchers = current.$$watchers)) {
// process our watches
length = watchers.length;
while (length--) {
try {
watch = watchers[length];
// Most common watches are on primitives, in which case we can short
// circuit it with === operator, only when === fails do we use .equals
if ((value = watch.get(current)) !== (last = watch.last) && !equals(value, last)) {
dirty = true;
watch.fn(current, watch.last = copy(value), last);
}
} catch (e) {
current.$service('$exceptionHandler')(e);
}
}
}
current.$$phase = null;
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $broadcast
if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
while(current !== target && !(next = current.$$nextSibling)) {
current = current.$parent;
}
}
} while ((current = next));
if(!(ttl--)) {
throw Error('100 $digest() iterations reached. Aborting!');
}
} while (dirty);
},
/**
* @ngdoc function
* @name angular.scope.$destroy
* @function
*
* @description
* Remove the current scope (and all of its children) from the parent scope. Removal implies
* that calls to {@link angular.scope.$digest $digest()} will no longer propagate to the current
* scope and its children. Removal also implies that the current scope is eligible for garbage
* collection.
*
* The destructing scope emits an `$destroy` {@link angular.scope.$emit event}.
*
* The `$destroy()` is usually used by directives such as
* {@link angular.widget.@ng:repeat ng:repeat} for managing the unrolling of the loop.
*
*/
$destroy: function() {
if (this.$root == this) return; // we can't remove the root node;
this.$emit('$destroy');
var parent = this.$parent;
if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
},
/**
* @ngdoc function
* @name angular.scope.$eval
* @function
*
* @description
* Executes the `expression` on the current scope returning the result. Any exceptions in the
* expression are propagated (uncaught). This is useful when evaluating engular expressions.
*
* # Example
<pre>
var scope = angular.scope();
scope.a = 1;
scope.b = 2;
expect(scope.$eval('a+b')).toEqual(3);
expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
</pre>
*
* @param {(string|function())=} expression An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/dev_guide.expressions expression}.
* - `function(scope)`: execute the function with the current `scope` parameter.
*
* @returns {*} The result of evaluating the expression.
*/
$eval: function(expr) {
var fn = isString(expr)
? expressionCompile(expr)
: expr || noop;
return fn(this);
},
/**
* @ngdoc function
* @name angular.scope.$evalAsync
* @function
*
* @description
* Executes the expression on the current scope at a later point in time.
*
* The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that:
*
* - it will execute in the current script execution context (before any DOM rendering).
* - at least one {@link angular.scope.$digest $digest cycle} will be performed after
* `expression` execution.
*
* Any exceptions from the execution of the expression are forwarded to the
* {@link angular.service.$exceptionHandler $exceptionHandler} service.
*
* @param {(string|function())=} expression An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/dev_guide.expressions expression}.
* - `function(scope)`: execute the function with the current `scope` parameter.
*
*/
$evalAsync: function(expr) {
this.$$asyncQueue.push(expr);
},
/**
* @ngdoc function
* @name angular.scope.$apply
* @function
*
* @description
* `$apply()` is used to execute an expression in angular from outside of the angular framework.
* (For example from browser DOM events, setTimeout, XHR or third party libraries).
* Because we are calling into the angular framework we need to perform proper scope life-cycle
* of {@link angular.service.$exceptionHandler exception handling},
* {@link angular.scope.$digest executing watches}.
*
* ## Life cycle
*
* # Pseudo-Code of `$apply()`
function $apply(expr) {
try {
return $eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
$root.$digest();
}
}
*
*
* Scope's `$apply()` method transitions through the following stages:
*
* 1. The {@link guide/dev_guide.expressions expression} is executed using the
* {@link angular.scope.$eval $eval()} method.
* 2. Any exceptions from the execution of the expression are forwarded to the
* {@link angular.service.$exceptionHandler $exceptionHandler} service.
* 3. The {@link angular.scope.$watch watch} listeners are fired immediately after the expression
* was executed using the {@link angular.scope.$digest $digest()} method.
*
*
* @param {(string|function())=} exp An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/dev_guide.expressions expression}.
* - `function(scope)`: execute the function with current `scope` parameter.
*
* @returns {*} The result of evaluating the expression.
*/
$apply: function(expr) {
try {
return this.$eval(expr);
} catch (e) {
this.$service('$exceptionHandler')(e);
} finally {
this.$root.$digest();
}
},
/**
* @ngdoc function
* @name angular.scope.$on
* @function
*
* @description
* Listen on events of a given type. See {@link angular.scope.$emit $emit} for discussion of
* event life cycle.
*
* @param {string} name Event name to listen on.
* @param {function(event)} listener Function to call when the event is emitted.
* @returns {function()} Returns a deregistration function for this listener.
*
* The event listener function format is: `function(event)`. The `event` object passed into the
* listener has the following attributes
* - `targetScope` - {Scope}: the scope on which the event was `$emit`-ed or `$broadcast`-ed.
* - `currentScope` - {Scope}: the current scope which is handling the event.
* - `name` - {string}: Name of the event.
* - `cancel` - {function=}: calling `cancel` function will cancel further event propagation
* (available only for events that were `$emit`-ed).
*/
$on: function(name, listener) {
var namedListeners = this.$$listeners[name];
if (!namedListeners) {
this.$$listeners[name] = namedListeners = [];
}
namedListeners.push(listener);
return function() {
angularArray.remove(namedListeners, listener);
};
},
/**
* @ngdoc function
* @name angular.scope.$emit
* @function
*
* @description
* Dispatches an event `name` upwards through the scope hierarchy notifying the
* registered {@link angular.scope.$on} listeners.
*
* The event life cycle starts at the scope on which `$emit` was called. All
* {@link angular.scope.$on listeners} listening for `name` event on this scope get notified.
* Afterwards, the event traverses upwards toward the root scope and calls all registered
* listeners along the way. The event will stop propagating if one of the listeners cancels it.
*
* Any exception emmited from the {@link angular.scope.$on listeners} will be passed
* onto the {@link angular.service.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to emit.
* @param {...*} args Optional set of arguments which will be passed onto the event listeners.
*/
$emit: function(name, args) {
var empty = [],
namedListeners,
canceled = false,
scope = this,
event = {
name: name,
targetScope: scope,
cancel: function(){canceled = true;}
},
listenerArgs = concat([event], arguments, 1),
i, length;
do {
namedListeners = scope.$$listeners[name] || empty;
event.currentScope = scope;
for (i=0, length=namedListeners.length; i<length; i++) {
try {
namedListeners[i].apply(null, listenerArgs);
if (canceled) return;
} catch (e) {
scope.$service('$exceptionHandler')(e);
}
}
//traverse upwards
scope = scope.$parent;
} while (scope);
},
/**
* @ngdoc function
* @name angular.scope.$broadcast
* @function
*
* @description
* Dispatches an event `name` downwards to all child scopes (and their children) notifying the
* registered {@link angular.scope.$on} listeners.
*
* The event life cycle starts at the scope on which `$broadcast` was called. All
* {@link angular.scope.$on listeners} listening for `name` event on this scope get notified.
* Afterwards, the event propagates to all direct and indirect scopes of the current scope and
* calls all registered listeners along the way. The event cannot be canceled.
*
* Any exception emmited from the {@link angular.scope.$on listeners} will be passed
* onto the {@link angular.service.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to emit.
* @param {...*} args Optional set of arguments which will be passed onto the event listeners.
*/
$broadcast: function(name, args) {
var target = this,
current = target,
next = target,
event = { name: name,
targetScope: target },
listenerArgs = concat([event], arguments, 1);
//down while you can, then up and next sibling or up and next sibling until back at root
do {
current = next;
event.currentScope = current;
forEach(current.$$listeners[name], function(listener) {
try {
listener.apply(null, listenerArgs);
} catch(e) {
current.$service('$exceptionHandler')(e);
}
});
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $digest
if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
while(current !== target && !(next = current.$$nextSibling)) {
current = current.$parent;
}
}
} while ((current = next));
}
};
function compileToFn(exp, name) {
var fn = isString(exp)
? expressionCompile(exp)
: exp;
assertArgFn(fn, name);
return fn;
}
/**
* @ngdoc function
* @name angular.injector
* @function
*
* @description
* Creates an injector function that can be used for retrieving services as well as for
* dependency injection (see {@link guide/dev_guide.di dependency injection}).
*
* Angular creates an injector automatically for the root scope and it is available as the
* {@link angular.scope.$service $service} property. Creating an injector doesn't automatically
* create all of the `$eager` {@link angular.service services}. You have to call `injector.eager()`
* to initialize them.
*
* @param {Object=} [factoryScope={}] The `this` for the service factory function.
* @param {Object.<string, function()>=} [factories=angular.service] Map of the service factory
* functions.
* @param {Object.<string, function()>=} [instanceCache={}] Place where instances of services are
* saved for reuse. Can also be used to override services specified by `serviceFactory`
* (useful in tests).
* @returns {function()} Injector function:
*
* * `injector(serviceName)`:
* * `serviceName` - `{string=}` - Name of the service to retrieve.
*
* The injector function also has these properties:
*
* * An `invoke` property which can be used to invoke methods with dependency-injected arguments.
* `injector.invoke(self, fn, curryArgs)`
* * `self` - The "`this`" to be used when invoking the function.
* * `fn` - The function to be invoked. The function may have the `$inject` property that
* lists the set of arguments which should be auto-injected.
* (see {@link guide/dev_guide.di dependency injection}).
* * `curryArgs(array)` - Optional array of arguments to pass to the function
* invocation after the injection arguments (also known as curry arguments or currying).
* * An `eager` property which is used to initialize the eager services.
* `injector.eager()`
*/
function createInjector(factoryScope, factories, instanceCache) {
factories = factories || angularService;
instanceCache = instanceCache || {};
factoryScope = factoryScope || {};
injector.invoke = invoke;
injector.eager = function(){
forEach(factories, function(factory, name){
if (factory.$eager)
injector(name);
if (factory.$creation)
throw new Error("Failed to register service '" + name +
"': $creation property is unsupported. Use $eager:true or see release notes.");
});
};
return injector;
function injector(value){
if (!(value in instanceCache)) {
var factory = factories[value];
if (!factory) throw Error("Unknown provider for '"+value+"'.");
instanceCache[value] = invoke(factoryScope, factory);
}
return instanceCache[value];
}
function invoke(self, fn, args){
args = args || [];
var injectNames = injectionArgs(fn);
var i = injectNames.length;
while(i--) {
args.unshift(injector(injectNames[i]));
}
return fn.apply(self, args);
}
}
/**
* THIS IS NOT PUBLIC DOC YET!
*
* @name angular.annotate
* @function
*
* @description
* Annotate the function with injection arguments. This is equivalent to setting the `$inject`
* property as described in {@link guide.di dependency injection}.
*
* <pre>
* var MyController = angular.annotate('$location', function($location){ ... });
* </pre>
*
* is the same as
*
* <pre>
* var MyController = function($location){ ... };
* MyController.$inject = ['$location'];
* </pre>
*
* @param {String|Array} serviceName... zero or more service names to inject into the
* `annotatedFunction`.
* @param {function} annotatedFunction function to annotate with `$inject`
* functions.
* @returns {function} `annotatedFunction`
*/
function annotate(services, fn) {
if (services instanceof Array) {
fn.$inject = services;
return fn;
} else {
var i = 0,
length = arguments.length - 1, // last one is the destination function
$inject = arguments[length].$inject = [];
for (; i < length; i++) {
$inject.push(arguments[i]);
}
return arguments[length]; // return the last one
}
}
function angularServiceInject(name, fn, inject, eager) {
angularService(name, fn, {$inject:inject, $eager:eager});
}
/**
* @returns the $inject property of function. If not found the
* the $inject is computed by looking at the toString of function and
* extracting all arguments which and assuming that they are the
* injection names.
*/
var FN_ARGS = /^function\s*[^\(]*\(([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(.+?)\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
function injectionArgs(fn) {
assertArgFn(fn);
if (!fn.$inject) {
var args = fn.$inject = [];
var fnText = fn.toString().replace(STRIP_COMMENTS, '');
var argDecl = fnText.match(FN_ARGS);
forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
arg.replace(FN_ARG, function(all, name){
args.push(name);
});
});
}
return fn.$inject;
}
var OPERATORS = {
'null':function(self){return null;},
'true':function(self){return true;},
'false':function(self){return false;},
$undefined:noop,
'+':function(self, a,b){a=a(self); b=b(self); return (isDefined(a)?a:0)+(isDefined(b)?b:0);},
'-':function(self, a,b){a=a(self); b=b(self); return (isDefined(a)?a:0)-(isDefined(b)?b:0);},
'*':function(self, a,b){return a(self)*b(self);},
'/':function(self, a,b){return a(self)/b(self);},
'%':function(self, a,b){return a(self)%b(self);},
'^':function(self, a,b){return a(self)^b(self);},
'=':noop,
'==':function(self, a,b){return a(self)==b(self);},
'!=':function(self, a,b){return a(self)!=b(self);},
'<':function(self, a,b){return a(self)<b(self);},
'>':function(self, a,b){return a(self)>b(self);},
'<=':function(self, a,b){return a(self)<=b(self);},
'>=':function(self, a,b){return a(self)>=b(self);},
'&&':function(self, a,b){return a(self)&&b(self);},
'||':function(self, a,b){return a(self)||b(self);},
'&':function(self, a,b){return a(self)&b(self);},
// '|':function(self, a,b){return a|b;},
'|':function(self, a,b){return b(self)(self, a(self));},
'!':function(self, a){return !a(self);}
};
var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
function lex(text, parseStringsForObjects){
var dateParseLength = parseStringsForObjects ? DATE_ISOSTRING_LN : -1,
tokens = [],
token,
index = 0,
json = [],
ch,
lastCh = ':'; // can start regexp
while (index < text.length) {
ch = text.charAt(index);
if (is('"\'')) {
readString(ch);
} else if (isNumber(ch) || is('.') && isNumber(peek())) {
readNumber();
} else if (isIdent(ch)) {
readIdent();
// identifiers can only be if the preceding char was a { or ,
if (was('{,') && json[0]=='{' &&
(token=tokens[tokens.length-1])) {
token.json = token.text.indexOf('.') == -1;
}
} else if (is('(){}[].,;:')) {
tokens.push({
index:index,
text:ch,
json:(was(':[,') && is('{[')) || is('}]:,')
});
if (is('{[')) json.unshift(ch);
if (is('}]')) json.shift();
index++;
} else if (isWhitespace(ch)) {
index++;
continue;
} else {
var ch2 = ch + peek(),
fn = OPERATORS[ch],
fn2 = OPERATORS[ch2];
if (fn2) {
tokens.push({index:index, text:ch2, fn:fn2});
index += 2;
} else if (fn) {
tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')});
index += 1;
} else {
throwError("Unexpected next character ", index, index+1);
}
}
lastCh = ch;
}
return tokens;
function is(chars) {
return chars.indexOf(ch) != -1;
}
function was(chars) {
return chars.indexOf(lastCh) != -1;
}
function peek() {
return index + 1 < text.length ? text.charAt(index + 1) : false;
}
function isNumber(ch) {
return '0' <= ch && ch <= '9';
}
function isWhitespace(ch) {
return ch == ' ' || ch == '\r' || ch == '\t' ||
ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0
}
function isIdent(ch) {
return 'a' <= ch && ch <= 'z' ||
'A' <= ch && ch <= 'Z' ||
'_' == ch || ch == '$';
}
function isExpOperator(ch) {
return ch == '-' || ch == '+' || isNumber(ch);
}
function throwError(error, start, end) {
end = end || index;
throw Error("Lexer Error: " + error + " at column" +
(isDefined(start)
? "s " + start + "-" + index + " [" + text.substring(start, end) + "]"
: " " + end) +
" in expression [" + text + "].");
}
function readNumber() {
var number = "";
var start = index;
while (index < text.length) {
var ch = lowercase(text.charAt(index));
if (ch == '.' || isNumber(ch)) {
number += ch;
} else {
var peekCh = peek();
if (ch == 'e' && isExpOperator(peekCh)) {
number += ch;
} else if (isExpOperator(ch) &&
peekCh && isNumber(peekCh) &&
number.charAt(number.length - 1) == 'e') {
number += ch;
} else if (isExpOperator(ch) &&
(!peekCh || !isNumber(peekCh)) &&
number.charAt(number.length - 1) == 'e') {
throwError('Invalid exponent');
} else {
break;
}
}
index++;
}
number = 1 * number;
tokens.push({index:start, text:number, json:true,
fn:function(){return number;}});
}
function readIdent() {
var ident = "";
var start = index;
var fn;
while (index < text.length) {
var ch = text.charAt(index);
if (ch == '.' || isIdent(ch) || isNumber(ch)) {
ident += ch;
} else {
break;
}
index++;
}
fn = OPERATORS[ident];
tokens.push({
index:start,
text:ident,
json: fn,
fn:fn||extend(getterFn(ident), {
assign:function(self, value){
return setter(self, ident, value);
}
})
});
}
function readString(quote) {
var start = index;
index++;
var string = "";
var rawString = quote;
var escape = false;
while (index < text.length) {
var ch = text.charAt(index);
rawString += ch;
if (escape) {
if (ch == 'u') {
var hex = text.substring(index + 1, index + 5);
if (!hex.match(/[\da-f]{4}/i))
throwError( "Invalid unicode escape [\\u" + hex + "]");
index += 4;
string += String.fromCharCode(parseInt(hex, 16));
} else {
var rep = ESCAPE[ch];
if (rep) {
string += rep;
} else {
string += ch;
}
}
escape = false;
} else if (ch == '\\') {
escape = true;
} else if (ch == quote) {
index++;
tokens.push({index:start, text:rawString, string:string, json:true,
fn:function(){
return (string.length == dateParseLength)
? angular['String']['toDate'](string)
: string;
}});
return;
} else {
string += ch;
}
index++;
}
throwError("Unterminated quote", start);
}
}
/////////////////////////////////////////
function parser(text, json){
var ZERO = valueFn(0),
tokens = lex(text, json),
assignment = _assignment,
assignable = logicalOR,
functionCall = _functionCall,
fieldAccess = _fieldAccess,
objectIndex = _objectIndex,
filterChain = _filterChain,
functionIdent = _functionIdent,
pipeFunction = _pipeFunction;
if(json){
// The extra level of aliasing is here, just in case the lexer misses something, so that
// we prevent any accidental execution in JSON.
assignment = logicalOR;
functionCall =
fieldAccess =
objectIndex =
assignable =
filterChain =
functionIdent =
pipeFunction =
function (){ throwError("is not valid json", {text:text, index:0}); };
}
//TODO: Shouldn't all of the public methods have assertAllConsumed?
//TODO: I think these should be public as part of the parser api instead of scope.$eval().
return {
assignable: assertConsumed(assignable),
primary: assertConsumed(primary),
statements: assertConsumed(statements),
validator: assertConsumed(validator),
formatter: assertConsumed(formatter),
filter: assertConsumed(filter)
};
function assertConsumed(fn) {
return function(){
var value = fn();
if (tokens.length !== 0) {
throwError("is an unexpected token", tokens[0]);
}
return value;
};
}
///////////////////////////////////
function throwError(msg, token) {
throw Error("Syntax Error: Token '" + token.text +
"' " + msg + " at column " +
(token.index + 1) + " of the expression [" +
text + "] starting at [" + text.substring(token.index) + "].");
}
function peekToken() {
if (tokens.length === 0)
throw Error("Unexpected end of expression: " + text);
return tokens[0];
}
function peek(e1, e2, e3, e4) {
if (tokens.length > 0) {
var token = tokens[0];
var t = token.text;
if (t==e1 || t==e2 || t==e3 || t==e4 ||
(!e1 && !e2 && !e3 && !e4)) {
return token;
}
}
return false;
}
function expect(e1, e2, e3, e4){
var token = peek(e1, e2, e3, e4);
if (token) {
if (json && !token.json) {
throwError("is not valid json", token);
}
tokens.shift();
return token;
}
return false;
}
function consume(e1){
if (!expect(e1)) {
throwError("is unexpected, expecting [" + e1 + "]", peek());
}
}
function unaryFn(fn, right) {
return function(self) {
return fn(self, right);
};
}
function binaryFn(left, fn, right) {
return function(self) {
return fn(self, left, right);
};
}
function hasTokens () {
return tokens.length > 0;
}
function statements(){
var statements = [];
while(true) {
if (tokens.length > 0 && !peek('}', ')', ';', ']'))
statements.push(filterChain());
if (!expect(';')) {
// optimize for the common case where there is only one statement.
// TODO(size): maybe we should not support multiple statements?
return statements.length == 1
? statements[0]
: function (self){
var value;
for ( var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (statement)
value = statement(self);
}
return value;
};
}
}
}
function _filterChain(){
var left = expression();
var token;
while(true) {
if ((token = expect('|'))) {
left = binaryFn(left, token.fn, filter());
} else {
return left;
}
}
}
function filter(){
return pipeFunction(angularFilter);
}
function validator(){
return pipeFunction(angularValidator);
}
function formatter(){
var token = expect();
var formatter = angularFormatter[token.text];
var argFns = [];
if (!formatter) throwError('is not a valid formatter.', token);
while(true) {
if ((token = expect(':'))) {
argFns.push(expression());
} else {
return valueFn({
format:invokeFn(formatter.format),
parse:invokeFn(formatter.parse)
});
}
}
function invokeFn(fn){
return function(self, input){
var args = [input];
for ( var i = 0; i < argFns.length; i++) {
args.push(argFns[i](self));
}
return fn.apply(self, args);
};
}
}
function _pipeFunction(fnScope){
var fn = functionIdent(fnScope);
var argsFn = [];
var token;
while(true) {
if ((token = expect(':'))) {
argsFn.push(expression());
} else {
var fnInvoke = function(self, input){
var args = [input];
for ( var i = 0; i < argsFn.length; i++) {
args.push(argsFn[i](self));
}
return fn.apply(self, args);
};
return function(){
return fnInvoke;
};
}
}
}
function expression(){
return assignment();
}
function _assignment(){
var left = logicalOR();
var right;
var token;
if ((token = expect('='))) {
if (!left.assign) {
throwError("implies assignment but [" +
text.substring(0, token.index) + "] can not be assigned to", token);
}
right = logicalOR();
return function(self){
return left.assign(self, right(self));
};
} else {
return left;
}
}
function logicalOR(){
var left = logicalAND();
var token;
while(true) {
if ((token = expect('||'))) {
left = binaryFn(left, token.fn, logicalAND());
} else {
return left;
}
}
}
function logicalAND(){
var left = equality();
var token;
if ((token = expect('&&'))) {
left = binaryFn(left, token.fn, logicalAND());
}
return left;
}
function equality(){
var left = relational();
var token;
if ((token = expect('==','!='))) {
left = binaryFn(left, token.fn, equality());
}
return left;
}
function relational(){
var left = additive();
var token;
if ((token = expect('<', '>', '<=', '>='))) {
left = binaryFn(left, token.fn, relational());
}
return left;
}
function additive(){
var left = multiplicative();
var token;
while ((token = expect('+','-'))) {
left = binaryFn(left, token.fn, multiplicative());
}
return left;
}
function multiplicative(){
var left = unary();
var token;
while ((token = expect('*','/','%'))) {
left = binaryFn(left, token.fn, unary());
}
return left;
}
function unary(){
var token;
if (expect('+')) {
return primary();
} else if ((token = expect('-'))) {
return binaryFn(ZERO, token.fn, unary());
} else if ((token = expect('!'))) {
return unaryFn(token.fn, unary());
} else {
return primary();
}
}
function _functionIdent(fnScope) {
var token = expect();
var element = token.text.split('.');
var instance = fnScope;
var key;
for ( var i = 0; i < element.length; i++) {
key = element[i];
if (instance)
instance = instance[key];
}
if (!isFunction(instance)) {
throwError("should be a function", token);
}
return instance;
}
function primary() {
var primary;
if (expect('(')) {
var expression = filterChain();
consume(')');
primary = expression;
} else if (expect('[')) {
primary = arrayDeclaration();
} else if (expect('{')) {
primary = object();
} else {
var token = expect();
primary = token.fn;
if (!primary) {
throwError("not a primary expression", token);
}
}
var next;
while ((next = expect('(', '[', '.'))) {
if (next.text === '(') {
primary = functionCall(primary);
} else if (next.text === '[') {
primary = objectIndex(primary);
} else if (next.text === '.') {
primary = fieldAccess(primary);
} else {
throwError("IMPOSSIBLE");
}
}
return primary;
}
function _fieldAccess(object) {
var field = expect().text;
var getter = getterFn(field);
return extend(function (self){
return getter(object(self));
}, {
assign:function(self, value){
return setter(object(self), field, value);
}
});
}
function _objectIndex(obj) {
var indexFn = expression();
consume(']');
return extend(
function (self){
var o = obj(self);
var i = indexFn(self);
return (o) ? o[i] : undefined;
}, {
assign:function(self, value){
return obj(self)[indexFn(self)] = value;
}
});
}
function _functionCall(fn) {
var argsFn = [];
if (peekToken().text != ')') {
do {
argsFn.push(expression());
} while (expect(','));
}
consume(')');
return function (self){
var args = [];
for ( var i = 0; i < argsFn.length; i++) {
args.push(argsFn[i](self));
}
var fnPtr = fn(self) || noop;
// IE stupidity!
return fnPtr.apply
? fnPtr.apply(self, args)
: fnPtr(args[0], args[1], args[2], args[3], args[4]);
};
}
// This is used with json array declaration
function arrayDeclaration () {
var elementFns = [];
if (peekToken().text != ']') {
do {
elementFns.push(expression());
} while (expect(','));
}
consume(']');
return function (self){
var array = [];
for ( var i = 0; i < elementFns.length; i++) {
array.push(elementFns[i](self));
}
return array;
};
}
function object () {
var keyValues = [];
if (peekToken().text != '}') {
do {
var token = expect(),
key = token.string || token.text;
consume(":");
var value = expression();
keyValues.push({key:key, value:value});
} while (expect(','));
}
consume('}');
return function (self){
var object = {};
for ( var i = 0; i < keyValues.length; i++) {
var keyValue = keyValues[i];
var value = keyValue.value(self);
object[keyValue.key] = value;
}
return object;
};
}
function watchDecl () {
var anchorName = expect().text;
consume(":");
var expressionFn;
if (peekToken().text == '{') {
consume("{");
expressionFn = statements();
consume("}");
} else {
expressionFn = expression();
}
return function(self) {
return {name:anchorName, fn:expressionFn};
};
}
}
//////////////////////////////////////////////////
// Parser helper functions
//////////////////////////////////////////////////
function setter(obj, path, setValue) {
var element = path.split('.');
for (var i = 0; element.length > 1; i++) {
var key = element.shift();
var propertyObj = obj[key];
if (!propertyObj) {
propertyObj = {};
obj[key] = propertyObj;
}
obj = propertyObj;
}
obj[element.shift()] = setValue;
return setValue;
}
/**
* Return the value accesible from the object by path. Any undefined traversals are ignored
* @param {Object} obj starting object
* @param {string} path path to traverse
* @param {boolean=true} bindFnToScope
* @returns value as accesbile by path
*/
function getter(obj, path, bindFnToScope) {
if (!path) return obj;
var keys = path.split('.');
var key;
var lastInstance = obj;
var len = keys.length;
for (var i = 0; i < len; i++) {
key = keys[i];
if (obj) {
obj = (lastInstance = obj)[key];
}
if (isUndefined(obj) && key.charAt(0) == '$') {
var type = angularGlobal.typeOf(lastInstance);
type = angular[type.charAt(0).toUpperCase()+type.substring(1)];
var fn = type ? type[[key.substring(1)]] : _undefined;
if (fn) {
return obj = bind(lastInstance, fn, lastInstance);
}
}
}
if (!bindFnToScope && isFunction(obj)) {
return bind(lastInstance, obj);
}
return obj;
}
var getterFnCache = {},
compileCache = {},
JS_KEYWORDS = {};
forEach(
("abstract,boolean,break,byte,case,catch,char,class,const,continue,debugger,default," +
"delete,do,double,else,enum,export,extends,false,final,finally,float,for,function,goto," +
"if,implements,import,ininstanceof,intinterface,long,native,new,null,package,private," +
"protected,public,return,short,static,super,switch,synchronized,this,throw,throws," +
"transient,true,try,typeof,var,volatile,void,undefined,while,with").split(/,/),
function(key){ JS_KEYWORDS[key] = true;}
);
function getterFn(path) {
var fn = getterFnCache[path];
if (fn) return fn;
var code = 'var l, fn, t;\n';
forEach(path.split('.'), function(key) {
key = (JS_KEYWORDS[key]) ? '["' + key + '"]' : '.' + key;
code += 'if(!s) return s;\n' +
'l=s;\n' +
's=s' + key + ';\n' +
'if(typeof s=="function" && !(s instanceof RegExp)) s = function(){ return l' +
key + '.apply(l, arguments); };\n';
if (key.charAt(1) == '$') {
// special code for super-imposed functions
var name = key.substr(2);
code += 'if(!s) {\n' +
' t = angular.Global.typeOf(l);\n' +
' fn = (angular[t.charAt(0).toUpperCase() + t.substring(1)]||{})["' + name + '"];\n' +
' if (fn) s = function(){ return fn.apply(l, ' +
'[l].concat(Array.prototype.slice.call(arguments, 0))); };\n' +
'}\n';
}
});
code += 'return s;';
fn = Function('s', code);
fn["toString"] = function(){ return code; };
return getterFnCache[path] = fn;
}
///////////////////////////////////
// TODO(misko): Should this function be public?
function compileExpr(expr) {
return parser(expr).statements();
}
// TODO(misko): Deprecate? Remove!
// I think that compilation should be a service.
function expressionCompile(exp) {
if (isFunction(exp)) return exp;
var fn = compileCache[exp];
if (!fn) {
fn = compileCache[exp] = parser(exp).statements();
}
return fn;
}
function Route(template, defaults) {
this.template = template = template + '#';
this.defaults = defaults || {};
var urlParams = this.urlParams = {};
forEach(template.split(/\W/), function(param){
if (param && template.match(new RegExp(":" + param + "\\W"))) {
urlParams[param] = true;
}
});
}
Route.prototype = {
url: function(params) {
var self = this,
url = this.template,
encodedVal;
params = params || {};
forEach(this.urlParams, function(_, urlParam){
encodedVal = encodeUriSegment(params[urlParam] || self.defaults[urlParam] || "");
url = url.replace(new RegExp(":" + urlParam + "(\\W)"), encodedVal + "$1");
});
url = url.replace(/\/?#$/, '');
var query = [];
forEachSorted(params, function(value, key){
if (!self.urlParams[key]) {
query.push(encodeUriQuery(key) + '=' + encodeUriQuery(value));
}
});
url = url.replace(/\/*$/, '');
return url + (query.length ? '?' + query.join('&') : '');
}
};
function ResourceFactory(xhr) {
this.xhr = xhr;
}
ResourceFactory.DEFAULT_ACTIONS = {
'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'}
};
ResourceFactory.prototype = {
route: function(url, paramDefaults, actions){
var self = this;
var route = new Route(url);
actions = extend({}, ResourceFactory.DEFAULT_ACTIONS, actions);
function extractParams(data){
var ids = {};
forEach(paramDefaults || {}, function(value, key){
ids[key] = value.charAt && value.charAt(0) == '@' ? getter(data, value.substr(1)) : value;
});
return ids;
}
function Resource(value){
copy(value || {}, this);
}
forEach(actions, function(action, name){
var isPostOrPut = action.method == 'POST' || action.method == 'PUT';
Resource[name] = function (a1, a2, a3, a4) {
var params = {};
var data;
var success = noop;
var error = null;
switch(arguments.length) {
case 4:
error = a4;
success = a3;
//fallthrough
case 3:
case 2:
if (isFunction(a2)) {
if (isFunction(a1)) {
success = a1;
error = a2;
break;
}
success = a2;
error = a3;
//fallthrough
} else {
params = a1;
data = a2;
success = a3;
break;
}
case 1:
if (isFunction(a1)) success = a1;
else if (isPostOrPut) data = a1;
else params = a1;
break;
case 0: break;
default:
throw "Expected between 0-4 arguments [params, data, success, error], got " +
arguments.length + " arguments.";
}
var value = this instanceof Resource ? this : (action.isArray ? [] : new Resource(data));
self.xhr(
action.method,
route.url(extend({}, extractParams(data), action.params || {}, params)),
data,
function(status, response) {
if (response) {
if (action.isArray) {
value.length = 0;
forEach(response, function(item) {
value.push(new Resource(item));
});
} else {
copy(response, value);
}
}
(success||noop)(value);
},
error || action.verifyCache,
action.verifyCache);
return value;
};
Resource.bind = function(additionalParamDefaults){
return self.route(url, extend({}, paramDefaults, additionalParamDefaults), actions);
};
Resource.prototype['$' + name] = function(a1, a2, a3) {
var params = extractParams(this),
success = noop,
error;
switch(arguments.length) {
case 3: params = a1; success = a2; error = a3; break;
case 2:
case 1:
if (isFunction(a1)) {
success = a1;
error = a2;
} else {
params = a1;
success = a2 || noop;
}
case 0: break;
default:
throw "Expected between 1-3 arguments [params, success, error], got " +
arguments.length + " arguments.";
}
var data = isPostOrPut ? this : undefined;
Resource[name].call(this, params, data, success, error);
};
});
return Resource;
}
};
//////////////////////////////
// Browser
//////////////////////////////
var XHR = window.XMLHttpRequest || function () {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {}
throw new Error("This browser does not support XMLHttpRequest.");
};
/**
* @ngdoc service
* @name angular.service.$browser
* @requires $log
*
* @description
* Constructor for the object exposed as $browser service.
*
* This object has two goals:
*
* - hide all the global state in the browser caused by the window object
* - abstract away all the browser specific features and inconsistencies
*
* For tests we provide {@link angular.mock.service.$browser mock implementation} of the `$browser`
* service, which can be used for convenient testing of the application without the interaction with
* the real browser apis.
*/
/**
* @param {object} window The global window object.
* @param {object} document jQuery wrapped document.
* @param {object} body jQuery wrapped document.body.
* @param {function()} XHR XMLHttpRequest constructor.
* @param {object} $log console.log or an object with the same interface.
* @param {object} $sniffer $sniffer service
*/
function Browser(window, document, body, XHR, $log, $sniffer) {
var self = this,
rawDocument = document[0],
location = window.location,
history = window.history,
setTimeout = window.setTimeout,
clearTimeout = window.clearTimeout,
pendingDeferIds = {};
self.isMock = false;
//////////////////////////////////////////////////////////////
// XHR API
//////////////////////////////////////////////////////////////
var idCounter = 0;
var outstandingRequestCount = 0;
var outstandingRequestCallbacks = [];
/**
* Executes the `fn` function (supports currying) and decrements the `outstandingRequestCallbacks`
* counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
*/
function completeOutstandingRequest(fn) {
try {
fn.apply(null, sliceArgs(arguments, 1));
} finally {
outstandingRequestCount--;
if (outstandingRequestCount === 0) {
while(outstandingRequestCallbacks.length) {
try {
outstandingRequestCallbacks.pop()();
} catch (e) {
$log.error(e);
}
}
}
}
}
/**
* @workInProgress
* @ngdoc method
* @name angular.service.$browser#xhr
* @methodOf angular.service.$browser
*
* @param {string} method Requested method (get|post|put|delete|head|json)
* @param {string} url Requested url
* @param {?string} post Post data to send (null if nothing to post)
* @param {function(number, string)} callback Function that will be called on response
* @param {object=} header additional HTTP headers to send with XHR.
* Standard headers are:
* <ul>
* <li><tt>Content-Type</tt>: <tt>application/x-www-form-urlencoded</tt></li>
* <li><tt>Accept</tt>: <tt>application/json, text/plain, */*</tt></li>
* <li><tt>X-Requested-With</tt>: <tt>XMLHttpRequest</tt></li>
* </ul>
*
* @description
* Send ajax request
*/
self.xhr = function(method, url, post, callback, headers) {
outstandingRequestCount ++;
if (lowercase(method) == 'json') {
var callbackId = ("angular_" + Math.random() + '_' + (idCounter++)).replace(/\d\./, '');
window[callbackId] = function(data) {
window[callbackId].data = data;
};
var script = self.addJs(url.replace('JSON_CALLBACK', callbackId), null, function() {
if (window[callbackId].data) {
completeOutstandingRequest(callback, 200, window[callbackId].data);
} else {
completeOutstandingRequest(callback);
}
delete window[callbackId];
body[0].removeChild(script);
});
} else {
var xhr = new XHR();
xhr.open(method, url, true);
forEach(headers, function(value, key) {
if (value) xhr.setRequestHeader(key, value);
});
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// normalize IE bug (http://bugs.jquery.com/ticket/1450)
var status = xhr.status == 1223 ? 204 : xhr.status;
completeOutstandingRequest(callback, status, xhr.responseText);
}
};
xhr.send(post || '');
}
};
/**
* @private
* Note: this method is used only by scenario runner
* TODO(vojta): prefix this method with $$ ?
* @param {function()} callback Function that will be called when no outstanding request
*/
self.notifyWhenNoOutstandingRequests = function(callback) {
// force browser to execute all pollFns - this is needed so that cookies and other pollers fire
// at some deterministic time in respect to the test runner's actions. Leaving things up to the
// regular poller would result in flaky tests.
forEach(pollFns, function(pollFn){ pollFn(); });
if (outstandingRequestCount === 0) {
callback();
} else {
outstandingRequestCallbacks.push(callback);
}
};
//////////////////////////////////////////////////////////////
// Poll Watcher API
//////////////////////////////////////////////////////////////
var pollFns = [],
pollTimeout;
/**
* @workInProgress
* @ngdoc method
* @name angular.service.$browser#addPollFn
* @methodOf angular.service.$browser
*
* @param {function()} fn Poll function to add
*
* @description
* Adds a function to the list of functions that poller periodically executes,
* and starts polling if not started yet.
*
* @returns {function()} the added function
*/
self.addPollFn = function(fn) {
if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
pollFns.push(fn);
return fn;
};
/**
* @param {number} interval How often should browser call poll functions (ms)
* @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
*
* @description
* Configures the poller to run in the specified intervals, using the specified
* setTimeout fn and kicks it off.
*/
function startPoller(interval, setTimeout) {
(function check() {
forEach(pollFns, function(pollFn){ pollFn(); });
pollTimeout = setTimeout(check, interval);
})();
}
//////////////////////////////////////////////////////////////
// URL API
//////////////////////////////////////////////////////////////
var lastBrowserUrl = location.href;
/**
* @workInProgress
* @ngdoc method
* @name angular.service.$browser#url
* @methodOf angular.service.$browser
*
* @description
* GETTER:
* Without any argument, this method just returns current value of location.href.
*
* SETTER:
* With at least one argument, this method sets url to new value.
* If html5 history api supported, pushState/replaceState is used, otherwise
* location.href/location.replace is used.
* Returns its own instance to allow chaining
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link angular.service.$location $location service} to change url.
*
* @param {string} url New url (when used as setter)
* @param {boolean=} replace Should new url replace current history record ?
*/
self.url = function(url, replace) {
// setter
if (url) {
lastBrowserUrl = url;
if ($sniffer.history) {
if (replace) history.replaceState(null, '', url);
else history.pushState(null, '', url);
} else {
if (replace) location.replace(url);
else location.href = url;
}
return self;
// getter
} else {
return location.href;
}
};
var urlChangeListeners = [],
urlChangeInit = false;
function fireUrlChange() {
if (lastBrowserUrl == self.url()) return;
lastBrowserUrl = self.url();
forEach(urlChangeListeners, function(listener) {
listener(self.url());
});
}
/**
* @workInProgress
* @ngdoc method
* @name angular.service.$browser#onUrlChange
* @methodOf angular.service.$browser
* @TODO(vojta): refactor to use node's syntax for events
*
* @description
* Register callback function that will be called, when url changes.
*
* It's only called when the url is changed by outside of angular:
* - user types different url into address bar
* - user clicks on history (forward/back) button
* - user clicks on a link
*
* It's not called when url is changed by $browser.url() method
*
* The listener gets called with new url as parameter.
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link angular.service.$location $location service} to monitor url changes in angular apps.
*
* @param {function(string)} listener Listener function to be called when url changes.
* @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
*/
self.onUrlChange = function(callback) {
if (!urlChangeInit) {
// We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
// don't fire popstate when user change the address bar and don't fire hashchange when url
// changed by push/replaceState
// html5 history api - popstate event
if ($sniffer.history) jqLite(window).bind('popstate', fireUrlChange);
// hashchange event
if ($sniffer.hashchange) jqLite(window).bind('hashchange', fireUrlChange);
// polling
else self.addPollFn(fireUrlChange);
urlChangeInit = true;
}
urlChangeListeners.push(callback);
return callback;
};
//////////////////////////////////////////////////////////////
// Cookies API
//////////////////////////////////////////////////////////////
var lastCookies = {};
var lastCookieString = '';
/**
* @workInProgress
* @ngdoc method
* @name angular.service.$browser#cookies
* @methodOf angular.service.$browser
*
* @param {string=} name Cookie name
* @param {string=} value Cokkie value
*
* @description
* The cookies method provides a 'private' low level access to browser cookies.
* It is not meant to be used directly, use the $cookie service instead.
*
* The return values vary depending on the arguments that the method was called with as follows:
* <ul>
* <li>cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it</li>
* <li>cookies(name, value) -> set name to value, if value is undefined delete the cookie</li>
* <li>cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)</li>
* </ul>
*
* @returns {Object} Hash of all cookies (if called without any parameter)
*/
self.cookies = function (name, value) {
var cookieLength, cookieArray, cookie, i, keyValue, index;
if (name) {
if (value === undefined) {
rawDocument.cookie = escape(name) + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
} else {
if (isString(value)) {
rawDocument.cookie = escape(name) + '=' + escape(value);
cookieLength = name.length + value.length + 1;
if (cookieLength > 4096) {
$log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+
cookieLength + " > 4096 bytes)!");
}
if (lastCookies.length > 20) {
$log.warn("Cookie '"+ name +"' possibly not set or overflowed because too many cookies " +
"were already set (" + lastCookies.length + " > 20 )");
}
}
}
} else {
if (rawDocument.cookie !== lastCookieString) {
lastCookieString = rawDocument.cookie;
cookieArray = lastCookieString.split("; ");
lastCookies = {};
for (i = 0; i < cookieArray.length; i++) {
cookie = cookieArray[i];
index = cookie.indexOf('=');
if (index > 0) { //ignore nameless cookies
lastCookies[unescape(cookie.substring(0, index))] = unescape(cookie.substring(index + 1));
}
}
}
return lastCookies;
}
};
/**
* @workInProgress
* @ngdoc method
* @name angular.service.$browser#defer
* @methodOf angular.service.$browser
* @param {function()} fn A function, who's execution should be defered.
* @param {number=} [delay=0] of milliseconds to defer the function execution.
* @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
*
* @description
* Executes a fn asynchroniously via `setTimeout(fn, delay)`.
*
* Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
* `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
* via `$browser.defer.flush()`.
*
*/
self.defer = function(fn, delay) {
var timeoutId;
outstandingRequestCount++;
timeoutId = setTimeout(function() {
delete pendingDeferIds[timeoutId];
completeOutstandingRequest(fn);
}, delay || 0);
pendingDeferIds[timeoutId] = true;
return timeoutId;
};
/**
* THIS DOC IS NOT VISIBLE because ngdocs can't process docs for foo#method.method
*
* @name angular.service.$browser#defer.cancel
* @methodOf angular.service.$browser.defer
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfuly canceled.
*
* @description
* Cancels a defered task identified with `deferId`.
*/
self.defer.cancel = function(deferId) {
if (pendingDeferIds[deferId]) {
delete pendingDeferIds[deferId];
clearTimeout(deferId);
completeOutstandingRequest(noop);
return true;
}
};
//////////////////////////////////////////////////////////////
// Misc API
//////////////////////////////////////////////////////////////
var hoverListener = noop;
/**
* @workInProgress
* @ngdoc method
* @name angular.service.$browser#hover
* @methodOf angular.service.$browser
*
* @description
* Set hover listener.
*
* @param {function(Object, boolean)} listener Function that will be called when a hover event
* occurs.
*/
self.hover = function(listener) { hoverListener = listener; };
/**
* @workInProgress
* @ngdoc method
* @name angular.service.$browser#bind
* @methodOf angular.service.$browser
*
* @description
* Register hover function to real browser
*/
self.bind = function() {
document.bind("mouseover", function(event){
hoverListener(jqLite(msie ? event.srcElement : event.target), true);
return true;
});
document.bind("mouseleave mouseout click dblclick keypress keyup", function(event){
hoverListener(jqLite(event.target), false);
return true;
});
};
/**
* @workInProgress
* @ngdoc method
* @name angular.service.$browser#addCss
* @methodOf angular.service.$browser
*
* @param {string} url Url to css file
* @description
* Adds a stylesheet tag to the head.
*/
self.addCss = function(url) {
var link = jqLite(rawDocument.createElement('link'));
link.attr('rel', 'stylesheet');
link.attr('type', 'text/css');
link.attr('href', url);
body.append(link);
};
/**
* @workInProgress
* @ngdoc method
* @name angular.service.$browser#addJs
* @methodOf angular.service.$browser
*
* @param {string} url Url to js file
* @param {string=} domId Optional id for the script tag
*
* @description
* Adds a script tag to the head.
*/
self.addJs = function(url, domId, done) {
// we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
// - fetches local scripts via XHR and evals them
// - adds and immediately removes script elements from the document
//
// We need addJs to be able to add angular-ie-compat.js which is very special and must remain
// part of the DOM so that the embedded images can reference it. jQuery's append implementation
// (v1.4.2) fubars it.
var script = rawDocument.createElement('script');
script.type = 'text/javascript';
script.src = url;
if (domId) script.id = domId;
if (msie) {
script.onreadystatechange = function() {
/loaded|complete/.test(script.readyState) && done && done();
};
} else {
if (done) script.onload = script.onerror = done;
}
body[0].appendChild(script);
return script;
};
/**
* Returns current <base href>
* (always relative - without domain)
*
* @returns {string=}
*/
self.baseHref = function() {
var href = document.find('base').attr('href');
return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : href;
};
}
/*
* HTML Parser By Misko Hevery (misko@hevery.com)
* based on: HTML Parser By John Resig (ejohn.org)
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*
* // Use like so:
* htmlParser(htmlString, {
* start: function(tag, attrs, unary) {},
* end: function(tag) {},
* chars: function(text) {},
* comment: function(text) {}
* });
*
*/
// Regular Expressions for parsing tags and attributes
var START_TAG_REGEXP = /^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/,
END_TAG_REGEXP = /^<\s*\/\s*([\w:-]+)[^>]*>/,
ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g,
BEGIN_TAG_REGEXP = /^</,
BEGING_END_TAGE_REGEXP = /^<\s*\//,
COMMENT_REGEXP = /<!--(.*?)-->/g,
CDATA_REGEXP = /<!\[CDATA\[(.*?)]]>/g,
URI_REGEXP = /^((ftp|https?):\/\/|mailto:|#)/,
NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g; // Match everything outside of normal chars and " (quote character)
// Empty Elements - HTML 4.01
var emptyElements = makeMap("area,br,col,hr,img");
// Block Elements - HTML 4.01
var blockElements = makeMap("address,blockquote,center,dd,del,dir,div,dl,dt,"+
"hr,ins,li,map,menu,ol,p,pre,script,table,tbody,td,tfoot,th,thead,tr,ul");
// Inline Elements - HTML 4.01
var inlineElements = makeMap("a,abbr,acronym,b,bdo,big,br,cite,code,del,dfn,em,font,i,img,"+
"ins,kbd,label,map,q,s,samp,small,span,strike,strong,sub,sup,tt,u,var");
// Elements that you can, intentionally, leave open
// (and which close themselves)
var closeSelfElements = makeMap("colgroup,dd,dt,li,p,td,tfoot,th,thead,tr");
// Special Elements (can contain anything)
var specialElements = makeMap("script,style");
var validElements = extend({}, emptyElements, blockElements, inlineElements, closeSelfElements);
//Attributes that have href and hence need to be sanitized
var uriAttrs = makeMap("background,href,longdesc,src,usemap");
var validAttrs = extend({}, uriAttrs, makeMap(
'abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+
'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,'+
'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,'+
'scope,scrolling,shape,span,start,summary,target,title,type,'+
'valign,value,vspace,width'));
/**
* @example
* htmlParser(htmlString, {
* start: function(tag, attrs, unary) {},
* end: function(tag) {},
* chars: function(text) {},
* comment: function(text) {}
* });
*
* @param {string} html string
* @param {object} handler
*/
function htmlParser( html, handler ) {
var index, chars, match, stack = [], last = html;
stack.last = function(){ return stack[ stack.length - 1 ]; };
while ( html ) {
chars = true;
// Make sure we're not in a script or style element
if ( !stack.last() || !specialElements[ stack.last() ] ) {
// Comment
if ( html.indexOf("<!--") === 0 ) {
index = html.indexOf("-->");
if ( index >= 0 ) {
if (handler.comment) handler.comment( html.substring( 4, index ) );
html = html.substring( index + 3 );
chars = false;
}
// end tag
} else if ( BEGING_END_TAGE_REGEXP.test(html) ) {
match = html.match( END_TAG_REGEXP );
if ( match ) {
html = html.substring( match[0].length );
match[0].replace( END_TAG_REGEXP, parseEndTag );
chars = false;
}
// start tag
} else if ( BEGIN_TAG_REGEXP.test(html) ) {
match = html.match( START_TAG_REGEXP );
if ( match ) {
html = html.substring( match[0].length );
match[0].replace( START_TAG_REGEXP, parseStartTag );
chars = false;
}
}
if ( chars ) {
index = html.indexOf("<");
var text = index < 0 ? html : html.substring( 0, index );
html = index < 0 ? "" : html.substring( index );
if (handler.chars) handler.chars( decodeEntities(text) );
}
} else {
html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'), function(all, text){
text = text.
replace(COMMENT_REGEXP, "$1").
replace(CDATA_REGEXP, "$1");
if (handler.chars) handler.chars( decodeEntities(text) );
return "";
});
parseEndTag( "", stack.last() );
}
if ( html == last ) {
throw "Parse Error: " + html;
}
last = html;
}
// Clean up any remaining tags
parseEndTag();
function parseStartTag( tag, tagName, rest, unary ) {
tagName = lowercase(tagName);
if ( blockElements[ tagName ] ) {
while ( stack.last() && inlineElements[ stack.last() ] ) {
parseEndTag( "", stack.last() );
}
}
if ( closeSelfElements[ tagName ] && stack.last() == tagName ) {
parseEndTag( "", tagName );
}
unary = emptyElements[ tagName ] || !!unary;
if ( !unary )
stack.push( tagName );
var attrs = {};
rest.replace(ATTR_REGEXP, function(match, name, doubleQuotedValue, singleQoutedValue, unqoutedValue) {
var value = doubleQuotedValue
|| singleQoutedValue
|| unqoutedValue
|| '';
attrs[name] = decodeEntities(value);
});
if (handler.start) handler.start( tagName, attrs, unary );
}
function parseEndTag( tag, tagName ) {
var pos = 0, i;
tagName = lowercase(tagName);
if ( tagName )
// Find the closest opened tag of the same type
for ( pos = stack.length - 1; pos >= 0; pos-- )
if ( stack[ pos ] == tagName )
break;
if ( pos >= 0 ) {
// Close all the open elements, up the stack
for ( i = stack.length - 1; i >= pos; i-- )
if (handler.end) handler.end( stack[ i ] );
// Remove the open elements from the stack
stack.length = pos;
}
}
}
/**
* decodes all entities into regular string
* @param value
* @returns {string} A string with decoded entities.
*/
var hiddenPre=document.createElement("pre");
function decodeEntities(value) {
hiddenPre.innerHTML=value.replace(/</g,"<");
return hiddenPre.innerText || hiddenPre.textContent || '';
}
/**
* Escapes all potentially dangerous characters, so that the
* resulting string can be safely inserted into attribute or
* element text.
* @param value
* @returns escaped text
*/
function encodeEntities(value) {
return value.
replace(/&/g, '&').
replace(NON_ALPHANUMERIC_REGEXP, function(value){
return '&#' + value.charCodeAt(0) + ';';
}).
replace(/</g, '<').
replace(/>/g, '>');
}
/**
* create an HTML/XML writer which writes to buffer
* @param {Array} buf use buf.jain('') to get out sanitized html string
* @returns {object} in the form of {
* start: function(tag, attrs, unary) {},
* end: function(tag) {},
* chars: function(text) {},
* comment: function(text) {}
* }
*/
function htmlSanitizeWriter(buf){
var ignore = false;
var out = bind(buf, buf.push);
return {
start: function(tag, attrs, unary){
tag = lowercase(tag);
if (!ignore && specialElements[tag]) {
ignore = tag;
}
if (!ignore && validElements[tag] == true) {
out('<');
out(tag);
forEach(attrs, function(value, key){
var lkey=lowercase(key);
if (validAttrs[lkey]==true && (uriAttrs[lkey]!==true || value.match(URI_REGEXP))) {
out(' ');
out(key);
out('="');
out(encodeEntities(value));
out('"');
}
});
out(unary ? '/>' : '>');
}
},
end: function(tag){
tag = lowercase(tag);
if (!ignore && validElements[tag] == true) {
out('</');
out(tag);
out('>');
}
if (tag == ignore) {
ignore = false;
}
},
chars: function(chars){
if (!ignore) {
out(encodeEntities(chars));
}
}
};
}
//////////////////////////////////
//JQLite
//////////////////////////////////
/**
* @ngdoc function
* @name angular.element
* @function
*
* @description
* Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
* `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if
* jQuery is available, or a function that wraps the element or string in Angular's jQuery lite
* implementation (commonly referred to as jqLite).
*
* Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded`
* event fired.
*
* jqLite is a tiny, API-compatible subset of jQuery that allows
* Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality
* within a very small footprint, so only a subset of the jQuery API - methods, arguments and
* invocation styles - are supported.
*
* Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never
* raw DOM references.
*
* ## Angular's jQuery lite provides the following methods:
*
* - [addClass()](http://api.jquery.com/addClass/)
* - [after()](http://api.jquery.com/after/)
* - [append()](http://api.jquery.com/append/)
* - [attr()](http://api.jquery.com/attr/)
* - [bind()](http://api.jquery.com/bind/)
* - [children()](http://api.jquery.com/children/)
* - [clone()](http://api.jquery.com/clone/)
* - [css()](http://api.jquery.com/css/)
* - [data()](http://api.jquery.com/data/)
* - [eq()](http://api.jquery.com/eq/)
* - [hasClass()](http://api.jquery.com/hasClass/)
* - [parent()](http://api.jquery.com/parent/)
* - [prop()](http://api.jquery.com/prop/)
* - [remove()](http://api.jquery.com/remove/)
* - [removeAttr()](http://api.jquery.com/removeAttr/)
* - [removeClass()](http://api.jquery.com/removeClass/)
* - [removeData()](http://api.jquery.com/removeData/)
* - [replaceWith()](http://api.jquery.com/replaceWith/)
* - [text()](http://api.jquery.com/text/)
* - [trigger()](http://api.jquery.com/trigger/)
* - [unbind()](http://api.jquery.com/unbind/)
*
* ## In addtion to the above, Angular privides an additional method to both jQuery and jQuery lite:
*
* - `scope()` - retrieves the current Angular scope of the element.
*
* @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
* @returns {Object} jQuery object.
*/
var jqCache = {},
jqName = 'ng-' + new Date().getTime(),
jqId = 1,
addEventListenerFn = (window.document.addEventListener
? function(element, type, fn) {element.addEventListener(type, fn, false);}
: function(element, type, fn) {element.attachEvent('on' + type, fn);}),
removeEventListenerFn = (window.document.removeEventListener
? function(element, type, fn) {element.removeEventListener(type, fn, false); }
: function(element, type, fn) {element.detachEvent('on' + type, fn); });
function jqNextId() { return (jqId++); }
function getStyle(element) {
var current = {}, style = element[0].style, value, name, i;
if (typeof style.length == 'number') {
for(i = 0; i < style.length; i++) {
name = style[i];
current[name] = style[name];
}
} else {
for (name in style) {
value = style[name];
if (1*name != name && name != 'cssText' && value && typeof value == 'string' && value !='false')
current[name] = value;
}
}
return current;
}
/**
* Converts dash-separated names to camelCase. Useful for dealing with css properties.
*/
function camelCase(name) {
return name.replace(/\-(\w)/g, function(all, letter, offset){
return (offset == 0 && letter == 'w') ? 'w' : letter.toUpperCase();
});
}
/////////////////////////////////////////////
function jqLiteWrap(element) {
if (isString(element) && element.charAt(0) != '<') {
throw new Error('selectors not implemented');
}
return new JQLite(element);
}
function JQLite(element) {
if (element instanceof JQLite) {
return element;
} else if (isString(element)) {
var div = document.createElement('div');
// Read about the NoScope elements here:
// http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
div.innerHTML = '<div> </div>' + element; // IE insanity to make NoScope elements work!
div.removeChild(div.firstChild); // remove the superfluous div
JQLiteAddNodes(this, div.childNodes);
this.remove(); // detach the elements from the temporary DOM div.
} else {
JQLiteAddNodes(this, element);
}
}
function JQLiteClone(element) {
return element.cloneNode(true);
}
function JQLiteDealoc(element){
JQLiteRemoveData(element);
for ( var i = 0, children = element.childNodes || []; i < children.length; i++) {
JQLiteDealoc(children[i]);
}
}
function JQLiteRemoveData(element) {
var cacheId = element[jqName],
cache = jqCache[cacheId];
if (cache) {
forEach(cache.bind || {}, function(fn, type){
removeEventListenerFn(element, type, fn);
});
delete jqCache[cacheId];
element[jqName] = undefined; // ie does not allow deletion of attributes on elements.
}
}
function JQLiteData(element, key, value) {
var cacheId = element[jqName],
cache = jqCache[cacheId || -1];
if (isDefined(value)) {
if (!cache) {
element[jqName] = cacheId = jqNextId();
cache = jqCache[cacheId] = {};
}
cache[key] = value;
} else {
return cache ? cache[key] : null;
}
}
function JQLiteHasClass(element, selector, _) {
// the argument '_' is important, since it makes the function have 3 arguments, which
// is needed for delegate function to realize the this is a getter.
var className = " " + selector + " ";
return ((" " + element.className + " ").replace(/[\n\t]/g, " ").indexOf( className ) > -1);
}
function JQLiteRemoveClass(element, selector) {
if (selector) {
forEach(selector.split(' '), function(cssClass) {
element.className = trim(
(" " + element.className + " ")
.replace(/[\n\t]/g, " ")
.replace(" " + trim(cssClass) + " ", " ")
);
});
}
}
function JQLiteAddClass(element, selector) {
if (selector) {
forEach(selector.split(' '), function(cssClass) {
if (!JQLiteHasClass(element, cssClass)) {
element.className = trim(element.className + ' ' + trim(cssClass));
}
});
}
}
function JQLiteAddNodes(root, elements) {
if (elements) {
elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements))
? elements
: [ elements ];
for(var i=0; i < elements.length; i++) {
root.push(elements[i]);
}
}
}
//////////////////////////////////////////
// Functions which are declared directly.
//////////////////////////////////////////
var JQLitePrototype = JQLite.prototype = {
ready: function(fn) {
var fired = false;
function trigger() {
if (fired) return;
fired = true;
fn();
}
this.bind('DOMContentLoaded', trigger); // works for modern browsers and IE9
// we can not use jqLite since we are not done loading and jQuery could be loaded later.
jqLiteWrap(window).bind('load', trigger); // fallback to window.onload for others
},
toString: function() {
var value = [];
forEach(this, function(e){ value.push('' + e);});
return '[' + value.join(', ') + ']';
},
eq: function(index) {
return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
},
length: 0,
push: push,
sort: [].sort,
splice: [].splice
};
//////////////////////////////////////////
// Functions iterating getter/setters.
// these functions return self on setter and
// value on get.
//////////////////////////////////////////
var SPECIAL_ATTR = makeMap("multiple,selected,checked,disabled,readonly");
forEach({
data: JQLiteData,
scope: function(element) {
var scope;
while (element && !(scope = jqLite(element).data($$scope))) {
element = element.parentNode;
}
return scope;
},
removeAttr: function(element,name) {
element.removeAttribute(name);
},
hasClass: JQLiteHasClass,
css: function(element, name, value) {
name = camelCase(name);
if (isDefined(value)) {
element.style[name] = value;
} else {
var val;
if (msie <= 8) {
// this is some IE specific weirdness that jQuery 1.6.4 does not sure why
val = element.currentStyle && element.currentStyle[name];
if (val === '') val = 'auto';
}
val = val || element.style[name];
if (msie <= 8) {
// jquery weirdness :-/
val = (val === '') ? undefined : val;
}
return val;
}
},
attr: function(element, name, value){
if (SPECIAL_ATTR[name]) {
if (isDefined(value)) {
if (!!value) {
element[name] = true;
element.setAttribute(name, name);
} else {
element[name] = false;
element.removeAttribute(name);
}
} else {
return (element[name] || element.getAttribute(name)) ? name : undefined;
}
} else if (isDefined(value)) {
element.setAttribute(name, value);
} else if (element.getAttribute) {
// the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
// some elements (e.g. Document) don't have get attribute, so return undefined
var ret = element.getAttribute(name, 2);
// normalize non-existing attributes to undefined (as jQuery)
return ret === null ? undefined : ret;
}
},
prop: function(element, name, value) {
if (isDefined(value)) {
element[name] = value;
} else {
return element[name];
}
},
text: extend((msie < 9)
? function(element, value) {
// NodeType == 3 is text node
if (element.nodeType == 3) {
if (isUndefined(value))
return element.nodeValue;
element.nodeValue = value;
} else {
if (isUndefined(value))
return element.innerText;
element.innerText = value;
}
}
: function(element, value) {
if (isUndefined(value)) {
return element.textContent;
}
element.textContent = value;
}, {$dv:''}),
val: function(element, value) {
if (isUndefined(value)) {
return element.value;
}
element.value = value;
},
html: function(element, value) {
if (isUndefined(value)) {
return element.innerHTML;
}
for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
JQLiteDealoc(childNodes[i]);
}
element.innerHTML = value;
}
}, function(fn, name){
/**
* Properties: writes return selection, reads return first value
*/
JQLite.prototype[name] = function(arg1, arg2) {
var i, key;
if ((fn.length == 2 ? arg1 : arg2) === undefined) {
if (isObject(arg1)) {
// we are a write, but the object properties are the key/values
for(i=0; i < this.length; i++) {
for (key in arg1) {
fn(this[i], key, arg1[key]);
}
}
// return self for chaining
return this;
} else {
// we are a read, so read the first child.
if (this.length)
return fn(this[0], arg1, arg2);
}
} else {
// we are a write, so apply to all children
for(i=0; i < this.length; i++) {
fn(this[i], arg1, arg2);
}
// return self for chaining
return this;
}
return fn.$dv;
};
});
//////////////////////////////////////////
// Functions iterating traversal.
// These functions chain results into a single
// selector.
//////////////////////////////////////////
forEach({
removeData: JQLiteRemoveData,
dealoc: JQLiteDealoc,
bind: function(element, type, fn){
var bind = JQLiteData(element, 'bind');
if (!bind) JQLiteData(element, 'bind', bind = {});
forEach(type.split(' '), function(type){
var eventHandler = bind[type];
if (!eventHandler) {
bind[type] = eventHandler = function(event) {
if (!event.preventDefault) {
event.preventDefault = function(){
event.returnValue = false; //ie
};
}
if (!event.stopPropagation) {
event.stopPropagation = function() {
event.cancelBubble = true; //ie
};
}
if (!event.target) {
event.target = event.srcElement || document;
}
if (isUndefined(event.defaultPrevented)) {
var prevent = event.preventDefault;
event.preventDefault = function() {
event.defaultPrevented = true;
prevent.call(event);
};
event.defaultPrevented = false;
}
event.isDefaultPrevented = function() {
return event.defaultPrevented;
};
forEach(eventHandler.fns, function(fn){
fn.call(element, event);
});
};
eventHandler.fns = [];
addEventListenerFn(element, type, eventHandler);
}
eventHandler.fns.push(fn);
});
},
unbind: function(element, type, fn) {
var bind = JQLiteData(element, 'bind');
if (!bind) return; //no listeners registered
if (isUndefined(type)) {
forEach(bind, function(eventHandler, type) {
removeEventListenerFn(element, type, eventHandler);
delete bind[type];
});
} else {
if (isUndefined(fn)) {
removeEventListenerFn(element, type, bind[type]);
delete bind[type];
} else {
angularArray.remove(bind[type].fns, fn);
}
}
},
replaceWith: function(element, replaceNode) {
var index, parent = element.parentNode;
JQLiteDealoc(element);
forEach(new JQLite(replaceNode), function(node){
if (index) {
parent.insertBefore(node, index.nextSibling);
} else {
parent.replaceChild(node, element);
}
index = node;
});
},
children: function(element) {
var children = [];
forEach(element.childNodes, function(element){
if (element.nodeName != '#text')
children.push(element);
});
return children;
},
append: function(element, node) {
forEach(new JQLite(node), function(child){
if (element.nodeType === 1)
element.appendChild(child);
});
},
prepend: function(element, node) {
if (element.nodeType === 1) {
var index = element.firstChild;
forEach(new JQLite(node), function(child){
if (index) {
element.insertBefore(child, index);
} else {
element.appendChild(child);
index = child;
}
});
}
},
remove: function(element) {
JQLiteDealoc(element);
var parent = element.parentNode;
if (parent) parent.removeChild(element);
},
after: function(element, newElement) {
var index = element, parent = element.parentNode;
forEach(new JQLite(newElement), function(node){
parent.insertBefore(node, index.nextSibling);
index = node;
});
},
addClass: JQLiteAddClass,
removeClass: JQLiteRemoveClass,
toggleClass: function(element, selector, condition) {
if (isUndefined(condition)) {
condition = !JQLiteHasClass(element, selector);
}
(condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector);
},
parent: function(element) {
var parent = element.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
next: function(element) {
return element.nextSibling;
},
find: function(element, selector) {
return element.getElementsByTagName(selector);
},
clone: JQLiteClone
}, function(fn, name){
/**
* chaining functions
*/
JQLite.prototype[name] = function(arg1, arg2) {
var value;
for(var i=0; i < this.length; i++) {
if (value == undefined) {
value = fn(this[i], arg1, arg2);
if (value !== undefined) {
// any function which returns a value needs to be wrapped
value = jqLite(value);
}
} else {
JQLiteAddNodes(value, fn(this[i], arg1, arg2));
}
}
return value == undefined ? this : value;
};
});
var angularGlobal = {
'typeOf':function(obj){
if (obj === null) return $null;
var type = typeof obj;
if (type == $object) {
if (obj instanceof Array) return $array;
if (isDate(obj)) return $date;
if (obj.nodeType == 1) return 'element';
}
return type;
}
};
/**
* @ngdoc overview
* @name angular.Object
* @function
*
* @description
* A namespace for utility functions used to work with JavaScript objects. These functions are
* exposed in two ways:
*
* * __Angular expressions:__ Functions are bound to all objects and augment the Object type.
* The names of these methods are prefixed with the '$' character in order to minimize naming
* collisions. To call a method, invoke the function without the first argument, for example,
* `myObject.$foo(param2)`.
*
* * __JavaScript code:__ Functions don't augment the Object type and must be invoked as functions
* of `angular.Object` as `angular.Object.foo(myObject, param2)`.
*
* * {@link angular.Object.copy angular.Object.copy()} - Creates a deep copy of the source
* parameter.
* * {@link angular.Object.equals angular.Object.equals()} - Determines if two objects or values
* are equivalent.
* * {@link angular.Object.size angular.Object.size()} - Determines the number of elements in
* strings, arrays, and objects.
*/
var angularCollection = {
'copy': copy,
'size': size,
'equals': equals
};
var angularObject = {
'extend': extend
};
/**
* @ngdoc overview
* @name angular.Array
*
* @description
* A namespace for utility functions for the manipulation of JavaScript Array objects.
*
* These functions are exposed in two ways:
*
* * __Angular expressions:__ Functions are bound to the Array objects and augment the Array type
* as array methods. The names of these methods are prefixed with the `$` character to minimize
* naming collisions. To call a method, invoke myArrayObject.$foo(params).
*
* Because Array type is a subtype of the Object type, all angular.Object functions augment
* the Array type in Angular expressions as well.
*
* * __JavaScript code:__ Functions do nor augment the Array type and must be invoked as functions
* of `angular.Array` as `angular.Array.foo(myArrayObject, params)`.
*
* The following APIs are built in to the Angular Array object:
*
* * {@link angular.Array.add angular.Array.add()} - Optionally adds a new element to an array.
* * {@link angular.Array.count angular.Array.count()} - Determines the number of elements in an
* array.
* * {@link angular.Array.filter angular.Array.filter()} - Returns the subset of elements specified
* in the filter as a new array.
* * {@link angular.Array.indexOf angular.Array.indexOf()} - Determines the index of an array
* value.
* * {@link angular.Array.limitTo angular.Array.limitTo()} - Creates a sub-array of an existing
* array.
* * {@link angular.Array.orderBy angular.Array.orderBy()} - Orders array elements.
* * {@link angular.Array.remove angular.Array.remove()} - Removes array elements.
* * {@link angular.Array.sum angular.Array.sum()} - Sums the numbers in an array.
*/
var angularArray = {
/**
* @ngdoc function
* @name angular.Array.indexOf
* @function
*
* @description
* Determines the index of a `value` in an `array`.
*
* Note: This function is used to augment the `Array` type in Angular expressions. See
* {@link angular.Array} for more information about Angular arrays.
*
* @param {Array} array Array to search.
* @param {*} value Value to search for.
* @returns {number} The position of the element in `array`. The position is 0-based.
* If the value cannot be found, `-1` is returned.
*
* @example
<doc:example>
<doc:source>
<div ng:init="books = ['Moby Dick', 'Great Gatsby', 'Romeo and Juliet']"></div>
<input name='bookName' value='Romeo and Juliet'> <br>
Index of '{{bookName}}' in the list {{books}} is <em>{{books.$indexOf(bookName)}}</em>.
</doc:source>
<doc:scenario>
it('should correctly calculate the initial index', function() {
expect(binding('books.$indexOf(bookName)')).toBe('2');
});
it('should recalculate', function() {
input('bookName').enter('foo');
expect(binding('books.$indexOf(bookName)')).toBe('-1');
input('bookName').enter('Moby Dick');
expect(binding('books.$indexOf(bookName)')).toBe('0');
});
</doc:scenario>
</doc:example>
*/
'indexOf': indexOf,
/**
* @ngdoc function
* @name angular.Array.sum
* @function
*
* @description
* The `sum` function calculates the sum of all numbers in an `array`. If an `expression` is
* supplied, `sum` evaluates each element in the `array` with the expression and then returns
* the sum of the calculated values.
*
* Note: This function is used to augment the `Array` type in Angular expressions. See
* {@link angular.Array} for more info about Angular arrays.
*
* @param {Array} array The source array.
* @param {(string|function())=} expression Angular expression or a function to be evaluated for
* each element in `array`. The array element becomes the `this` during the evaluation.
* @returns {number} Sum of items in the array.
*
* @example
<doc:example>
<doc:source>
<table ng:init="invoice= {items:[{qty:10, description:'gadget', cost:9.95}]}">
<tr><th>Qty</th><th>Description</th><th>Cost</th><th>Total</th><th></th></tr>
<tr ng:repeat="item in invoice.items">
<td><input name="item.qty" value="1" size="4" ng:required ng:validate="integer"></td>
<td><input name="item.description"></td>
<td><input name="item.cost" value="0.00" ng:required ng:validate="number" size="6"></td>
<td>{{item.qty * item.cost | currency}}</td>
<td>[<a href ng:click="invoice.items.$remove(item)">X</a>]</td>
</tr>
<tr>
<td><a href ng:click="invoice.items.$add()">add item</a></td>
<td></td>
<td>Total:</td>
<td>{{invoice.items.$sum('qty*cost') | currency}}</td>
</tr>
</table>
</doc:source>
<doc:scenario>
//TODO: these specs are lame because I had to work around issues #164 and #167
it('should initialize and calculate the totals', function() {
expect(repeater('.doc-example-live table tr', 'item in invoice.items').count()).toBe(3);
expect(repeater('.doc-example-live table tr', 'item in invoice.items').row(1)).
toEqual(['$99.50']);
expect(binding("invoice.items.$sum('qty*cost')")).toBe('$99.50');
expect(binding("invoice.items.$sum('qty*cost')")).toBe('$99.50');
});
it('should add an entry and recalculate', function() {
element('.doc-example-live a:contains("add item")').click();
using('.doc-example-live tr:nth-child(3)').input('item.qty').enter('20');
using('.doc-example-live tr:nth-child(3)').input('item.cost').enter('100');
expect(repeater('.doc-example-live table tr', 'item in invoice.items').row(2)).
toEqual(['$2,000.00']);
expect(binding("invoice.items.$sum('qty*cost')")).toBe('$2,099.50');
});
</doc:scenario>
</doc:example>
*/
'sum':function(array, expression) {
var fn = angularFunction.compile(expression);
var sum = 0;
for (var i = 0; i < array.length; i++) {
var value = 1 * fn(array[i]);
if (!isNaN(value)){
sum += value;
}
}
return sum;
},
/**
* @ngdoc function
* @name angular.Array.remove
* @function
*
* @description
* Modifies `array` by removing an element from it. The element will be looked up using the
* {@link angular.Array.indexOf indexOf} function on the `array` and only the first instance of
* the element will be removed.
*
* Note: This function is used to augment the `Array` type in Angular expressions. See
* {@link angular.Array} for more information about Angular arrays.
*
* @param {Array} array Array from which an element should be removed.
* @param {*} value Element to be removed.
* @returns {*} The removed element.
*
* @example
<doc:example>
<doc:source>
<ul ng:init="tasks=['Learn Angular', 'Read Documentation',
'Check out demos', 'Build cool applications']">
<li ng:repeat="task in tasks">
{{task}} [<a href="" ng:click="tasks.$remove(task)">X</a>]
</li>
</ul>
<hr/>
tasks = {{tasks}}
</doc:source>
<doc:scenario>
it('should initialize the task list with for tasks', function() {
expect(repeater('.doc-example-live ul li', 'task in tasks').count()).toBe(4);
expect(repeater('.doc-example-live ul li', 'task in tasks').column('task')).
toEqual(['Learn Angular', 'Read Documentation', 'Check out demos',
'Build cool applications']);
});
it('should initialize the task list with for tasks', function() {
element('.doc-example-live ul li a:contains("X"):first').click();
expect(repeater('.doc-example-live ul li', 'task in tasks').count()).toBe(3);
element('.doc-example-live ul li a:contains("X"):last').click();
expect(repeater('.doc-example-live ul li', 'task in tasks').count()).toBe(2);
expect(repeater('.doc-example-live ul li', 'task in tasks').column('task')).
toEqual(['Read Documentation', 'Check out demos']);
});
</doc:scenario>
</doc:example>
*/
'remove':function(array, value) {
var index = indexOf(array, value);
if (index >=0)
array.splice(index, 1);
return value;
},
/**
* @ngdoc function
* @name angular.Array.filter
* @function
*
* @description
* Selects a subset of items from `array` and returns it as a new array.
*
* Note: This function is used to augment the `Array` type in Angular expressions. See
* {@link angular.Array} for more information about Angular arrays.
*
* @param {Array} array The source array.
* @param {string|Object|function()} expression The predicate to be used for selecting items from
* `array`.
*
* Can be one of:
*
* - `string`: Predicate that results in a substring match using the value of `expression`
* string. All strings or objects with string properties in `array` that contain this string
* will be returned. The predicate can be negated by prefixing the string with `!`.
*
* - `Object`: A pattern object can be used to filter specific properties on objects contained
* by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
* which have property `name` containing "M" and property `phone` containing "1". A special
* property name `$` can be used (as in `{$:"text"}`) to accept a match against any
* property of the object. That's equivalent to the simple substring match with a `string`
* as described above.
*
* - `function`: A predicate function can be used to write arbitrary filters. The function is
* called for each element of `array`. The final result is an array of those elements that
* the predicate returned true for.
*
* @example
<doc:example>
<doc:source>
<div ng:init="friends = [{name:'John', phone:'555-1276'},
{name:'Mary', phone:'800-BIG-MARY'},
{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},
{name:'Julie', phone:'555-8765'}]"></div>
Search: <input name="searchText"/>
<table id="searchTextResults">
<tr><th>Name</th><th>Phone</th><tr>
<tr ng:repeat="friend in friends.$filter(searchText)">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<tr>
</table>
<hr>
Any: <input name="search.$"/> <br>
Name only <input name="search.name"/><br>
Phone only <input name="search.phone"/><br>
<table id="searchObjResults">
<tr><th>Name</th><th>Phone</th><tr>
<tr ng:repeat="friend in friends.$filter(search)">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<tr>
</table>
</doc:source>
<doc:scenario>
it('should search across all fields when filtering with a string', function() {
input('searchText').enter('m');
expect(repeater('#searchTextResults tr', 'friend in friends').column('name')).
toEqual(['Mary', 'Mike', 'Adam']);
input('searchText').enter('76');
expect(repeater('#searchTextResults tr', 'friend in friends').column('name')).
toEqual(['John', 'Julie']);
});
it('should search in specific fields when filtering with a predicate object', function() {
input('search.$').enter('i');
expect(repeater('#searchObjResults tr', 'friend in friends').column('name')).
toEqual(['Mary', 'Mike', 'Julie']);
});
</doc:scenario>
</doc:example>
*/
'filter':function(array, expression) {
var predicates = [];
predicates.check = function(value) {
for (var j = 0; j < predicates.length; j++) {
if(!predicates[j](value)) {
return false;
}
}
return true;
};
var search = function(obj, text){
if (text.charAt(0) === '!') {
return !search(obj, text.substr(1));
}
switch (typeof obj) {
case "boolean":
case "number":
case "string":
return ('' + obj).toLowerCase().indexOf(text) > -1;
case "object":
for ( var objKey in obj) {
if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
return true;
}
}
return false;
case "array":
for ( var i = 0; i < obj.length; i++) {
if (search(obj[i], text)) {
return true;
}
}
return false;
default:
return false;
}
};
switch (typeof expression) {
case "boolean":
case "number":
case "string":
expression = {$:expression};
case "object":
for (var key in expression) {
if (key == '$') {
(function(){
var text = (''+expression[key]).toLowerCase();
if (!text) return;
predicates.push(function(value) {
return search(value, text);
});
})();
} else {
(function(){
var path = key;
var text = (''+expression[key]).toLowerCase();
if (!text) return;
predicates.push(function(value) {
return search(getter(value, path), text);
});
})();
}
}
break;
case 'function':
predicates.push(expression);
break;
default:
return array;
}
var filtered = [];
for ( var j = 0; j < array.length; j++) {
var value = array[j];
if (predicates.check(value)) {
filtered.push(value);
}
}
return filtered;
},
/**
* @ngdoc function
* @name angular.Array.add
* @function
*
* @description
* The `add` function in Angualar is similar to JavaScript's `Array#push` method in that it
* appends a new element to an array. Angular's function differs from the JavaScript method in
* that specifying a value for the function is optional and the default for the function is an
* empty object.
*
* Note: This function is used to augment the `Array` type in Angular expressions. See
* {@link angular.Array} for more information about Angular arrays.
*
* @param {Array} array The array to be expanded.
* @param {*=} [value={}] The value to be appended.
* @returns {Array} The expanded array.
*
* @TODO simplify the example.
*
* @example
* This example shows how you can use the `$add` method to populate an initially empty array
* with objects created from user input.
<doc:example>
<doc:source>
[<a href="" ng:click="people.$add()">add empty</a>]
[<a href="" ng:click="people.$add({name:'John', sex:'male'})">add 'John'</a>]
[<a href="" ng:click="people.$add({name:'Mary', sex:'female'})">add 'Mary'</a>]
<ul ng:init="people=[]">
<li ng:repeat="person in people">
<input name="person.name">
<select name="person.sex">
<option value="">--chose one--</option>
<option>male</option>
<option>female</option>
</select>
[<a href="" ng:click="people.$remove(person)">X</a>]
</li>
</ul>
<pre>people = {{people}}</pre>
</doc:source>
<doc:scenario>
beforeEach(function() {
expect(binding('people')).toBe('people = []');
});
it('should create an empty record when "add empty" is clicked', function() {
element('.doc-example-live a:contains("add empty")').click();
expect(binding('people')).toBe('people = [{\n "name":"",\n "sex":null}]');
});
it('should create a "John" record when "add \'John\'" is clicked', function() {
element('.doc-example-live a:contains("add \'John\'")').click();
expect(binding('people')).toBe('people = [{\n "name":"John",\n "sex":"male"}]');
});
it('should create a "Mary" record when "add \'Mary\'" is clicked', function() {
element('.doc-example-live a:contains("add \'Mary\'")').click();
expect(binding('people')).toBe('people = [{\n "name":"Mary",\n "sex":"female"}]');
});
it('should delete a record when "X" is clicked', function() {
element('.doc-example-live a:contains("add empty")').click();
element('.doc-example-live li a:contains("X"):first').click();
expect(binding('people')).toBe('people = []');
});
</doc:scenario>
</doc:example>
*/
'add':function(array, value) {
array.push(isUndefined(value)? {} : value);
return array;
},
/**
* @ngdoc function
* @name angular.Array.count
* @function
*
* @description
* Determines the number of elements in an array. Provides an option for counting only those
* elements for which a specified `condition` evaluates to `true`.
*
* Note: This function is used to augment the `Array` type in Angular expressions. See
* {@link angular.Array} for more information about Angular arrays.
*
* @param {Array} array The array containing the elements to be counted.
* @param {(function()|string)=} condition A function to be evaluated or
* an Angular expression to be compiled and evaluated. The element being
* iterated over is exposed to the `condition` as `this`.
* @returns {number} Number of elements in the array. If a `condition` is specified, returns
* the number of elements whose `condition` evaluates to `true`.
*
* @example
<doc:example>
<doc:source>
<pre ng:init="items = [{name:'knife', points:1},
{name:'fork', points:3},
{name:'spoon', points:1}]"></pre>
<ul>
<li ng:repeat="item in items">
{{item.name}}: points=
<input type="text" name="item.points"/> <!-- id="item{{$index}} -->
</li>
</ul>
<p>Number of items which have one point: <em>{{ items.$count('points==1') }}</em></p>
<p>Number of items which have more than one point:
<em>{{items.$count('points>1')}}</em></p>
</doc:source>
<doc:scenario>
it('should calculate counts', function() {
expect(binding('items.$count(\'points==1\')')).toEqual('2');
expect(binding('items.$count(\'points>1\')')).toEqual('1');
});
it('should recalculate when updated', function() {
using('.doc-example-live li:first-child').input('item.points').enter('23');
expect(binding('items.$count(\'points==1\')')).toEqual('1');
expect(binding('items.$count(\'points>1\')')).toEqual('2');
});
</doc:scenario>
</doc:example>
*/
'count':function(array, condition) {
if (!condition) return array.length;
var fn = angularFunction.compile(condition), count = 0;
forEach(array, function(value){
if (fn(value)) {
count ++;
}
});
return count;
},
/**
* @ngdoc function
* @name angular.Array.orderBy
* @function
*
* @description
* Orders a specified `array` by the `expression` predicate.
*
* Note: this function is used to augment the `Array` type in Angular expressions. See
* {@link angular.Array} for more informaton about Angular arrays.
*
* @param {Array} array The array to sort.
* @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be
* used by the comparator to determine the order of elements.
*
* Can be one of:
*
* - `function`: Getter function. The result of this function will be sorted using the
* `<`, `=`, `>` operator.
* - `string`: An Angular expression which evaluates to an object to order by, such as 'name'
* to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control
* ascending or descending sort order (for example, +name or -name).
* - `Array`: An array of function or string predicates. The first predicate in the array
* is used for sorting, but when two items are equivalent, the next predicate is used.
*
* @param {boolean=} reverse Reverse the order the array.
* @returns {Array} Sorted copy of the source array.
*
* @example
<doc:example>
<doc:source>
<div ng:init="friends = [{name:'John', phone:'555-1212', age:10},
{name:'Mary', phone:'555-9876', age:19},
{name:'Mike', phone:'555-4321', age:21},
{name:'Adam', phone:'555-5678', age:35},
{name:'Julie', phone:'555-8765', age:29}]"></div>
<pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
<hr/>
[ <a href="" ng:click="predicate=''">unsorted</a> ]
<table ng:init="predicate='-age'">
<tr>
<th><a href="" ng:click="predicate = 'name'; reverse=false">Name</a>
(<a href ng:click="predicate = '-name'; reverse=false">^</a>)</th>
<th><a href="" ng:click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
<th><a href="" ng:click="predicate = 'age'; reverse=!reverse">Age</a></th>
<tr>
<tr ng:repeat="friend in friends.$orderBy(predicate, reverse)">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
<tr>
</table>
</doc:source>
<doc:scenario>
it('should be reverse ordered by aged', function() {
expect(binding('predicate')).toBe('Sorting predicate = -age; reverse = ');
expect(repeater('.doc-example-live table', 'friend in friends').column('friend.age')).
toEqual(['35', '29', '21', '19', '10']);
expect(repeater('.doc-example-live table', 'friend in friends').column('friend.name')).
toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']);
});
it('should reorder the table when user selects different predicate', function() {
element('.doc-example-live a:contains("Name")').click();
expect(repeater('.doc-example-live table', 'friend in friends').column('friend.name')).
toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']);
expect(repeater('.doc-example-live table', 'friend in friends').column('friend.age')).
toEqual(['35', '10', '29', '19', '21']);
element('.doc-example-live a:contains("Phone")').click();
expect(repeater('.doc-example-live table', 'friend in friends').column('friend.phone')).
toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']);
expect(repeater('.doc-example-live table', 'friend in friends').column('friend.name')).
toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']);
});
</doc:scenario>
</doc:example>
*/
'orderBy':function(array, sortPredicate, reverseOrder) {
if (!sortPredicate) return array;
sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate];
sortPredicate = map(sortPredicate, function(predicate){
var descending = false, get = predicate || identity;
if (isString(predicate)) {
if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
descending = predicate.charAt(0) == '-';
predicate = predicate.substring(1);
}
get = expressionCompile(predicate);
}
return reverseComparator(function(a,b){
return compare(get(a),get(b));
}, descending);
});
var arrayCopy = [];
for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); }
return arrayCopy.sort(reverseComparator(comparator, reverseOrder));
function comparator(o1, o2){
for ( var i = 0; i < sortPredicate.length; i++) {
var comp = sortPredicate[i](o1, o2);
if (comp !== 0) return comp;
}
return 0;
}
function reverseComparator(comp, descending) {
return toBoolean(descending)
? function(a,b){return comp(b,a);}
: comp;
}
function compare(v1, v2){
var t1 = typeof v1;
var t2 = typeof v2;
if (t1 == t2) {
if (t1 == "string") v1 = v1.toLowerCase();
if (t1 == "string") v2 = v2.toLowerCase();
if (v1 === v2) return 0;
return v1 < v2 ? -1 : 1;
} else {
return t1 < t2 ? -1 : 1;
}
}
},
/**
* @ngdoc function
* @name angular.Array.limitTo
* @function
*
* @description
* Creates a new array containing only a specified number of elements in an array. The elements
* are taken from either the beginning or the end of the source array, as specified by the
* value and sign (positive or negative) of `limit`.
*
* Note: This function is used to augment the `Array` type in Angular expressions. See
* {@link angular.Array} for more information about Angular arrays.
*
* @param {Array} array Source array to be limited.
* @param {string|Number} limit The length of the returned array. If the `limit` number is
* positive, `limit` number of items from the beginning of the source array are copied.
* If the number is negative, `limit` number of items from the end of the source array are
* copied. The `limit` will be trimmed if it exceeds `array.length`
* @returns {Array} A new sub-array of length `limit` or less if input array had less than `limit`
* elements.
*
* @example
<doc:example>
<doc:source>
<div ng:init="numbers = [1,2,3,4,5,6,7,8,9]">
Limit [1,2,3,4,5,6,7,8,9] to: <input name="limit" value="3"/>
<p>Output: {{ numbers.$limitTo(limit) | json }}</p>
</div>
</doc:source>
<doc:scenario>
it('should limit the numer array to first three items', function() {
expect(element('.doc-example-live input[name=limit]').val()).toBe('3');
expect(binding('numbers.$limitTo(limit) | json')).toEqual('[1,2,3]');
});
it('should update the output when -3 is entered', function() {
input('limit').enter(-3);
expect(binding('numbers.$limitTo(limit) | json')).toEqual('[7,8,9]');
});
it('should not exceed the maximum size of input array', function() {
input('limit').enter(100);
expect(binding('numbers.$limitTo(limit) | json')).toEqual('[1,2,3,4,5,6,7,8,9]');
});
</doc:scenario>
</doc:example>
*/
limitTo: function(array, limit) {
limit = parseInt(limit, 10);
var out = [],
i, n;
// check that array is iterable
if (!array || !(array instanceof Array))
return out;
// if abs(limit) exceeds maximum length, trim it
if (limit > array.length)
limit = array.length;
else if (limit < -array.length)
limit = -array.length;
if (limit > 0) {
i = 0;
n = limit;
} else {
i = array.length + limit;
n = array.length;
}
for (; i<n; i++) {
out.push(array[i]);
}
return out;
}
};
var R_ISO8061_STR = /^(\d{4})-(\d\d)-(\d\d)(?:T(\d\d)(?:\:(\d\d)(?:\:(\d\d)(?:\.(\d{3}))?)?)?Z)?$/;
var angularString = {
'quote':function(string) {
return '"' + string.replace(/\\/g, '\\\\').
replace(/"/g, '\\"').
replace(/\n/g, '\\n').
replace(/\f/g, '\\f').
replace(/\r/g, '\\r').
replace(/\t/g, '\\t').
replace(/\v/g, '\\v') +
'"';
},
'quoteUnicode':function(string) {
var str = angular['String']['quote'](string);
var chars = [];
for ( var i = 0; i < str.length; i++) {
var ch = str.charCodeAt(i);
if (ch < 128) {
chars.push(str.charAt(i));
} else {
var encode = "000" + ch.toString(16);
chars.push("\\u" + encode.substring(encode.length - 4));
}
}
return chars.join('');
},
/**
* Tries to convert input to date and if successful returns the date, otherwise returns the
* input.
*
* @param {string} string
* @return {(Date|string)}
*/
'toDate':function(string){
var match;
if (isString(string) && (match = string.match(R_ISO8061_STR))){
var date = new Date(0);
date.setUTCFullYear(match[1], match[2] - 1, match[3]);
date.setUTCHours(match[4]||0, match[5]||0, match[6]||0, match[7]||0);
return date;
}
return string;
}
};
var angularDate = {
'toString':function(date){
if (!date) return date;
var isoString = date.toISOString ? date.toISOString() : '';
return (isoString.length==24) ?
isoString :
padNumber(date.getUTCFullYear(), 4) + '-' +
padNumber(date.getUTCMonth() + 1, 2) + '-' +
padNumber(date.getUTCDate(), 2) + 'T' +
padNumber(date.getUTCHours(), 2) + ':' +
padNumber(date.getUTCMinutes(), 2) + ':' +
padNumber(date.getUTCSeconds(), 2) + '.' +
padNumber(date.getUTCMilliseconds(), 3) + 'Z';
}
};
var angularFunction = {
'compile': function(expression) {
if (isFunction(expression)){
return expression;
} else if (expression){
return expressionCompile(expression);
} else {
return identity;
}
}
};
/**
* Computes a hash of an 'obj'.
* Hash of a:
* string is string
* number is number as string
* object is either call $hashKey function on object or assign unique hashKey id.
*
* @param obj
* @returns {String} hash string such that the same input will have the same hash string
*/
function hashKey(obj) {
var objType = typeof obj;
var key = obj;
if (objType == 'object') {
if (typeof (key = obj.$hashKey) == 'function') {
// must invoke on object to keep the right this
key = obj.$hashKey();
} else if (key === undefined) {
key = obj.$hashKey = nextUid();
}
}
return objType + ':' + key;
}
/**
* HashMap which can use objects as keys
*/
function HashMap(){}
HashMap.prototype = {
/**
* Store key value pair
* @param key key to store can be any type
* @param value value to store can be any type
* @returns old value if any
*/
put: function(key, value) {
var _key = hashKey(key);
var oldValue = this[_key];
this[_key] = value;
return oldValue;
},
/**
* @param key
* @returns the value for the key
*/
get: function(key) {
return this[hashKey(key)];
},
/**
* Remove the key/value pair
* @param key
* @returns value associated with key before it was removed
*/
remove: function(key) {
var _key = hashKey(key);
var value = this[_key];
delete this[_key];
return value;
}
};
function defineApi(dst, chain){
angular[dst] = angular[dst] || {};
forEach(chain, function(parent){
extend(angular[dst], parent);
});
}
defineApi('Global', [angularGlobal]);
defineApi('Collection', [angularGlobal, angularCollection]);
defineApi('Array', [angularGlobal, angularCollection, angularArray]);
defineApi('Object', [angularGlobal, angularCollection, angularObject]);
defineApi('String', [angularGlobal, angularString]);
defineApi('Date', [angularGlobal, angularDate]);
//IE bug
angular.Date.toString = angularDate.toString;
defineApi('Function', [angularGlobal, angularCollection, angularFunction]);
/**
* @workInProgress
* @ngdoc overview
* @name angular.filter
* @description
*
* Filters are used for formatting data displayed to the user.
*
* The general syntax in templates is as follows:
*
* {{ expression | [ filter_name ] }}
*
* Following is the list of built-in angular filters:
*
* * {@link angular.filter.currency currency}
* * {@link angular.filter.date date}
* * {@link angular.filter.html html}
* * {@link angular.filter.json json}
* * {@link angular.filter.linky linky}
* * {@link angular.filter.lowercase lowercase}
* * {@link angular.filter.number number}
* * {@link angular.filter.uppercase uppercase}
*
* For more information about how angular filters work, and how to create your own filters, see
* {@link guide/dev_guide.templates.filters Understanding Angular Filters} in the angular Developer
* Guide.
*/
/**
* @workInProgress
* @ngdoc filter
* @name angular.filter.currency
* @function
*
* @description
* Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
* symbol for current locale is used.
*
* @param {number} amount Input to filter.
* @param {string=} symbol Currency symbol or identifier to be displayed.
* @returns {string} Formatted number.
*
* @css ng-format-negative
* When the value is negative, this css class is applied to the binding making it (by default) red.
*
* @example
<doc:example>
<doc:source>
<input type="text" name="amount" value="1234.56"/> <br/>
default currency symbol ($): {{amount | currency}}<br/>
custom currency identifier (USD$): {{amount | currency:"USD$"}}
</doc:source>
<doc:scenario>
it('should init with 1234.56', function(){
expect(binding('amount | currency')).toBe('$1,234.56');
expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56');
});
it('should update', function(){
input('amount').enter('-1234');
expect(binding('amount | currency')).toBe('($1,234.00)');
expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)');
expect(element('.doc-example-live .ng-binding').prop('className')).
toMatch(/ng-format-negative/);
});
</doc:scenario>
</doc:example>
*/
angularFilter.currency = function(amount, currencySymbol){
var formats = this.$service('$locale').NUMBER_FORMATS;
this.$element.toggleClass('ng-format-negative', amount < 0);
if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM;
return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2).
replace(/\u00A4/g, currencySymbol);
};
/**
* @workInProgress
* @ngdoc filter
* @name angular.filter.number
* @function
*
* @description
* Formats a number as text.
*
* If the input is not a number an empty string is returned.
*
* @param {number|string} number Number to format.
* @param {(number|string)=} [fractionSize=2] Number of decimal places to round the number to.
* @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
*
* @example
<doc:example>
<doc:source>
Enter number: <input name='val' value='1234.56789' /><br/>
Default formatting: {{val | number}}<br/>
No fractions: {{val | number:0}}<br/>
Negative number: {{-val | number:4}}
</doc:source>
<doc:scenario>
it('should format numbers', function(){
expect(binding('val | number')).toBe('1,234.568');
expect(binding('val | number:0')).toBe('1,235');
expect(binding('-val | number:4')).toBe('-1,234.5679');
});
it('should update', function(){
input('val').enter('3374.333');
expect(binding('val | number')).toBe('3,374.333');
expect(binding('val | number:0')).toBe('3,374');
expect(binding('-val | number:4')).toBe('-3,374.3330');
});
</doc:scenario>
</doc:example>
*/
var DECIMAL_SEP = '.';
angularFilter.number = function(number, fractionSize) {
var formats = this.$service('$locale').NUMBER_FORMATS;
return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP,
formats.DECIMAL_SEP, fractionSize);
};
function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
if (isNaN(number) || !isFinite(number)) return '';
var isNegative = number < 0;
number = Math.abs(number);
var numStr = number + '',
formatedText = '',
parts = [];
if (numStr.indexOf('e') !== -1) {
formatedText = numStr;
} else {
var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
// determine fractionSize if it is not specified
if (isUndefined(fractionSize)) {
fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
}
var pow = Math.pow(10, fractionSize);
number = Math.round(number * pow) / pow;
var fraction = ('' + number).split(DECIMAL_SEP);
var whole = fraction[0];
fraction = fraction[1] || '';
var pos = 0,
lgroup = pattern.lgSize,
group = pattern.gSize;
if (whole.length >= (lgroup + group)) {
pos = whole.length - lgroup;
for (var i = 0; i < pos; i++) {
if ((pos - i)%group === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
}
for (i = pos; i < whole.length; i++) {
if ((whole.length - i)%lgroup === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
// format fraction part.
while(fraction.length < fractionSize) {
fraction += '0';
}
if (fractionSize) formatedText += decimalSep + fraction.substr(0, fractionSize);
}
parts.push(isNegative ? pattern.negPre : pattern.posPre);
parts.push(formatedText);
parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
return parts.join('');
}
function padNumber(num, digits, trim) {
var neg = '';
if (num < 0) {
neg = '-';
num = -num;
}
num = '' + num;
while(num.length < digits) num = '0' + num;
if (trim)
num = num.substr(num.length - digits);
return neg + num;
}
function dateGetter(name, size, offset, trim) {
return function(date) {
var value = date['get' + name]();
if (offset > 0 || value > -offset)
value += offset;
if (value === 0 && offset == -12 ) value = 12;
return padNumber(value, size, trim);
};
}
function dateStrGetter(name, shortForm) {
return function(date, formats) {
var value = date['get' + name]();
var get = uppercase(shortForm ? ('SHORT' + name) : name);
return formats[get][value];
};
}
function timeZoneGetter(date) {
var offset = date.getTimezoneOffset();
return padNumber(offset / 60, 2) + padNumber(Math.abs(offset % 60), 2);
}
function ampmGetter(date, formats) {
return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
}
var DATE_FORMATS = {
yyyy: dateGetter('FullYear', 4),
yy: dateGetter('FullYear', 2, 0, true),
y: dateGetter('FullYear', 1),
MMMM: dateStrGetter('Month'),
MMM: dateStrGetter('Month', true),
MM: dateGetter('Month', 2, 1),
M: dateGetter('Month', 1, 1),
dd: dateGetter('Date', 2),
d: dateGetter('Date', 1),
HH: dateGetter('Hours', 2),
H: dateGetter('Hours', 1),
hh: dateGetter('Hours', 2, -12),
h: dateGetter('Hours', 1, -12),
mm: dateGetter('Minutes', 2),
m: dateGetter('Minutes', 1),
ss: dateGetter('Seconds', 2),
s: dateGetter('Seconds', 1),
EEEE: dateStrGetter('Day'),
EEE: dateStrGetter('Day', true),
a: ampmGetter,
Z: timeZoneGetter
};
var GET_TIME_ZONE = /[A-Z]{3}(?![+\-])/,
DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,
OPERA_TOSTRING_PATTERN = /^[\d].*Z$/,
NUMBER_STRING = /^\d+$/;
/**
* @workInProgress
* @ngdoc filter
* @name angular.filter.date
* @function
*
* @description
* Formats `date` to a string based on the requested `format`.
*
* `format` string can be composed of the following elements:
*
* * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
* * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
* * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
* * `'MMMM'`: Month in year (January-December)
* * `'MMM'`: Month in year (Jan-Dec)
* * `'MM'`: Month in year, padded (01-12)
* * `'M'`: Month in year (1-12)
* * `'dd'`: Day in month, padded (01-31)
* * `'d'`: Day in month (1-31)
* * `'EEEE'`: Day in Week,(Sunday-Saturday)
* * `'EEE'`: Day in Week, (Sun-Sat)
* * `'HH'`: Hour in day, padded (00-23)
* * `'H'`: Hour in day (0-23)
* * `'hh'`: Hour in am/pm, padded (01-12)
* * `'h'`: Hour in am/pm, (1-12)
* * `'mm'`: Minute in hour, padded (00-59)
* * `'m'`: Minute in hour (0-59)
* * `'ss'`: Second in minute, padded (00-59)
* * `'s'`: Second in minute (0-59)
* * `'a'`: am/pm marker
* * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-1200)
*
* `format` string can also be one of the following predefined
* {@link guide/dev_guide.i18n localizable formats}:
*
* * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
* (e.g. Sep 3, 2010 12:05:08 pm)
* * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm)
* * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale
* (e.g. Friday, September 3, 2010)
* * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010
* * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
* * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
* * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm)
* * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm)
*
* `format` string can contain literal values. These need to be quoted with single quotes (e.g.
* `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence
* (e.g. `"h o''clock"`).
*
* @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
* number) or ISO 8601 extended datetime string (yyyy-MM-ddTHH:mm:ss.SSSZ).
* @param {string=} format Formatting rules (see Description). If not specified,
* Date#toLocaleDateString is used.
* @returns {string} Formatted string or the input if input is not recognized as date/millis.
*
* @example
<doc:example>
<doc:source>
<span ng:non-bindable>{{1288323623006 | date:'medium'}}</span>:
{{1288323623006 | date:'medium'}}<br/>
<span ng:non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br/>
<span ng:non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br/>
</doc:source>
<doc:scenario>
it('should format date', function(){
expect(binding("1288323623006 | date:'medium'")).
toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).
toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} \-?\d{4}/);
expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).
toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
});
</doc:scenario>
</doc:example>
*/
angularFilter.date = function(date, format) {
var $locale = this.$service('$locale');
format = $locale.DATETIME_FORMATS[format] || format;
if (isString(date)) {
if (NUMBER_STRING.test(date)) {
date = parseInt(date, 10);
} else {
date = angularString.toDate(date);
}
}
if (isNumber(date)) {
date = new Date(date);
}
if (!isDate(date)) {
return date;
}
var text = date.toLocaleDateString(), fn;
if (format && isString(format)) {
text = '';
var parts = [], match;
while(format) {
match = DATE_FORMATS_SPLIT.exec(format);
if (match) {
parts = concat(parts, match, 1);
format = parts.pop();
} else {
parts.push(format);
format = null;
}
}
forEach(parts, function(value){
fn = DATE_FORMATS[value];
text += fn ? fn(date, $locale.DATETIME_FORMATS)
: value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
});
}
return text;
};
/**
* @workInProgress
* @ngdoc filter
* @name angular.filter.json
* @function
*
* @description
* Allows you to convert a JavaScript object into JSON string.
*
* This filter is mostly useful for debugging. When using the double curly {{value}} notation
* the binding is automatically converted to JSON.
*
* @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
* @returns {string} JSON string.
*
* @css ng-monospace Always applied to the encapsulating element.
*
* @example:
<doc:example>
<doc:source>
<pre>{{ {'name':'value'} | json }}</pre>
</doc:source>
<doc:scenario>
it('should jsonify filtered objects', function() {
expect(binding('| json')).toBe('{\n "name":"value"}');
});
</doc:scenario>
</doc:example>
*
*/
angularFilter.json = function(object) {
this.$element.addClass("ng-monospace");
return toJson(object, true);
};
/**
* @workInProgress
* @ngdoc filter
* @name angular.filter.lowercase
* @function
*
* @see angular.lowercase
*/
angularFilter.lowercase = lowercase;
/**
* @workInProgress
* @ngdoc filter
* @name angular.filter.uppercase
* @function
*
* @see angular.uppercase
*/
angularFilter.uppercase = uppercase;
/**
* @workInProgress
* @ngdoc filter
* @name angular.filter.html
* @function
*
* @description
* Prevents the input from getting escaped by angular. By default the input is sanitized and
* inserted into the DOM as is.
*
* The input is sanitized by parsing the html into tokens. All safe tokens (from a whitelist) are
* then serialized back to properly escaped html string. This means that no unsafe input can make
* it into the returned string, however, since our parser is more strict than a typical browser
* parser, it's possible that some obscure input, which would be recognized as valid HTML by a
* browser, won't make it through the sanitizer.
*
* If you hate your users, you may call the filter with optional 'unsafe' argument, which bypasses
* the html sanitizer, but makes your application vulnerable to XSS and other attacks. Using this
* option is strongly discouraged and should be used only if you absolutely trust the input being
* filtered and you can't get the content through the sanitizer.
*
* @param {string} html Html input.
* @param {string=} option If 'unsafe' then do not sanitize the HTML input.
* @returns {string} Sanitized or raw html.
*
* @example
<doc:example>
<doc:source>
Snippet: <textarea name="snippet" cols="60" rows="3">
<p style="color:blue">an html
<em onmouseover="this.textContent='PWN3D!'">click here</em>
snippet</p></textarea>
<table>
<tr>
<td>Filter</td>
<td>Source</td>
<td>Rendered</td>
</tr>
<tr id="html-filter">
<td>html filter</td>
<td>
<pre><div ng:bind="snippet | html"><br/></div></pre>
</td>
<td>
<div ng:bind="snippet | html"></div>
</td>
</tr>
<tr id="escaped-html">
<td>no filter</td>
<td><pre><div ng:bind="snippet"><br/></div></pre></td>
<td><div ng:bind="snippet"></div></td>
</tr>
<tr id="html-unsafe-filter">
<td>unsafe html filter</td>
<td><pre><div ng:bind="snippet | html:'unsafe'"><br/></div></pre></td>
<td><div ng:bind="snippet | html:'unsafe'"></div></td>
</tr>
</table>
</doc:source>
<doc:scenario>
it('should sanitize the html snippet ', function(){
expect(using('#html-filter').binding('snippet | html')).
toBe('<p>an html\n<em>click here</em>\nsnippet</p>');
});
it('should escape snippet without any filter', function() {
expect(using('#escaped-html').binding('snippet')).
toBe("<p style=\"color:blue\">an html\n" +
"<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
"snippet</p>");
});
it('should inline raw snippet if filtered as unsafe', function() {
expect(using('#html-unsafe-filter').binding("snippet | html:'unsafe'")).
toBe("<p style=\"color:blue\">an html\n" +
"<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
"snippet</p>");
});
it('should update', function(){
input('snippet').enter('new <b>text</b>');
expect(using('#html-filter').binding('snippet | html')).toBe('new <b>text</b>');
expect(using('#escaped-html').binding('snippet')).toBe("new <b>text</b>");
expect(using('#html-unsafe-filter').binding("snippet | html:'unsafe'")).toBe('new <b>text</b>');
});
</doc:scenario>
</doc:example>
*/
angularFilter.html = function(html, option){
return new HTML(html, option);
};
/**
* @workInProgress
* @ngdoc filter
* @name angular.filter.linky
* @function
*
* @description
* Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and
* plain email address links.
*
* @param {string} text Input text.
* @returns {string} Html-linkified text.
*
* @example
<doc:example>
<doc:source>
Snippet: <textarea name="snippet" cols="60" rows="3">
Pretty text with some links:
http://angularjs.org/,
mailto:us@somewhere.org,
another@somewhere.org,
and one more: ftp://127.0.0.1/.</textarea>
<table>
<tr>
<td>Filter</td>
<td>Source</td>
<td>Rendered</td>
</tr>
<tr id="linky-filter">
<td>linky filter</td>
<td>
<pre><div ng:bind="snippet | linky"><br/></div></pre>
</td>
<td>
<div ng:bind="snippet | linky"></div>
</td>
</tr>
<tr id="escaped-html">
<td>no filter</td>
<td><pre><div ng:bind="snippet"><br/></div></pre></td>
<td><div ng:bind="snippet"></div></td>
</tr>
</table>
</doc:source>
<doc:scenario>
it('should linkify the snippet with urls', function(){
expect(using('#linky-filter').binding('snippet | linky')).
toBe('Pretty text with some links:\n' +
'<a href="http://angularjs.org/">http://angularjs.org/</a>,\n' +
'<a href="mailto:us@somewhere.org">us@somewhere.org</a>,\n' +
'<a href="mailto:another@somewhere.org">another@somewhere.org</a>,\n' +
'and one more: <a href="ftp://127.0.0.1/">ftp://127.0.0.1/</a>.');
});
it ('should not linkify snippet without the linky filter', function() {
expect(using('#escaped-html').binding('snippet')).
toBe("Pretty text with some links:\n" +
"http://angularjs.org/,\n" +
"mailto:us@somewhere.org,\n" +
"another@somewhere.org,\n" +
"and one more: ftp://127.0.0.1/.");
});
it('should update', function(){
input('snippet').enter('new http://link.');
expect(using('#linky-filter').binding('snippet | linky')).
toBe('new <a href="http://link">http://link</a>.');
expect(using('#escaped-html').binding('snippet')).toBe('new http://link.');
});
</doc:scenario>
</doc:example>
*/
var LINKY_URL_REGEXP = /((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s\.\;\,\(\)\{\}\<\>]/,
MAILTO_REGEXP = /^mailto:/;
angularFilter.linky = function(text) {
if (!text) return text;
var match;
var raw = text;
var html = [];
var writer = htmlSanitizeWriter(html);
var url;
var i;
while ((match = raw.match(LINKY_URL_REGEXP))) {
// We can not end in these as they are sometimes found at the end of the sentence
url = match[0];
// if we did not match ftp/http/mailto then assume mailto
if (match[2] == match[3]) url = 'mailto:' + url;
i = match.index;
writer.chars(raw.substr(0, i));
writer.start('a', {href:url});
writer.chars(match[0].replace(MAILTO_REGEXP, ''));
writer.end('a');
raw = raw.substring(i + match[0].length);
}
writer.chars(raw);
return new HTML(html.join(''));
};
/**
* @workInProgress
* @ngdoc overview
* @name angular.formatter
* @description
*
* Formatters are used for translating data formats between those used for display and those used
* for storage.
*
* Following is the list of built-in angular formatters:
*
* * {@link angular.formatter.boolean boolean} - Formats user input in boolean format
* * {@link angular.formatter.json json} - Formats user input in JSON format
* * {@link angular.formatter.list list} - Formats user input string as an array
* * {@link angular.formatter.number number} - Formats user input strings as a number
* * {@link angular.formatter.trim trim} - Trims extras spaces from end of user input
*
* For more information about how angular formatters work, and how to create your own formatters,
* see {@link guide/dev_guide.templates.formatters Understanding Angular Formatters} in the angular
* Developer Guide.
*/
function formatter(format, parse) {return {'format':format, 'parse':parse || format};}
function toString(obj) {
return (isDefined(obj) && obj !== null) ? "" + obj : obj;
}
var NUMBER = /^\s*[-+]?\d*(\.\d*)?\s*$/;
angularFormatter.noop = formatter(identity, identity);
/**
* @workInProgress
* @ngdoc formatter
* @name angular.formatter.json
*
* @description
* Formats the user input as JSON text.
*
* @returns {?string} A JSON string representation of the model.
*
* @example
<doc:example>
<doc:source>
<div ng:init="data={name:'misko', project:'angular'}">
<input type="text" size='50' name="data" ng:format="json"/>
<pre>data={{data}}</pre>
</div>
</doc:source>
<doc:scenario>
it('should format json', function(){
expect(binding('data')).toEqual('data={\n \"name\":\"misko\",\n \"project\":\"angular\"}');
input('data').enter('{}');
expect(binding('data')).toEqual('data={\n }');
});
</doc:scenario>
</doc:example>
*/
angularFormatter.json = formatter(toJson, function(value){
return fromJson(value || 'null');
});
/**
* @workInProgress
* @ngdoc formatter
* @name angular.formatter.boolean
*
* @description
* Use boolean formatter if you wish to store the data as boolean.
*
* @returns {boolean} Converts to `true` unless user enters (blank), `f`, `false`, `0`, `no`, `[]`.
*
* @example
<doc:example>
<doc:source>
Enter truthy text:
<input type="text" name="value" ng:format="boolean" value="no"/>
<input type="checkbox" name="value"/>
<pre>value={{value}}</pre>
</doc:source>
<doc:scenario>
it('should format boolean', function(){
expect(binding('value')).toEqual('value=false');
input('value').enter('truthy');
expect(binding('value')).toEqual('value=true');
});
</doc:scenario>
</doc:example>
*/
angularFormatter['boolean'] = formatter(toString, toBoolean);
/**
* @workInProgress
* @ngdoc formatter
* @name angular.formatter.number
*
* @description
* Use number formatter if you wish to convert the user entered string to a number.
*
* @returns {number} Number from the parsed string.
*
* @example
<doc:example>
<doc:source>
Enter valid number:
<input type="text" name="value" ng:format="number" value="1234"/>
<pre>value={{value}}</pre>
</doc:source>
<doc:scenario>
it('should format numbers', function(){
expect(binding('value')).toEqual('value=1234');
input('value').enter('5678');
expect(binding('value')).toEqual('value=5678');
});
</doc:scenario>
</doc:example>
*/
angularFormatter.number = formatter(toString, function(obj){
if (obj == null || NUMBER.exec(obj)) {
return obj===null || obj === '' ? null : 1*obj;
} else {
throw "Not a number";
}
});
/**
* @workInProgress
* @ngdoc formatter
* @name angular.formatter.list
*
* @description
* Use list formatter if you wish to convert the user entered string to an array.
*
* @returns {Array} Array parsed from the entered string.
*
* @example
<doc:example>
<doc:source>
Enter a list of items:
<input type="text" name="value" ng:format="list" value=" chair ,, table"/>
<input type="text" name="value" ng:format="list"/>
<pre>value={{value}}</pre>
</doc:source>
<doc:scenario>
it('should format lists', function(){
expect(binding('value')).toEqual('value=["chair","table"]');
this.addFutureAction('change to XYZ', function($window, $document, done){
$document.elements('.doc-example-live :input:last').val(',,a,b,').trigger('change');
done();
});
expect(binding('value')).toEqual('value=["a","b"]');
});
</doc:scenario>
</doc:example>
*/
angularFormatter.list = formatter(
function(obj) { return obj ? obj.join(", ") : obj; },
function(value) {
var list = [];
forEach((value || '').split(','), function(item){
item = trim(item);
if (item) list.push(item);
});
return list;
}
);
/**
* @workInProgress
* @ngdoc formatter
* @name angular.formatter.trim
*
* @description
* Use trim formatter if you wish to trim extra spaces in user text.
*
* @returns {String} Trim excess leading and trailing space.
*
* @example
<doc:example>
<doc:source>
Enter text with leading/trailing spaces:
<input type="text" name="value" ng:format="trim" value=" book "/>
<input type="text" name="value" ng:format="trim"/>
<pre>value={{value|json}}</pre>
</doc:source>
<doc:scenario>
it('should format trim', function(){
expect(binding('value')).toEqual('value="book"');
this.addFutureAction('change to XYZ', function($window, $document, done){
$document.elements('.doc-example-live :input:last').val(' text ').trigger('change');
done();
});
expect(binding('value')).toEqual('value="text"');
});
</doc:scenario>
</doc:example>
*/
angularFormatter.trim = formatter(
function(obj) { return obj ? trim("" + obj) : ""; }
);
/**
* @workInProgress
* @ngdoc overview
* @name angular.validator
* @description
*
* Most of the built-in angular validators are used to check user input against defined types or
* patterns. You can easily create your own custom validators as well.
*
* Following is the list of built-in angular validators:
*
* * {@link angular.validator.asynchronous asynchronous()} - Provides asynchronous validation via a
* callback function.
* * {@link angular.validator.date date()} - Checks user input against default date format:
* "MM/DD/YYYY"
* * {@link angular.validator.email email()} - Validates that user input is a well-formed email
* address.
* * {@link angular.validator.integer integer()} - Validates that user input is an integer
* * {@link angular.validator.json json()} - Validates that user input is valid JSON
* * {@link angular.validator.number number()} - Validates that user input is a number
* * {@link angular.validator.phone phone()} - Validates that user input matches the pattern
* "1(123)123-1234"
* * {@link angular.validator.regexp regexp()} - Restricts valid input to a specified regular
* expression pattern
* * {@link angular.validator.url url()} - Validates that user input is a well-formed URL.
*
* For more information about how angular validators work, and how to create your own validators,
* see {@link guide/dev_guide.templates.validators Understanding Angular Validators} in the angular
* Developer Guide.
*/
extend(angularValidator, {
'noop': function() { return null; },
/**
* @workInProgress
* @ngdoc validator
* @name angular.validator.regexp
* @description
* Use regexp validator to restrict the input to any Regular Expression.
*
* @param {string} value value to validate
* @param {string|regexp} expression regular expression.
* @param {string=} msg error message to display.
* @css ng-validation-error
*
* @example
<doc:example>
<doc:source>
<script> function Cntl(){
this.ssnRegExp = /^\d\d\d-\d\d-\d\d\d\d$/;
}
</script>
Enter valid SSN:
<div ng:controller="Cntl">
<input name="ssn" value="123-45-6789" ng:validate="regexp:ssnRegExp" >
</div>
</doc:source>
<doc:scenario>
it('should invalidate non ssn', function(){
var textBox = element('.doc-example-live :input');
expect(textBox.prop('className')).not().toMatch(/ng-validation-error/);
expect(textBox.val()).toEqual('123-45-6789');
input('ssn').enter('123-45-67890');
expect(textBox.prop('className')).toMatch(/ng-validation-error/);
});
</doc:scenario>
</doc:example>
*
*/
'regexp': function(value, regexp, msg) {
if (!value.match(regexp)) {
return msg ||
"Value does not match expected format " + regexp + ".";
} else {
return null;
}
},
/**
* @workInProgress
* @ngdoc validator
* @name angular.validator.number
* @description
* Use number validator to restrict the input to numbers with an
* optional range. (See integer for whole numbers validator).
*
* @param {string} value value to validate
* @param {int=} [min=MIN_INT] minimum value.
* @param {int=} [max=MAX_INT] maximum value.
* @css ng-validation-error
*
* @example
<doc:example>
<doc:source>
Enter number: <input name="n1" ng:validate="number" > <br>
Enter number greater than 10: <input name="n2" ng:validate="number:10" > <br>
Enter number between 100 and 200: <input name="n3" ng:validate="number:100:200" > <br>
</doc:source>
<doc:scenario>
it('should invalidate number', function(){
var n1 = element('.doc-example-live :input[name=n1]');
expect(n1.prop('className')).not().toMatch(/ng-validation-error/);
input('n1').enter('1.x');
expect(n1.prop('className')).toMatch(/ng-validation-error/);
var n2 = element('.doc-example-live :input[name=n2]');
expect(n2.prop('className')).not().toMatch(/ng-validation-error/);
input('n2').enter('9');
expect(n2.prop('className')).toMatch(/ng-validation-error/);
var n3 = element('.doc-example-live :input[name=n3]');
expect(n3.prop('className')).not().toMatch(/ng-validation-error/);
input('n3').enter('201');
expect(n3.prop('className')).toMatch(/ng-validation-error/);
});
</doc:scenario>
</doc:example>
*
*/
'number': function(value, min, max) {
var num = 1 * value;
if (num == value) {
if (typeof min != $undefined && num < min) {
return "Value can not be less than " + min + ".";
}
if (typeof min != $undefined && num > max) {
return "Value can not be greater than " + max + ".";
}
return null;
} else {
return "Not a number";
}
},
/**
* @workInProgress
* @ngdoc validator
* @name angular.validator.integer
* @description
* Use number validator to restrict the input to integers with an
* optional range. (See integer for whole numbers validator).
*
* @param {string} value value to validate
* @param {int=} [min=MIN_INT] minimum value.
* @param {int=} [max=MAX_INT] maximum value.
* @css ng-validation-error
*
* @example
<doc:example>
<doc:source>
Enter integer: <input name="n1" ng:validate="integer" > <br>
Enter integer equal or greater than 10: <input name="n2" ng:validate="integer:10" > <br>
Enter integer between 100 and 200 (inclusive): <input name="n3" ng:validate="integer:100:200" > <br>
</doc:source>
<doc:scenario>
it('should invalidate integer', function(){
var n1 = element('.doc-example-live :input[name=n1]');
expect(n1.prop('className')).not().toMatch(/ng-validation-error/);
input('n1').enter('1.1');
expect(n1.prop('className')).toMatch(/ng-validation-error/);
var n2 = element('.doc-example-live :input[name=n2]');
expect(n2.prop('className')).not().toMatch(/ng-validation-error/);
input('n2').enter('10.1');
expect(n2.prop('className')).toMatch(/ng-validation-error/);
var n3 = element('.doc-example-live :input[name=n3]');
expect(n3.prop('className')).not().toMatch(/ng-validation-error/);
input('n3').enter('100.1');
expect(n3.prop('className')).toMatch(/ng-validation-error/);
});
</doc:scenario>
</doc:example>
*/
'integer': function(value, min, max) {
var numberError = angularValidator['number'](value, min, max);
if (numberError) return numberError;
if (!("" + value).match(/^\s*[\d+]*\s*$/) || value != Math.round(value)) {
return "Not a whole number";
}
return null;
},
/**
* @workInProgress
* @ngdoc validator
* @name angular.validator.date
* @description
* Use date validator to restrict the user input to a valid date
* in format in format MM/DD/YYYY.
*
* @param {string} value value to validate
* @css ng-validation-error
*
* @example
<doc:example>
<doc:source>
Enter valid date:
<input name="text" value="1/1/2009" ng:validate="date" >
</doc:source>
<doc:scenario>
it('should invalidate date', function(){
var n1 = element('.doc-example-live :input');
expect(n1.prop('className')).not().toMatch(/ng-validation-error/);
input('text').enter('123/123/123');
expect(n1.prop('className')).toMatch(/ng-validation-error/);
});
</doc:scenario>
</doc:example>
*
*/
'date': function(value) {
var fields = /^(\d\d?)\/(\d\d?)\/(\d\d\d\d)$/.exec(value);
var date = fields ? new Date(fields[3], fields[1]-1, fields[2]) : 0;
return (date &&
date.getFullYear() == fields[3] &&
date.getMonth() == fields[1]-1 &&
date.getDate() == fields[2])
? null
: "Value is not a date. (Expecting format: 12/31/2009).";
},
/**
* @workInProgress
* @ngdoc validator
* @name angular.validator.email
* @description
* Use email validator if you wist to restrict the user input to a valid email.
*
* @param {string} value value to validate
* @css ng-validation-error
*
* @example
<doc:example>
<doc:source>
Enter valid email:
<input name="text" ng:validate="email" value="me@example.com">
</doc:source>
<doc:scenario>
it('should invalidate email', function(){
var n1 = element('.doc-example-live :input');
expect(n1.prop('className')).not().toMatch(/ng-validation-error/);
input('text').enter('a@b.c');
expect(n1.prop('className')).toMatch(/ng-validation-error/);
});
</doc:scenario>
</doc:example>
*
*/
'email': function(value) {
if (value.match(/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/)) {
return null;
}
return "Email needs to be in username@host.com format.";
},
/**
* @workInProgress
* @ngdoc validator
* @name angular.validator.phone
* @description
* Use phone validator to restrict the input phone numbers.
*
* @param {string} value value to validate
* @css ng-validation-error
*
* @example
<doc:example>
<doc:source>
Enter valid phone number:
<input name="text" value="1(234)567-8901" ng:validate="phone" >
</doc:source>
<doc:scenario>
it('should invalidate phone', function(){
var n1 = element('.doc-example-live :input');
expect(n1.prop('className')).not().toMatch(/ng-validation-error/);
input('text').enter('+12345678');
expect(n1.prop('className')).toMatch(/ng-validation-error/);
});
</doc:scenario>
</doc:example>
*
*/
'phone': function(value) {
if (value.match(/^1\(\d\d\d\)\d\d\d-\d\d\d\d$/)) {
return null;
}
if (value.match(/^\+\d{2,3} (\(\d{1,5}\))?[\d ]+\d$/)) {
return null;
}
return "Phone number needs to be in 1(987)654-3210 format in North America " +
"or +999 (123) 45678 906 internationally.";
},
/**
* @workInProgress
* @ngdoc validator
* @name angular.validator.url
* @description
* Use phone validator to restrict the input URLs.
*
* @param {string} value value to validate
* @css ng-validation-error
*
* @example
<doc:example>
<doc:source>
Enter valid URL:
<input name="text" value="http://example.com/abc.html" size="40" ng:validate="url" >
</doc:source>
<doc:scenario>
it('should invalidate url', function(){
var n1 = element('.doc-example-live :input');
expect(n1.prop('className')).not().toMatch(/ng-validation-error/);
input('text').enter('abc://server/path');
expect(n1.prop('className')).toMatch(/ng-validation-error/);
});
</doc:scenario>
</doc:example>
*
*/
'url': function(value) {
if (value.match(/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/)) {
return null;
}
return "URL needs to be in http://server[:port]/path format.";
},
/**
* @workInProgress
* @ngdoc validator
* @name angular.validator.json
* @description
* Use json validator if you wish to restrict the user input to a valid JSON.
*
* @param {string} value value to validate
* @css ng-validation-error
*
* @example
<doc:example>
<doc:source>
<textarea name="json" cols="60" rows="5" ng:validate="json">
{name:'abc'}
</textarea>
</doc:source>
<doc:scenario>
it('should invalidate json', function(){
var n1 = element('.doc-example-live :input');
expect(n1.prop('className')).not().toMatch(/ng-validation-error/);
input('json').enter('{name}');
expect(n1.prop('className')).toMatch(/ng-validation-error/);
});
</doc:scenario>
</doc:example>
*
*/
'json': function(value) {
try {
fromJson(value);
return null;
} catch (e) {
return e.toString();
}
},
/**
* @workInProgress
* @ngdoc validator
* @name angular.validator.asynchronous
* @description
* Use asynchronous validator if the validation can not be computed
* immediately, but is provided through a callback. The widget
* automatically shows a spinning indicator while the validity of
* the widget is computed. This validator caches the result.
*
* @param {string} value value to validate
* @param {function(inputToValidate,validationDone)} validate function to call to validate the state
* of the input.
* @param {function(data)=} [update=noop] function to call when state of the
* validator changes
*
* @paramDescription
* The `validate` function (specified by you) is called as
* `validate(inputToValidate, validationDone)`:
*
* * `inputToValidate`: value of the input box.
* * `validationDone`: `function(error, data){...}`
* * `error`: error text to display if validation fails
* * `data`: data object to pass to update function
*
* The `update` function is optionally specified by you and is
* called by <angular/> on input change. Since the
* asynchronous validator caches the results, the update
* function can be called without a call to `validate`
* function. The function is called as `update(data)`:
*
* * `data`: data object as passed from validate function
*
* @css ng-input-indicator-wait, ng-validation-error
*
* @example
<doc:example>
<doc:source>
<script>
function MyCntl(){
this.myValidator = function (inputToValidate, validationDone) {
setTimeout(function(){
validationDone(inputToValidate.length % 2);
}, 500);
}
}
</script>
This input is validated asynchronously:
<div ng:controller="MyCntl">
<input name="text" ng:validate="asynchronous:myValidator">
</div>
</doc:source>
<doc:scenario>
it('should change color in delayed way', function(){
var textBox = element('.doc-example-live :input');
expect(textBox.prop('className')).not().toMatch(/ng-input-indicator-wait/);
expect(textBox.prop('className')).not().toMatch(/ng-validation-error/);
input('text').enter('X');
expect(textBox.prop('className')).toMatch(/ng-input-indicator-wait/);
sleep(.6);
expect(textBox.prop('className')).not().toMatch(/ng-input-indicator-wait/);
expect(textBox.prop('className')).toMatch(/ng-validation-error/);
});
</doc:scenario>
</doc:example>
*
*/
/*
* cache is attached to the element
* cache: {
* inputs : {
* 'user input': {
* response: server response,
* error: validation error
* },
* current: 'current input'
* }
* }
*
*/
'asynchronous': function(input, asynchronousFn, updateFn) {
if (!input) return;
var scope = this;
var element = scope.$element;
var cache = element.data('$asyncValidator');
if (!cache) {
element.data('$asyncValidator', cache = {inputs:{}});
}
cache.current = input;
var inputState = cache.inputs[input],
$invalidWidgets = scope.$service('$invalidWidgets');
if (!inputState) {
cache.inputs[input] = inputState = { inFlight: true };
$invalidWidgets.markInvalid(scope.$element);
element.addClass('ng-input-indicator-wait');
asynchronousFn(input, function(error, data) {
inputState.response = data;
inputState.error = error;
inputState.inFlight = false;
if (cache.current == input) {
element.removeClass('ng-input-indicator-wait');
$invalidWidgets.markValid(element);
}
element.data($$validate)();
});
} else if (inputState.inFlight) {
// request in flight, mark widget invalid, but don't show it to user
$invalidWidgets.markInvalid(scope.$element);
} else {
(updateFn||noop)(inputState.response);
}
return inputState.error;
}
});
/**
* @workInProgress
* @ngdoc service
* @name angular.service.$cookieStore
* @requires $cookies
*
* @description
* Provides a key-value (string-object) storage, that is backed by session cookies.
* Objects put or retrieved from this storage are automatically serialized or
* deserialized by angular's toJson/fromJson.
* @example
*/
angularServiceInject('$cookieStore', function($store) {
return {
/**
* @workInProgress
* @ngdoc method
* @name angular.service.$cookieStore#get
* @methodOf angular.service.$cookieStore
*
* @description
* Returns the value of given cookie key
*
* @param {string} key Id to use for lookup.
* @returns {Object} Deserialized cookie value.
*/
get: function(key) {
return fromJson($store[key]);
},
/**
* @workInProgress
* @ngdoc method
* @name angular.service.$cookieStore#put
* @methodOf angular.service.$cookieStore
*
* @description
* Sets a value for given cookie key
*
* @param {string} key Id for the `value`.
* @param {Object} value Value to be stored.
*/
put: function(key, value) {
$store[key] = toJson(value);
},
/**
* @workInProgress
* @ngdoc method
* @name angular.service.$cookieStore#remove
* @methodOf angular.service.$cookieStore
*
* @description
* Remove given cookie
*
* @param {string} key Id of the key-value pair to delete.
*/
remove: function(key) {
delete $store[key];
}
};
}, ['$cookies']);
/**
* @workInProgress
* @ngdoc service
* @name angular.service.$cookies
* @requires $browser
*
* @description
* Provides read/write access to browser's cookies.
*
* Only a simple Object is exposed and by adding or removing properties to/from
* this object, new cookies are created/deleted at the end of current $eval.
*
* @example
*/
angularServiceInject('$cookies', function($browser) {
var rootScope = this,
cookies = {},
lastCookies = {},
lastBrowserCookies,
runEval = false;
//creates a poller fn that copies all cookies from the $browser to service & inits the service
$browser.addPollFn(function() {
var currentCookies = $browser.cookies();
if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl
lastBrowserCookies = currentCookies;
copy(currentCookies, lastCookies);
copy(currentCookies, cookies);
if (runEval) rootScope.$apply();
}
})();
runEval = true;
//at the end of each eval, push cookies
//TODO: this should happen before the "delayed" watches fire, because if some cookies are not
// strings or browser refuses to store some cookies, we update the model in the push fn.
this.$watch(push);
return cookies;
/**
* Pushes all the cookies from the service to the browser and verifies if all cookies were stored.
*/
function push(){
var name,
value,
browserCookies,
updated;
//delete any cookies deleted in $cookies
for (name in lastCookies) {
if (isUndefined(cookies[name])) {
$browser.cookies(name, undefined);
}
}
//update all cookies updated in $cookies
for(name in cookies) {
value = cookies[name];
if (!isString(value)) {
if (isDefined(lastCookies[name])) {
cookies[name] = lastCookies[name];
} else {
delete cookies[name];
}
} else if (value !== lastCookies[name]) {
$browser.cookies(name, value);
updated = true;
}
}
//verify what was actually stored
if (updated){
updated = false;
browserCookies = $browser.cookies();
for (name in cookies) {
if (cookies[name] !== browserCookies[name]) {
//delete or reset all cookies that the browser dropped from $cookies
if (isUndefined(browserCookies[name])) {
delete cookies[name];
} else {
cookies[name] = browserCookies[name];
}
updated = true;
}
}
}
}
}, ['$browser']);
/**
* @workInProgress
* @ngdoc service
* @name angular.service.$defer
* @requires $browser
*
* @description
* Delegates to {@link angular.service.$browser $browser.defer}, but wraps the `fn` function
* into a try/catch block and delegates any exceptions to
* {@link angular.service.$exceptionHandler $exceptionHandler} service.
*
* In tests you can use `$browser.defer.flush()` to flush the queue of deferred functions.
*
* @param {function()} fn A function, who's execution should be deferred.
* @param {number=} [delay=0] of milliseconds to defer the function execution.
*/
angularServiceInject('$defer', function($browser) {
var scope = this;
return function(fn, delay) {
$browser.defer(function() {
scope.$apply(fn);
}, delay);
};
}, ['$browser']);
/**
* @workInProgress
* @ngdoc service
* @name angular.service.$document
* @requires $window
*
* @description
* A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document`
* element.
*/
angularServiceInject("$document", function(window){
return jqLite(window.document);
}, ['$window']);
/**
* @workInProgress
* @ngdoc service
* @name angular.service.$exceptionHandler
* @requires $log
*
* @description
* Any uncaught exception in angular expressions is delegated to this service.
* The default implementation simply delegates to `$log.error` which logs it into
* the browser console.
*
* In unit tests, if `angular-mocks.js` is loaded, this service is overriden by
* {@link angular.mock.service.$exceptionHandler mock $exceptionHandler}
*
* @example
*/
var $exceptionHandlerFactory; //reference to be used only in tests
angularServiceInject('$exceptionHandler', $exceptionHandlerFactory = function($log){
return function(e) {
$log.error(e);
};
}, ['$log']);
/**
* @workInProgress
* @ngdoc service
* @name angular.service.$hover
* @requires $browser
* @requires $document
*
* @description
*
* @example
*/
angularServiceInject("$hover", function(browser, document) {
var tooltip, self = this, error, width = 300, arrowWidth = 10, body = jqLite(document[0].body);
browser.hover(function(element, show){
if (show && (error = element.attr(NG_EXCEPTION) || element.attr(NG_VALIDATION_ERROR))) {
if (!tooltip) {
tooltip = {
callout: jqLite('<div id="ng-callout"></div>'),
arrow: jqLite('<div></div>'),
title: jqLite('<div class="ng-title"></div>'),
content: jqLite('<div class="ng-content"></div>')
};
tooltip.callout.append(tooltip.arrow);
tooltip.callout.append(tooltip.title);
tooltip.callout.append(tooltip.content);
body.append(tooltip.callout);
}
var docRect = body[0].getBoundingClientRect(),
elementRect = element[0].getBoundingClientRect(),
leftSpace = docRect.right - elementRect.right - arrowWidth;
tooltip.title.text(element.hasClass("ng-exception") ? "EXCEPTION:" : "Validation error...");
tooltip.content.text(error);
if (leftSpace < width) {
tooltip.arrow.addClass('ng-arrow-right');
tooltip.arrow.css({left: (width + 1)+'px'});
tooltip.callout.css({
position: 'fixed',
left: (elementRect.left - arrowWidth - width - 4) + "px",
top: (elementRect.top - 3) + "px",
width: width + "px"
});
} else {
tooltip.arrow.addClass('ng-arrow-left');
tooltip.callout.css({
position: 'fixed',
left: (elementRect.right + arrowWidth) + "px",
top: (elementRect.top - 3) + "px",
width: width + "px"
});
}
} else if (tooltip) {
tooltip.callout.remove();
tooltip = null;
}
});
}, ['$browser', '$document'], true);
/**
* @workInProgress
* @ngdoc service
* @name angular.service.$invalidWidgets
*
* @description
* Keeps references to all invalid widgets found during validation.
* Can be queried to find whether there are any invalid widgets currently displayed.
*
* @example
*/
angularServiceInject("$invalidWidgets", function(){
var invalidWidgets = [];
/** Remove an element from the array of invalid widgets */
invalidWidgets.markValid = function(element){
var index = indexOf(invalidWidgets, element);
if (index != -1)
invalidWidgets.splice(index, 1);
};
/** Add an element to the array of invalid widgets */
invalidWidgets.markInvalid = function(element){
var index = indexOf(invalidWidgets, element);
if (index === -1)
invalidWidgets.push(element);
};
/** Return count of all invalid widgets that are currently visible */
invalidWidgets.visible = function() {
var count = 0;
forEach(invalidWidgets, function(widget){
count = count + (isVisible(widget) ? 1 : 0);
});
return count;
};
/* At the end of each eval removes all invalid widgets that are not part of the current DOM. */
this.$watch(function() {
for(var i = 0; i < invalidWidgets.length;) {
var widget = invalidWidgets[i];
if (isOrphan(widget[0])) {
invalidWidgets.splice(i, 1);
if (widget.dealoc) widget.dealoc();
} else {
i++;
}
}
});
/**
* Traverses DOM element's (widget's) parents and considers the element to be an orphan if one of
* it's parents isn't the current window.document.
*/
function isOrphan(widget) {
if (widget == window.document) return false;
var parent = widget.parentNode;
return !parent || isOrphan(parent);
}
return invalidWidgets;
});
var URL_MATCH = /^(file|ftp|http|https):\/\/(\w+:{0,1}\w*@)?([\w\.-]*)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/,
PATH_MATCH = /^([^\?#]*)?(\?([^#]*))?(#(.*))?$/,
HASH_MATCH = PATH_MATCH,
DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
/**
* Encode path using encodeUriSegment, ignoring forward slashes
*
* @param {string} path Path to encode
* @returns {string}
*/
function encodePath(path) {
var segments = path.split('/'),
i = segments.length;
while (i--) {
segments[i] = encodeUriSegment(segments[i]);
}
return segments.join('/');
}
function matchUrl(url, obj) {
var match = URL_MATCH.exec(url),
match = {
protocol: match[1],
host: match[3],
port: parseInt(match[5]) || DEFAULT_PORTS[match[1]] || null,
path: match[6] || '/',
search: match[8],
hash: match[10]
};
if (obj) {
obj.$$protocol = match.protocol;
obj.$$host = match.host;
obj.$$port = match.port;
}
return match;
}
function composeProtocolHostPort(protocol, host, port) {
return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' : ':' + port);
}
function pathPrefixFromBase(basePath) {
return basePath.substr(0, basePath.lastIndexOf('/'));
}
function convertToHtml5Url(url, basePath, hashPrefix) {
var match = matchUrl(url);
// already html5 url
if (decodeURIComponent(match.path) != basePath || isUndefined(match.hash) ||
match.hash.indexOf(hashPrefix) != 0) {
return url;
// convert hashbang url -> html5 url
} else {
return composeProtocolHostPort(match.protocol, match.host, match.port) +
pathPrefixFromBase(basePath) + match.hash.substr(hashPrefix.length);
}
}
function convertToHashbangUrl(url, basePath, hashPrefix) {
var match = matchUrl(url);
// already hashbang url
if (decodeURIComponent(match.path) == basePath) {
return url;
// convert html5 url -> hashbang url
} else {
var search = match.search && '?' + match.search || '',
hash = match.hash && '#' + match.hash || '',
pathPrefix = pathPrefixFromBase(basePath),
path = match.path.substr(pathPrefix.length);
if (match.path.indexOf(pathPrefix) != 0) {
throw 'Invalid url "' + url + '", missing path prefix "' + pathPrefix + '" !';
}
return composeProtocolHostPort(match.protocol, match.host, match.port) + basePath +
'#' + hashPrefix + path + search + hash;
}
}
/**
* LocationUrl represents an url
* This object is exposed as $location service when html5 is enabled and supported
*
* @constructor
* @param {string} url Html5 url
* @param {string} pathPrefix
*/
function LocationUrl(url, pathPrefix) {
pathPrefix = pathPrefix || '';
/**
* Parse given html5 (regular) url string into properties
* @param {string} url Html5 url
* @private
*/
this.$$parse = function(url) {
var match = matchUrl(url, this);
if (match.path.indexOf(pathPrefix) != 0) {
throw 'Invalid url "' + url + '", missing path prefix "' + pathPrefix + '" !';
}
this.$$path = decodeURIComponent(match.path.substr(pathPrefix.length));
this.$$search = parseKeyValue(match.search);
this.$$hash = match.hash && decodeURIComponent(match.hash) || '';
this.$$compose();
},
/**
* Compose url and update `absUrl` property
* @private
*/
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) +
pathPrefix + this.$$url;
};
this.$$parse(url);
}
/**
* LocationHashbangUrl represents url
* This object is exposed as $location service when html5 history api is disabled or not supported
*
* @constructor
* @param {string} url Legacy url
* @param {string} hashPrefix Prefix for hash part (containing path and search)
*/
function LocationHashbangUrl(url, hashPrefix) {
var basePath;
/**
* Parse given hashbang url into properties
* @param {string} url Hashbang url
* @private
*/
this.$$parse = function(url) {
var match = matchUrl(url, this);
if (match.hash && match.hash.indexOf(hashPrefix) != 0) {
throw 'Invalid url "' + url + '", missing hash prefix "' + hashPrefix + '" !';
}
basePath = match.path + (match.search ? '?' + match.search : '');
match = HASH_MATCH.exec((match.hash || '').substr(hashPrefix.length));
if (match[1]) {
this.$$path = (match[1].charAt(0) == '/' ? '' : '/') + decodeURIComponent(match[1]);
} else {
this.$$path = '';
}
this.$$search = parseKeyValue(match[3]);
this.$$hash = match[5] && decodeURIComponent(match[5]) || '';
this.$$compose();
};
/**
* Compose hashbang url and update `absUrl` property
* @private
*/
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) +
basePath + (this.$$url ? '#' + hashPrefix + this.$$url : '');
};
this.$$parse(url);
}
LocationUrl.prototype = LocationHashbangUrl.prototype = {
/**
* Has any change been replacing ?
* @private
*/
$$replace: false,
/**
* @ngdoc method
* @name angular.service.$location#absUrl
* @methodOf angular.service.$location
*
* @description
* This method is getter only.
*
* Return full url representation with all segments encoded according to rules specified in
* {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}.
*
* @return {string}
*/
absUrl: locationGetter('$$absUrl'),
/**
* @ngdoc method
* @name angular.service.$location#url
* @methodOf angular.service.$location
*
* @description
* This method is getter / setter.
*
* Return url (e.g. `/path?a=b#hash`) when called without any parameter.
*
* Change path, search and hash, when called with parameter and return `$location`.
*
* @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
* @return {string}
*/
url: function(url, replace) {
if (isUndefined(url))
return this.$$url;
var match = PATH_MATCH.exec(url);
this.path(decodeURIComponent(match[1] || '')).search(match[3] || '')
.hash(match[5] || '', replace);
return this;
},
/**
* @ngdoc method
* @name angular.service.$location#protocol
* @methodOf angular.service.$location
*
* @description
* This method is getter only.
*
* Return protocol of current url.
*
* @return {string}
*/
protocol: locationGetter('$$protocol'),
/**
* @ngdoc method
* @name angular.service.$location#host
* @methodOf angular.service.$location
*
* @description
* This method is getter only.
*
* Return host of current url.
*
* @return {string}
*/
host: locationGetter('$$host'),
/**
* @ngdoc method
* @name angular.service.$location#port
* @methodOf angular.service.$location
*
* @description
* This method is getter only.
*
* Return port of current url.
*
* @return {Number}
*/
port: locationGetter('$$port'),
/**
* @ngdoc method
* @name angular.service.$location#path
* @methodOf angular.service.$location
*
* @description
* This method is getter / setter.
*
* Return path of current url when called without any parameter.
*
* Change path when called with parameter and return `$location`.
*
* Note: Path should always begin with forward slash (/), this method will add the forward slash
* if it is missing.
*
* @param {string=} path New path
* @return {string}
*/
path: locationGetterSetter('$$path', function(path) {
return path.charAt(0) == '/' ? path : '/' + path;
}),
/**
* @ngdoc method
* @name angular.service.$location#search
* @methodOf angular.service.$location
*
* @description
* This method is getter / setter.
*
* Return search part (as object) of current url when called without any parameter.
*
* Change search part when called with parameter and return `$location`.
*
* @param {string|object<string,string>=} search New search part - string or hash object
* @return {string}
*/
search: function(search, paramValue) {
if (isUndefined(search))
return this.$$search;
if (isDefined(paramValue)) {
if (paramValue === null) {
delete this.$$search[search];
} else {
this.$$search[search] = encodeUriQuery(paramValue);
}
} else {
this.$$search = isString(search) ? parseKeyValue(search) : search;
}
this.$$compose();
return this;
},
/**
* @ngdoc method
* @name angular.service.$location#hash
* @methodOf angular.service.$location
*
* @description
* This method is getter / setter.
*
* Return hash fragment when called without any parameter.
*
* Change hash fragment when called with parameter and return `$location`.
*
* @param {string=} hash New hash fragment
* @return {string}
*/
hash: locationGetterSetter('$$hash', identity),
/**
* @ngdoc method
* @name angular.service.$location#replace
* @methodOf angular.service.$location
*
* @description
* If called, all changes to $location during current `$digest` will be replacing current history
* record, instead of adding new one.
*/
replace: function() {
this.$$replace = true;
return this;
}
};
function locationGetter(property) {
return function() {
return this[property];
};
}
function locationGetterSetter(property, preprocess) {
return function(value) {
if (isUndefined(value))
return this[property];
this[property] = preprocess(value);
this.$$compose();
return this;
};
}
/**
* @ngdoc service
* @name angular.service.$location
*
* @requires $browser
* @requires $sniffer
* @requires $config
* @requires $document
*
* @description
* The $location service parses the URL in the browser address bar (based on the {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL available to your application. Changes to the URL in the address bar are reflected into $location service and changes to $location are reflected into the browser address bar.
*
* **The $location service:**
*
* - Exposes the current URL in the browser address bar, so you can
* - Watch and observe the URL.
* - Change the URL.
* - Synchronizes the URL with the browser when the user
* - Changes the address bar.
* - Clicks the back or forward button (or clicks a History link).
* - Clicks on a link.
* - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
*
* For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular Services: Using $location}
*/
angularServiceInject('$location', function($browser, $sniffer, $config, $document) {
var scope = this, currentUrl,
basePath = $browser.baseHref() || '/',
pathPrefix = pathPrefixFromBase(basePath),
hashPrefix = $config.hashPrefix || '',
initUrl = $browser.url();
if ($config.html5Mode) {
if ($sniffer.history) {
currentUrl = new LocationUrl(convertToHtml5Url(initUrl, basePath, hashPrefix), pathPrefix);
} else {
currentUrl = new LocationHashbangUrl(convertToHashbangUrl(initUrl, basePath, hashPrefix),
hashPrefix);
}
// link rewriting
var u = currentUrl,
absUrlPrefix = composeProtocolHostPort(u.protocol(), u.host(), u.port()) + pathPrefix;
$document.bind('click', function(event) {
// TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
// currently we open nice url link and redirect then
if (uppercase(event.target.nodeName) != 'A' || event.ctrlKey || event.which == 2) return;
var elm = jqLite(event.target),
href = elm.attr('href');
if (!href || isDefined(elm.attr('ng:ext-link')) || elm.attr('target')) return;
// remove same domain from full url links (IE7 always returns full hrefs)
href = href.replace(absUrlPrefix, '');
// link to different domain (or base path)
if (href.substr(0, 4) == 'http') return;
// remove pathPrefix from absolute links
href = href.indexOf(pathPrefix) === 0 ? href.substr(pathPrefix.length) : href;
currentUrl.url(href);
scope.$apply();
event.preventDefault();
// hack to work around FF6 bug 684208 when scenario runner clicks on links
window.angular['ff-684208-preventDefault'] = true;
});
} else {
currentUrl = new LocationHashbangUrl(initUrl, hashPrefix);
}
// rewrite hashbang url <> html5 url
if (currentUrl.absUrl() != initUrl) {
$browser.url(currentUrl.absUrl(), true);
}
// update $location when $browser url changes
$browser.onUrlChange(function(newUrl) {
if (currentUrl.absUrl() != newUrl) {
currentUrl.$$parse(newUrl);
scope.$apply();
}
});
// update browser
var changeCounter = 0;
scope.$watch(function() {
if ($browser.url() != currentUrl.absUrl()) {
changeCounter++;
scope.$evalAsync(function() {
$browser.url(currentUrl.absUrl(), currentUrl.$$replace);
currentUrl.$$replace = false;
});
}
return changeCounter;
});
return currentUrl;
}, ['$browser', '$sniffer', '$locationConfig', '$document']);
angular.service('$locationConfig', function() {
return {
html5Mode: false,
hashPrefix: ''
};
});
/**
* @workInProgress
* @ngdoc service
* @name angular.service.$log
* @requires $window
*
* @description
* Simple service for logging. Default implementation writes the message
* into the browser's console (if present).
*
* The main purpose of this service is to simplify debugging and troubleshooting.
*
* @example
<doc:example>
<doc:source>
<script>
function LogCtrl($log) {
this.$log = $log;
}
</script>
<div ng:controller="LogCtrl">
<p>Reload this page with open console, enter text and hit the log button...</p>
Message:
<input type="text" name="message" value="Hello World!"/>
<button ng:click="$log.log(message)">log</button>
<button ng:click="$log.warn(message)">warn</button>
<button ng:click="$log.info(message)">info</button>
<button ng:click="$log.error(message)">error</button>
</div>
</doc:source>
<doc:scenario>
</doc:scenario>
</doc:example>
*/
var $logFactory; //reference to be used only in tests
angularServiceInject("$log", $logFactory = function($window){
return {
/**
* @workInProgress
* @ngdoc method
* @name angular.service.$log#log
* @methodOf angular.service.$log
*
* @description
* Write a log message
*/
log: consoleLog('log'),
/**
* @workInProgress
* @ngdoc method
* @name angular.service.$log#warn
* @methodOf angular.service.$log
*
* @description
* Write a warning message
*/
warn: consoleLog('warn'),
/**
* @workInProgress
* @ngdoc method
* @name angular.service.$log#info
* @methodOf angular.service.$log
*
* @description
* Write an information message
*/
info: consoleLog('info'),
/**
* @workInProgress
* @ngdoc method
* @name angular.service.$log#error
* @methodOf angular.service.$log
*
* @description
* Write an error message
*/
error: consoleLog('error')
};
function consoleLog(type) {
var console = $window.console || {};
var logFn = console[type] || console.log || noop;
if (logFn.apply) {
return function(){
var args = [];
forEach(arguments, function(arg){
args.push(formatError(arg));
});
return logFn.apply(console, args);
};
} else {
// we are IE, in which case there is nothing we can do
return logFn;
}
}
}, ['$window']);
/**
* @workInProgress
* @ngdoc service
* @name angular.service.$resource
* @requires $xhr.cache
*
* @description
* A factory which creates a resource object that lets you interact with
* [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources.
*
* The returned resource object has action methods which provide high-level behaviors without
* the need to interact with the low level {@link angular.service.$xhr $xhr} service or
* raw XMLHttpRequest.
*
* @param {string} url A parameterized URL template with parameters prefixed by `:` as in
* `/user/:username`.
*
* @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in
* `actions` methods.
*
* Each key value in the parameter object is first bound to url template if present and then any
* excess keys are appended to the url search query after the `?`.
*
* Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in
* URL `/path/greet?salutation=Hello`.
*
* If the parameter value is prefixed with `@` then the value of that parameter is extracted from
* the data object (useful for non-GET operations).
*
* @param {Object.<Object>=} actions Hash with declaration of custom action that should extend the
* default set of resource actions. The declaration should be created in the following format:
*
* {action1: {method:?, params:?, isArray:?, verifyCache:?},
* action2: {method:?, params:?, isArray:?, verifyCache:?},
* ...}
*
* Where:
*
* - `action` – {string} – The name of action. This name becomes the name of the method on your
* resource object.
* - `method` – {string} – HTTP request method. Valid methods are: `GET`, `POST`, `PUT`, `DELETE`,
* and `JSON` (also known as JSONP).
* - `params` – {object=} – Optional set of pre-bound parameters for this action.
* - isArray – {boolean=} – If true then the returned object for this action is an array, see
* `returns` section.
* - verifyCache – {boolean=} – If true then whenever cache hit occurs, the object is returned and
* an async request will be made to the server and the resources as well as the cache will be
* updated when the response is received.
*
* @returns {Object} A resource "class" object with methods for the default set of resource actions
* optionally extended with custom `actions`. The default set contains these actions:
*
* { 'get': {method:'GET'},
* 'save': {method:'POST'},
* 'query': {method:'GET', isArray:true},
* 'remove': {method:'DELETE'},
* 'delete': {method:'DELETE'} };
*
* Calling these methods invoke an {@link angular.service.$xhr} with the specified http method,
* destination and parameters. When the data is returned from the server then the object is an
* instance of the resource class `save`, `remove` and `delete` actions are available on it as
* methods with the `$` prefix. This allows you to easily perform CRUD operations (create, read,
* update, delete) on server-side data like this:
* <pre>
var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function(){
user.abc = true;
user.$save();
});
</pre>
*
* It is important to realize that invoking a $resource object method immediately returns an
* empty reference (object or array depending on `isArray`). Once the data is returned from the
* server the existing reference is populated with the actual data. This is a useful trick since
* usually the resource is assigned to a model which is then rendered by the view. Having an empty
* object results in no rendering, once the data arrives from the server then the object is
* populated with the data and the view automatically re-renders itself showing the new data. This
* means that in most case one never has to write a callback function for the action methods.
*
* The action methods on the class object or instance object can be invoked with the following
* parameters:
*
* - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])`
* - non-GET "class" actions: `Resource.action(postData, [parameters], [success], [error])`
* - non-GET instance actions: `instance.$action([parameters], [success], [error])`
*
*
* @example
*
* # Credit card resource
*
* <pre>
// Define CreditCard class
var CreditCard = $resource('/user/:userId/card/:cardId',
{userId:123, cardId:'@id'}, {
charge: {method:'POST', params:{charge:true}}
});
// We can retrieve a collection from the server
var cards = CreditCard.query();
// GET: /user/123/card
// server returns: [ {id:456, number:'1234', name:'Smith'} ];
var card = cards[0];
// each item is an instance of CreditCard
expect(card instanceof CreditCard).toEqual(true);
card.name = "J. Smith";
// non GET methods are mapped onto the instances
card.$save();
// POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
// server returns: {id:456, number:'1234', name: 'J. Smith'};
// our custom method is mapped as well.
card.$charge({amount:9.99});
// POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
// server returns: {id:456, number:'1234', name: 'J. Smith'};
// we can create an instance as well
var newCard = new CreditCard({number:'0123'});
newCard.name = "Mike Smith";
newCard.$save();
// POST: /user/123/card {number:'0123', name:'Mike Smith'}
// server returns: {id:789, number:'01234', name: 'Mike Smith'};
expect(newCard.id).toEqual(789);
* </pre>
*
* The object returned from this function execution is a resource "class" which has "static" method
* for each action in the definition.
*
* Calling these methods invoke `$xhr` on the `url` template with the given `method` and `params`.
* When the data is returned from the server then the object is an instance of the resource type and
* all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD
* operations (create, read, update, delete) on server-side data.
<pre>
var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function(){
user.abc = true;
user.$save();
});
</pre>
*
* It's worth noting that the success callback for `get`, `query` and other method gets passed
* in the response that came from the server, so one could rewrite the above example as:
*
<pre>
var User = $resource('/user/:userId', {userId:'@id'});
User.get({userId:123}, function(u){
u.abc = true;
u.$save();
});
</pre>
* # Buzz client
Let's look at what a buzz client created with the `$resource` service looks like:
<doc:example>
<doc:source jsfiddle="false">
<script>
function BuzzController($resource) {
this.Activity = $resource(
'https://www.googleapis.com/buzz/v1/activities/:userId/:visibility/:activityId/:comments',
{alt:'json', callback:'JSON_CALLBACK'},
{get:{method:'JSON', params:{visibility:'@self'}}, replies: {method:'JSON', params:{visibility:'@self', comments:'@comments'}}}
);
}
BuzzController.prototype = {
fetch: function() {
this.activities = this.Activity.get({userId:this.userId});
},
expandReplies: function(activity) {
activity.replies = this.Activity.replies({userId:this.userId, activityId:activity.id});
}
};
BuzzController.$inject = ['$resource'];
</script>
<div ng:controller="BuzzController">
<input name="userId" value="googlebuzz"/>
<button ng:click="fetch()">fetch</button>
<hr/>
<div ng:repeat="item in activities.data.items">
<h1 style="font-size: 15px;">
<img src="{{item.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/>
<a href="{{item.actor.profileUrl}}">{{item.actor.name}}</a>
<a href ng:click="expandReplies(item)" style="float: right;">Expand replies: {{item.links.replies[0].count}}</a>
</h1>
{{item.object.content | html}}
<div ng:repeat="reply in item.replies.data.items" style="margin-left: 20px;">
<img src="{{reply.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/>
<a href="{{reply.actor.profileUrl}}">{{reply.actor.name}}</a>: {{reply.content | html}}
</div>
</div>
</div>
</doc:source>
<doc:scenario>
</doc:scenario>
</doc:example>
*/
angularServiceInject('$resource', function($xhr){
var resource = new ResourceFactory($xhr);
return bind(resource, resource.route);
}, ['$xhr.cache']);
/**
* @workInProgress
* @ngdoc service
* @name angular.service.$route
* @requires $location
* @requires $routeParams
*
* @property {Object} current Reference to the current route definition.
* @property {Array.<Object>} routes Array of all configured routes.
*
* @description
* Watches `$location.url()` and tries to map the path to an existing route
* definition. It is used for deep-linking URLs to controllers and views (HTML partials).
*
* The `$route` service is typically used in conjunction with {@link angular.widget.ng:view ng:view}
* widget and the {@link angular.service.$routeParams $routeParams} service.
*
* @example
This example shows how changing the URL hash causes the <tt>$route</tt>
to match a route against the URL, and the <tt>[[ng:include]]</tt> pulls in the partial.
<doc:example>
<doc:source jsfiddle="false">
<script>
function MainCntl($route, $routeParams, $location) {
this.$route = $route;
this.$location = $location;
this.$routeParams = $routeParams;
$route.when('/Book/:bookId', {template: 'examples/book.html', controller: BookCntl});
$route.when('/Book/:bookId/ch/:chapterId', {template: 'examples/chapter.html', controller: ChapterCntl});
}
function BookCntl($routeParams) {
this.name = "BookCntl";
this.params = $routeParams;
}
function ChapterCntl($routeParams) {
this.name = "ChapterCntl";
this.params = $routeParams;
}
</script>
<div ng:controller="MainCntl">
Choose:
<a href="#/Book/Moby">Moby</a> |
<a href="#/Book/Moby/ch/1">Moby: Ch1</a> |
<a href="#/Book/Gatsby">Gatsby</a> |
<a href="#/Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a><br/>
<pre>$location.path() = {{$location.path()}}</pre>
<pre>$route.current.template = {{$route.current.template}}</pre>
<pre>$route.current.params = {{$route.current.params}}</pre>
<pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
<pre>$routeParams = {{$routeParams}}</pre>
<hr />
<ng:view></ng:view>
</div>
</doc:source>
<doc:scenario>
</doc:scenario>
</doc:example>
*/
angularServiceInject('$route', function($location, $routeParams) {
/**
* @workInProgress
* @ngdoc event
* @name angular.service.$route#$beforeRouteChange
* @eventOf angular.service.$route
* @eventType broadcast on root scope
* @description
* Broadcasted before a route change.
*
* @param {Route} next Future route information.
* @param {Route} current Current route information.
*
* The `Route` object extends the route definition with the following properties.
*
* * `scope` - The instance of the route controller.
* * `params` - The current {@link angular.service.$routeParams params}.
*
*/
/**
* @workInProgress
* @ngdoc event
* @name angular.service.$route#$afterRouteChange
* @eventOf angular.service.$route
* @eventType broadcast on root scope
* @description
* Broadcasted after a route change.
*
* @param {Route} current Current route information.
* @param {Route} previous Previous route information.
*
* The `Route` object extends the route definition with the following properties.
*
* * `scope` - The instance of the route controller.
* * `params` - The current {@link angular.service.$routeParams params}.
*
*/
/**
* @workInProgress
* @ngdoc event
* @name angular.service.$route#$routeUpdate
* @eventOf angular.service.$route
* @eventType emit on the current route scope
* @description
*
* The `reloadOnSearch` property has been set to false, and we are reusing the same
* instance of the Controller.
*/
var routes = {},
matcher = switchRouteMatcher,
parentScope = this,
rootScope = this,
dirty = 0,
forceReload = false,
$route = {
routes: routes,
/**
* @workInProgress
* @ngdoc method
* @name angular.service.$route#parent
* @methodOf angular.service.$route
*
* @param {Scope} [scope=rootScope] Scope to be used as parent for newly created
* `$route.current.scope` scopes.
*
* @description
* Sets a scope to be used as the parent scope for scopes created on route change. If not
* set, defaults to the root scope.
*/
parent: function(scope) {
if (scope) parentScope = scope;
},
/**
* @workInProgress
* @ngdoc method
* @name angular.service.$route#when
* @methodOf angular.service.$route
*
* @param {string} path Route path (matched against `$location.hash`)
* @param {Object} route Mapping information to be assigned to `$route.current` on route
* match.
*
* Object properties:
*
* - `controller` – `{function()=}` – Controller fn that should be associated with newly
* created scope.
* - `template` – `{string=}` – path to an html template that should be used by
* {@link angular.widget.ng:view ng:view} or
* {@link angular.widget.ng:include ng:include} widgets.
* - `redirectTo` – {(string|function())=} – value to update
* {@link angular.service.$location $location} path with and trigger route redirection.
*
* If `redirectTo` is a function, it will be called with the following parameters:
*
* - `{Object.<string>}` - route parameters extracted from the current
* `$location.path()` by applying the current route template.
* - `{string}` - current `$location.path()`
* - `{Object}` - current `$location.search()`
*
* The custom `redirectTo` function is expected to return a string which will be used
* to update `$location.path()` and `$location.search()`.
*
* - `[reloadOnSearch=true]` - {boolean=} - reload route when only $location.search()
* changes.
*
* If the option is set to false and url in the browser changes, then
* $routeUpdate event is emited on the current route scope. You can use this event to
* react to {@link angular.service.$routeParams} changes:
*
* function MyCtrl($route, $routeParams) {
* this.$on('$routeUpdate', function() {
* // do stuff with $routeParams
* });
* }
*
* @returns {Object} route object
*
* @description
* Adds a new route definition to the `$route` service.
*/
when: function (path, route) {
var routeDef = routes[path];
if (!routeDef) routeDef = routes[path] = {reloadOnSearch: true};
if (route) extend(routeDef, route); // TODO(im): what the heck? merge two route definitions?
dirty++;
return routeDef;
},
/**
* @workInProgress
* @ngdoc method
* @name angular.service.$route#otherwise
* @methodOf angular.service.$route
*
* @description
* Sets route definition that will be used on route change when no other route definition
* is matched.
*
* @param {Object} params Mapping information to be assigned to `$route.current`.
*/
otherwise: function(params) {
$route.when(null, params);
},
/**
* @workInProgress
* @ngdoc method
* @name angular.service.$route#reload
* @methodOf angular.service.$route
*
* @description
* Causes `$route` service to reload (and recreate the `$route.current` scope) upon the next
* eval even if {@link angular.service.$location $location} hasn't changed.
*/
reload: function() {
dirty++;
forceReload = true;
}
};
this.$watch(function() { return dirty + $location.url(); }, updateRoute);
return $route;
/////////////////////////////////////////////////////
function switchRouteMatcher(on, when) {
// TODO(i): this code is convoluted and inefficient, we should construct the route matching
// regex only once and then reuse it
var regex = '^' + when.replace(/([\.\\\(\)\^\$])/g, "\\$1") + '$',
params = [],
dst = {};
forEach(when.split(/\W/), function(param) {
if (param) {
var paramRegExp = new RegExp(":" + param + "([\\W])");
if (regex.match(paramRegExp)) {
regex = regex.replace(paramRegExp, "([^\\/]*)$1");
params.push(param);
}
}
});
var match = on.match(new RegExp(regex));
if (match) {
forEach(params, function(name, index) {
dst[name] = match[index + 1];
});
}
return match ? dst : null;
}
function updateRoute() {
var next = parseRoute(),
last = $route.current;
if (next && last && next.$route === last.$route
&& equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) {
$route.current = next;
copy(next.params, $routeParams);
last.scope && last.scope.$emit('$routeUpdate');
} else {
forceReload = false;
rootScope.$broadcast('$beforeRouteChange', next, last);
last && last.scope && last.scope.$destroy();
$route.current = next;
if (next) {
if (next.redirectTo) {
if (isString(next.redirectTo)) {
$location.path(interpolate(next.redirectTo, next.params)).search(next.params)
.replace();
} else {
$location.url(next.redirectTo(next.pathParams, $location.path(), $location.search()))
.replace();
}
} else {
copy(next.params, $routeParams);
next.scope = parentScope.$new(next.controller);
}
}
rootScope.$broadcast('$afterRouteChange', next, last);
}
}
/**
* @returns the current active route, by matching it against the URL
*/
function parseRoute() {
// Match a route
var params, match;
forEach(routes, function(route, path) {
if (!match && (params = matcher($location.path(), path))) {
match = inherit(route, {
params: extend({}, $location.search(), params),
pathParams: params});
match.$route = route;
}
});
// No route matched; fallback to "otherwise" route
return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}});
}
/**
* @returns interpolation of the redirect path with the parametrs
*/
function interpolate(string, params) {
var result = [];
forEach((string||'').split(':'), function(segment, i) {
if (i == 0) {
result.push(segment);
} else {
var segmentMatch = segment.match(/(\w+)(.*)/);
var key = segmentMatch[1];
result.push(params[key]);
result.push(segmentMatch[2] || '');
delete params[key];
}
});
return result.join('');
}
}, ['$location', '$routeParams']);
/**
* @workInProgress
* @ngdoc service
* @name angular.service.$routeParams
* @requires $route
*
* @description
* Current set of route parameters. The route parameters are a combination of the
* {@link angular.service.$location $location} `search()`, and `path()`. The `path` parameters
* are extracted when the {@link angular.service.$route $route} path is matched.
*
* In case of parameter name collision, `path` params take precedence over `search` params.
*
* The service guarantees that the identity of the `$routeParams` object will remain unchanged
* (but its properties will likely change) even when a route change occurs.
*
* @example
* <pre>
* // Given:
* // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
* // Route: /Chapter/:chapterId/Section/:sectionId
* //
* // Then
* $routeParams ==> {chapterId:1, sectionId:2, search:'moby'}
* </pre>
*/
angularService('$routeParams', function(){
return {};
});
/**
* @workInProgress
* @ngdoc service
* @name angular.service.$sniffer
* @requires $window
*
* @property {boolean} history Does the browser support html5 history api ?
* @property {boolean} hashchange Does the browser support hashchange event ?
*
* @description
* This is very simple implementation of testing browser's features.
*/
angularServiceInject('$sniffer', function($window) {
if ($window.Modernizr) return $window.Modernizr;
return {
history: !!($window.history && $window.history.pushState),
hashchange: 'onhashchange' in $window &&
// IE8 compatible mode lies
(!$window.document.documentMode || $window.document.documentMode > 7)
};
}, ['$window']);
/**
* @workInProgress
* @ngdoc service
* @name angular.service.$window
*
* @description
* A reference to the browser's `window` object. While `window`
* is globally available in JavaScript, it causes testability problems, because
* it is a global variable. In angular we always refer to it through the
* `$window` service, so it may be overriden, removed or mocked for testing.
*
* All expressions are evaluated with respect to current scope so they don't
* suffer from window globality.
*
* @example
<doc:example>
<doc:source>
<input ng:init="$window = $service('$window'); greeting='Hello World!'" type="text" name="greeting" />
<button ng:click="$window.alert(greeting)">ALERT</button>
</doc:source>
<doc:scenario>
</doc:scenario>
</doc:example>
*/
angularServiceInject("$window", bind(window, identity, window));
/**
* @workInProgress
* @ngdoc service
* @name angular.service.$xhr.bulk
* @requires $xhr
* @requires $xhr.error
* @requires $log
*
* @description
*
* @example
*/
angularServiceInject('$xhr.bulk', function($xhr, $error, $log){
var requests = [],
scope = this;
function bulkXHR(method, url, post, success, error) {
if (isFunction(post)) {
error = success;
success = post;
post = null;
}
var currentQueue;
forEach(bulkXHR.urls, function(queue){
if (isFunction(queue.match) ? queue.match(url) : queue.match.exec(url)) {
currentQueue = queue;
}
});
if (currentQueue) {
if (!currentQueue.requests) currentQueue.requests = [];
var request = {
method: method,
url: url,
data: post,
success: success};
if (error) request.error = error;
currentQueue.requests.push(request);
} else {
$xhr(method, url, post, success, error);
}
}
bulkXHR.urls = {};
bulkXHR.flush = function(success, errorback) {
assertArgFn(success = success || noop, 0);
assertArgFn(errorback = errorback || noop, 1);
forEach(bulkXHR.urls, function(queue, url) {
var currentRequests = queue.requests;
if (currentRequests && currentRequests.length) {
queue.requests = [];
queue.callbacks = [];
$xhr('POST', url, {requests: currentRequests},
function(code, response) {
forEach(response, function(response, i) {
try {
if (response.status == 200) {
(currentRequests[i].success || noop)(response.status, response.response);
} else if (isFunction(currentRequests[i].error)) {
currentRequests[i].error(response.status, response.response);
} else {
$error(currentRequests[i], response);
}
} catch(e) {
$log.error(e);
}
});
success();
},
function(code, response) {
forEach(currentRequests, function(request, i) {
try {
if (isFunction(request.error)) {
request.error(code, response);
} else {
$error(request, response);
}
} catch(e) {
$log.error(e);
}
});
noop();
});
}
});
};
this.$watch(function(){ bulkXHR.flush(); });
return bulkXHR;
}, ['$xhr', '$xhr.error', '$log']);
/**
* @workInProgress
* @ngdoc service
* @name angular.service.$xhr.cache
* @function
*
* @requires $xhr.bulk
* @requires $defer
* @requires $xhr.error
* @requires $log
*
* @description
* Acts just like the {@link angular.service.$xhr $xhr} service but caches responses for `GET`
* requests. All cache misses are delegated to the $xhr service.
*
* @property {function()} delegate Function to delegate all the cache misses to. Defaults to
* the {@link angular.service.$xhr $xhr} service.
* @property {object} data The hashmap where all cached entries are stored.
*
* @param {string} method HTTP method.
* @param {string} url Destination URL.
* @param {(string|Object)=} post Request body.
* @param {function(number, (string|Object))} success Response success callback.
* @param {function(number, (string|Object))=} error Response error callback.
* @param {boolean=} [verifyCache=false] If `true` then a result is immediately returned from cache
* (if present) while a request is sent to the server for a fresh response that will update the
* cached entry. The `success` function will be called when the response is received.
* @param {boolean=} [sync=false] in case of cache hit execute `success` synchronously.
*/
angularServiceInject('$xhr.cache', function($xhr, $defer, $error, $log) {
var inflight = {}, self = this;
function cache(method, url, post, success, error, verifyCache, sync) {
if (isFunction(post)) {
if (!isFunction(success)) {
verifyCache = success;
sync = error;
error = null;
} else {
sync = verifyCache;
verifyCache = error;
error = success;
}
success = post;
post = null;
} else if (!isFunction(error)) {
sync = verifyCache;
verifyCache = error;
error = null;
}
if (method == 'GET') {
var data, dataCached;
if ((dataCached = cache.data[url])) {
if (sync) {
success(200, copy(dataCached.value));
} else {
$defer(function() { success(200, copy(dataCached.value)); });
}
if (!verifyCache)
return;
}
if ((data = inflight[url])) {
data.successes.push(success);
data.errors.push(error);
} else {
inflight[url] = {successes: [success], errors: [error]};
cache.delegate(method, url, post,
function(status, response) {
if (status == 200)
cache.data[url] = {value: response};
var successes = inflight[url].successes;
delete inflight[url];
forEach(successes, function(success) {
try {
(success||noop)(status, copy(response));
} catch(e) {
$log.error(e);
}
});
},
function(status, response) {
var errors = inflight[url].errors,
successes = inflight[url].successes;
delete inflight[url];
forEach(errors, function(error, i) {
try {
if (isFunction(error)) {
error(status, copy(response));
} else {
$error(
{method: method, url: url, data: post, success: successes[i]},
{status: status, body: response});
}
} catch(e) {
$log.error(e);
}
});
});
}
} else {
cache.data = {};
cache.delegate(method, url, post, success, error);
}
}
cache.data = {};
cache.delegate = $xhr;
return cache;
}, ['$xhr.bulk', '$defer', '$xhr.error', '$log']);
/**
* @workInProgress
* @ngdoc service
* @name angular.service.$xhr.error
* @function
* @requires $log
*
* @description
* Error handler for {@link angular.service.$xhr $xhr service}. An application can replaces this
* service with one specific for the application. The default implementation logs the error to
* {@link angular.service.$log $log.error}.
*
* @param {Object} request Request object.
*
* The object has the following properties
*
* - `method` – `{string}` – The http request method.
* - `url` – `{string}` – The request destination.
* - `data` – `{(string|Object)=} – An optional request body.
* - `success` – `{function()}` – The success callback function
*
* @param {Object} response Response object.
*
* The response object has the following properties:
*
* - status – {number} – Http status code.
* - body – {string|Object} – Body of the response.
*
* @example
<doc:example>
<doc:source>
fetch a non-existent file and log an error in the console:
<button ng:click="$service('$xhr')('GET', '/DOESNT_EXIST')">fetch</button>
</doc:source>
</doc:example>
*/
angularServiceInject('$xhr.error', function($log){
return function(request, response){
$log.error('ERROR: XHR: ' + request.url, request, response);
};
}, ['$log']);
/**
* @workInProgress
* @ngdoc service
* @name angular.service.$xhr
* @function
* @requires $browser $xhr delegates all XHR requests to the `$browser.xhr()`. A mock version
* of the $browser exists which allows setting expectations on XHR requests
* in your tests
* @requires $xhr.error $xhr delegates all non `2xx` response code to this service.
* @requires $log $xhr delegates all exceptions to `$log.error()`.
*
* @description
* Generates an XHR request. The $xhr service delegates all requests to
* {@link angular.service.$browser $browser.xhr()} and adds error handling and security features.
* While $xhr service provides nicer api than raw XmlHttpRequest, it is still considered a lower
* level api in angular. For a higher level abstraction that utilizes `$xhr`, please check out the
* {@link angular.service.$resource $resource} service.
*
* # Error handling
* If no `error callback` is specified, XHR response with response code other then `2xx` will be
* delegated to {@link angular.service.$xhr.error $xhr.error}. The `$xhr.error` can intercept the
* request and process it in application specific way, or resume normal execution by calling the
* request `success` method.
*
* # HTTP Headers
* The $xhr service will automatically add certain http headers to all requests. These defaults can
* be fully configured by accessing the `$xhr.defaults.headers` configuration object, which
* currently contains this default configuration:
*
* - `$xhr.defaults.headers.common` (headers that are common for all requests):
* - `Accept: application/json, text/plain, *\/*`
* - `X-Requested-With: XMLHttpRequest`
* - `$xhr.defaults.headers.post` (header defaults for HTTP POST requests):
* - `Content-Type: application/x-www-form-urlencoded`
*
* To add or overwrite these defaults, simple add or remove a property from this configuration
* object. To add headers for an HTTP method other than POST, simple create a new object with name
* equal to the lowercased http method name, e.g. `$xhr.defaults.headers.get['My-Header']='value'`.
*
*
* # Security Considerations
* When designing web applications your design needs to consider security threats from
* {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
* JSON Vulnerability} and {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF}.
* Both server and the client must cooperate in order to eliminate these threats. Angular comes
* pre-configured with strategies that address these issues, but for this to work backend server
* cooperation is required.
*
* ## JSON Vulnerability Protection
* A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
* JSON Vulnerability} allows third party web-site to turn your JSON resource URL into
* {@link http://en.wikipedia.org/wiki/JSON#JSONP JSONP} request under some conditions. To
* counter this your server can prefix all JSON requests with following string `")]}',\n"`.
* Angular will automatically strip the prefix before processing it as JSON.
*
* For example if your server needs to return:
* <pre>
* ['one','two']
* </pre>
*
* which is vulnerable to attack, your server can return:
* <pre>
* )]}',
* ['one','two']
* </pre>
*
* angular will strip the prefix, before processing the JSON.
*
*
* ## Cross Site Request Forgery (XSRF) Protection
* {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which an
* unauthorized site can gain your user's private data. Angular provides following mechanism to
* counter XSRF. When performing XHR requests, the $xhr service reads a token from a cookie
* called `XSRF-TOKEN` and sets it as the HTTP header `X-XSRF-TOKEN`. Since only JavaScript that
* runs on your domain could read the cookie, your server can be assured that the XHR came from
* JavaScript running on your domain.
*
* To take advantage of this, your server needs to set a token in a JavaScript readable session
* cookie called `XSRF-TOKEN` on first HTTP GET request. On subsequent non-GET requests the server
* can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure that only
* JavaScript running on your domain could have read the token. The token must be unique for each
* user and must be verifiable by the server (to prevent the JavaScript making up its own tokens).
* We recommend that the token is a digest of your site's authentication cookie with
* {@link http://en.wikipedia.org/wiki/Rainbow_table salt for added security}.
*
* @param {string} method HTTP method to use. Valid values are: `GET`, `POST`, `PUT`, `DELETE`, and
* `JSON`. `JSON` is a special case which causes a
* [JSONP](http://en.wikipedia.org/wiki/JSON#JSONP) cross domain request using script tag
* insertion.
* @param {string} url Relative or absolute URL specifying the destination of the request. For
* `JSON` requests, `url` should include `JSON_CALLBACK` string to be replaced with a name of an
* angular generated callback function.
* @param {(string|Object)=} post Request content as either a string or an object to be stringified
* as JSON before sent to the server.
* @param {function(number, (string|Object))} success A function to be called when the response is
* received. The success function will be called with:
*
* - {number} code [HTTP status code](http://en.wikipedia.org/wiki/List_of_HTTP_status_codes) of
* the response. This will currently always be 200, since all non-200 responses are routed to
* {@link angular.service.$xhr.error} service (or custom error callback).
* - {string|Object} response Response object as string or an Object if the response was in JSON
* format.
* @param {function(number, (string|Object))} error A function to be called if the response code is
* not 2xx.. Accepts the same arguments as success, above.
*
* @example
<doc:example>
<doc:source jsfiddle="false">
<script>
function FetchCntl($xhr) {
var self = this;
this.fetch = function() {
self.code = null;
self.response = null;
$xhr(self.method, self.url, function(code, response) {
self.code = code;
self.response = response;
}, function(code, response) {
self.code = code;
self.response = response || "Request failed";
});
};
this.updateModel = function(method, url) {
self.method = method;
self.url = url;
};
}
FetchCntl.$inject = ['$xhr'];
</script>
<div ng:controller="FetchCntl">
<select name="method">
<option>GET</option>
<option>JSON</option>
</select>
<input type="text" name="url" value="index.html" size="80"/>
<button ng:click="fetch()">fetch</button><br>
<button ng:click="updateModel('GET', 'index.html')">Sample GET</button>
<button ng:click="updateModel('JSON', 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">Sample JSONP</button>
<button ng:click="updateModel('JSON', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">Invalid JSONP</button>
<pre>code={{code}}</pre>
<pre>response={{response}}</pre>
</div>
</doc:source>
<doc:scenario>
it('should make xhr GET request', function() {
element(':button:contains("Sample GET")').click();
element(':button:contains("fetch")').click();
expect(binding('code')).toBe('code=200');
expect(binding('response')).toMatch(/angularjs.org/);
});
it('should make JSONP request to the angularjs.org', function() {
element(':button:contains("Sample JSONP")').click();
element(':button:contains("fetch")').click();
expect(binding('code')).toBe('code=200');
expect(binding('response')).toMatch(/Super Hero!/);
});
it('should make JSONP request to invalid URL and invoke the error handler',
function() {
element(':button:contains("Invalid JSONP")').click();
element(':button:contains("fetch")').click();
expect(binding('code')).toBe('code=');
expect(binding('response')).toBe('response=Request failed');
});
</doc:scenario>
</doc:example>
*/
angularServiceInject('$xhr', function($browser, $error, $log){
var rootScope = this;
var xhrHeaderDefaults = {
common: {
"Accept": "application/json, text/plain, */*",
"X-Requested-With": "XMLHttpRequest"
},
post: {'Content-Type': 'application/x-www-form-urlencoded'},
get: {}, // all these empty properties are needed so that client apps can just do:
head: {}, // $xhr.defaults.headers.head.foo="bar" without having to create head object
put: {}, // it also means that if we add a header for these methods in the future, it
'delete': {}, // won't be easily silently lost due to an object assignment.
patch: {}
};
function xhr(method, url, post, success, error) {
if (isFunction(post)) {
error = success;
success = post;
post = null;
}
if (post && isObject(post)) {
post = toJson(post);
}
$browser.xhr(method, url, post, function(code, response){
try {
if (isString(response)) {
if (response.match(/^\)\]\}',\n/)) response=response.substr(6);
if (/^\s*[\[\{]/.exec(response) && /[\}\]]\s*$/.exec(response)) {
response = fromJson(response, true);
}
}
rootScope.$apply(function(){
if (200 <= code && code < 300) {
success(code, response);
} else if (isFunction(error)) {
error(code, response);
} else {
$error(
{method: method, url: url, data: post, success: success},
{status: code, body: response});
}
});
} catch (e) {
$log.error(e);
}
}, extend({'X-XSRF-TOKEN': $browser.cookies()['XSRF-TOKEN']},
xhrHeaderDefaults.common,
xhrHeaderDefaults[lowercase(method)]));
}
xhr.defaults = {headers: xhrHeaderDefaults};
return xhr;
}, ['$browser', '$xhr.error', '$log']);
/**
* @ngdoc service
* @name angular.service.$locale
*
* @description
* $locale service provides localization rules for various Angular components. As of right now the
* only public api is:
*
* * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
*/
angularServiceInject('$locale', function() {
return {
id: 'en-us',
NUMBER_FORMATS: {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PATTERNS: [
{ // Decimal Pattern
minInt: 1,
minFrac: 0,
maxFrac: 3,
posPre: '',
posSuf: '',
negPre: '-',
negSuf: '',
gSize: 3,
lgSize: 3
},{ //Currency Pattern
minInt: 1,
minFrac: 2,
maxFrac: 2,
posPre: '\u00A4',
posSuf: '',
negPre: '(\u00A4',
negSuf: ')',
gSize: 3,
lgSize: 3
}
],
CURRENCY_SYM: '$'
},
DATETIME_FORMATS: {
MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December'
.split(','),
SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
AMPMS: ['AM','PM'],
medium: 'MMM d, y h:mm:ss a',
short: 'M/d/yy h:mm a',
fullDate: 'EEEE, MMMM d, y',
longDate: 'MMMM d, y',
mediumDate: 'MMM d, y',
shortDate: 'M/d/yy',
mediumTime: 'h:mm:ss a',
shortTime: 'h:mm a'
},
pluralCat: function(num) {
if (num === 1) {
return 'one';
}
return 'other';
}
};
});
/**
* @ngdoc overview
* @name angular.directive
* @description
*
* Angular directives create custom attributes for DOM elements. A directive can modify the
* behavior of the element in which it is specified. Do not use directives to add elements to the
* DOM; instead, use {@link angular.widget widgets} to add DOM elements.
*
* Following is the list of built-in Angular directives:
*
* * {@link angular.directive.ng:autobind ng:autobind} - An Angular bootstrap parameter that can
* act as a directive.
* * {@link angular.directive.ng:bind ng:bind} - Creates a data-binding between an HTML text value
* and a data model.
* * {@link angular.directive.ng:bind-attr ng:bind-attr} - Creates a data-binding in a way similar
* to `ng:bind`, but uses JSON key / value pairs to do so.
* * {@link angular.directive.ng:bind-template ng:bind-template} - Replaces the text value of an
* element with a specified template.
* * {@link angular.directive.ng:change ng:change} - Executes an expression when the value of an
* input widget changes.
* * {@link angular.directive.ng:class ng:class} - Conditionally set a CSS class on an element.
* * {@link angular.directive.ng:class-even ng:class-even} - Like `ng:class`, but works in
* conjunction with {@link angular.widget.@ng:repeat} to affect even rows in a collection.
* * {@link angular.directive.ng:class-odd ng:class-odd} - Like `ng:class`, but works with {@link
* angular.widget.@ng:repeat} to affect odd rows.
* * {@link angular.directive.ng:click ng:click} - Executes custom behavior when an element is
* clicked.
* * {@link angular.directive.ng:controller ng:controller} - Creates a scope object linked to the
* DOM element and assigns behavior to the scope.
* * {@link angular.directive.ng:hide ng:hide} - Conditionally hides a portion of HTML.
* * {@link angular.directive.ng:href ng:href} - Places an href in the Angular namespace.
* * {@link angular.directive.ng:init} - Initialization tasks run before a template is executed.
* * {@link angular.directive.ng:show ng:show} - Conditionally displays a portion of HTML.
* * {@link angular.directive.ng:src ng:src} - Places a `src` attribute into the Angular namespace.
* * {@link angular.directive.ng:style ng:style} - Conditionally set CSS styles on an element.
* * {@link angular.directive.ng:submit} - Binds Angular expressions to `onSubmit` events.
*
* For more information about how Angular directives work, and to learn how to create your own
* directives, see {@link guide/dev_guide.compiler.directives Understanding Angular Directives} in
* the Angular Developer Guide.
*/
/**
* @workInProgress
* @ngdoc directive
* @name angular.directive.ng:init
*
* @description
* The `ng:init` attribute specifies initialization tasks to be executed
* before the template enters execution mode during bootstrap.
*
* @element ANY
* @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval.
*
* @example
<doc:example>
<doc:source>
<div ng:init="greeting='Hello'; person='World'">
{{greeting}} {{person}}!
</div>
</doc:source>
<doc:scenario>
it('should check greeting', function(){
expect(binding('greeting')).toBe('Hello');
expect(binding('person')).toBe('World');
});
</doc:scenario>
</doc:example>
*/
angularDirective("ng:init", function(expression){
return function(element){
this.$eval(expression);
};
});
/**
* @workInProgress
* @ngdoc directive
* @name angular.directive.ng:controller
*
* @description
* The `ng:controller` directive assigns behavior to a scope. This is a key aspect of how angular
* supports the principles behind the Model-View-Controller design pattern.
*
* MVC components in angular:
*
* * Model — The Model is data in scope properties; scopes are attached to the DOM.
* * View — The template (HTML with data bindings) is rendered into the View.
* * Controller — The `ng:controller` directive specifies a Controller class; the class has
* methods that typically express the business logic behind the application.
*
* Note that an alternative way to define controllers is via the `{@link angular.service.$route}`
* service.
*
* @element ANY
* @param {expression} expression Name of a globally accessible constructor function or an
* {@link guide/dev_guide.expressions expression} that on the current scope evaluates to a
* constructor function.
*
* @example
* Here is a simple form for editing user contact information. Adding, removing, clearing, and
* greeting are methods declared on the controller (see source tab). These methods can
* easily be called from the angular markup. Notice that the scope becomes the `this` for the
* controller's instance. This allows for easy access to the view data from the controller. Also
* notice that any changes to the data are automatically reflected in the View without the need
* for a manual update.
<doc:example>
<doc:source>
<script type="text/javascript">
function SettingsController() {
this.name = "John Smith";
this.contacts = [
{type:'phone', value:'408 555 1212'},
{type:'email', value:'john.smith@example.org'} ];
}
SettingsController.prototype = {
greet: function(){
alert(this.name);
},
addContact: function(){
this.contacts.push({type:'email', value:'yourname@example.org'});
},
removeContact: function(contactToRemove) {
angular.Array.remove(this.contacts, contactToRemove);
},
clearContact: function(contact) {
contact.type = 'phone';
contact.value = '';
}
};
</script>
<div ng:controller="SettingsController">
Name: <input type="text" name="name"/>
[ <a href="" ng:click="greet()">greet</a> ]<br/>
Contact:
<ul>
<li ng:repeat="contact in contacts">
<select name="contact.type">
<option>phone</option>
<option>email</option>
</select>
<input type="text" name="contact.value"/>
[ <a href="" ng:click="clearContact(contact)">clear</a>
| <a href="" ng:click="removeContact(contact)">X</a> ]
</li>
<li>[ <a href="" ng:click="addContact()">add</a> ]</li>
</ul>
</div>
</doc:source>
<doc:scenario>
it('should check controller', function(){
expect(element('.doc-example-live div>:input').val()).toBe('John Smith');
expect(element('.doc-example-live li[ng\\:repeat-index="0"] input').val())
.toBe('408 555 1212');
expect(element('.doc-example-live li[ng\\:repeat-index="1"] input').val())
.toBe('john.smith@example.org');
element('.doc-example-live li:first a:contains("clear")').click();
expect(element('.doc-example-live li:first input').val()).toBe('');
element('.doc-example-live li:last a:contains("add")').click();
expect(element('.doc-example-live li[ng\\:repeat-index="2"] input').val())
.toBe('yourname@example.org');
});
</doc:scenario>
</doc:example>
*/
angularDirective("ng:controller", function(expression){
this.scope(function(scope){
var Controller =
getter(scope, expression, true) ||
getter(window, expression, true);
assertArgFn(Controller, expression);
return Controller;
});
return noop;
});
/**
* @ngdoc directive
* @name angular.directive.ng:bind
*
* @description
* The `ng:bind` attribute tells Angular to replace the text content of the specified HTML element
* with the value of a given expression, and to update the text content when the value of that
* expression changes.
*
* Typically, you don't use `ng:bind` directly, but instead you use the double curly markup like
* `{{ expression }}` and let the Angular compiler transform it to
* `<span ng:bind="expression"></span>` when the template is compiled.
*
* @element ANY
* @param {expression} expression {@link guide/dev_guide.expressions Expression} to evaluate.
*
* @example
* Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
<doc:example>
<doc:source>
Enter name: <input type="text" name="name" value="Whirled"> <br>
Hello <span ng:bind="name"></span>!
</doc:source>
<doc:scenario>
it('should check ng:bind', function(){
expect(using('.doc-example-live').binding('name')).toBe('Whirled');
using('.doc-example-live').input('name').enter('world');
expect(using('.doc-example-live').binding('name')).toBe('world');
});
</doc:scenario>
</doc:example>
*/
angularDirective("ng:bind", function(expression, element){
element.addClass('ng-binding');
var exprFn = parser(expression).statements();
return function(element) {
var lastValue = noop, lastError = noop;
this.$watch(function(scope) {
// TODO(misko): remove error handling https://github.com/angular/angular.js/issues/347
var error, value, html, isHtml, isDomElement,
hadOwnElement = scope.hasOwnProperty('$element'),
oldElement = scope.$element;
// TODO(misko): get rid of $element https://github.com/angular/angular.js/issues/348
scope.$element = element;
try {
value = exprFn(scope);
} catch (e) {
scope.$service('$exceptionHandler')(e);
error = formatError(e);
} finally {
if (hadOwnElement) {
scope.$element = oldElement;
} else {
delete scope.$element;
}
}
// If we are HTML, then save the raw HTML data so that we don't
// recompute sanitization since that is expensive.
// TODO: turn this into a more generic way to compute this
if ((isHtml = (value instanceof HTML)))
value = (html = value).html;
if (lastValue === value && lastError == error) return;
isDomElement = isElement(value);
if (!isHtml && !isDomElement && isObject(value)) {
value = toJson(value, true);
}
if (value != lastValue || error != lastError) {
lastValue = value;
lastError = error;
elementError(element, NG_EXCEPTION, error);
if (error) value = error;
if (isHtml) {
element.html(html.get());
} else if (isDomElement) {
element.html('');
element.append(value);
} else {
element.text(value == undefined ? '' : value);
}
}
});
};
});
var bindTemplateCache = {};
function compileBindTemplate(template){
var fn = bindTemplateCache[template];
if (!fn) {
var bindings = [];
forEach(parseBindings(template), function(text){
var exp = binding(text);
bindings.push(exp
? function(scope, element) {
var error, value;
try {
value = scope.$eval(exp);
} catch(e) {
scope.$service('$exceptionHandler')(e);
error = toJson(e);
}
elementError(element, NG_EXCEPTION, error);
return error ? error : value;
}
: function() {
return text;
});
});
bindTemplateCache[template] = fn = function(scope, element, prettyPrintJson) {
var parts = [],
hadOwnElement = scope.hasOwnProperty('$element'),
oldElement = scope.$element;
// TODO(misko): get rid of $element
scope.$element = element;
try {
for (var i = 0; i < bindings.length; i++) {
var value = bindings[i](scope, element);
if (isElement(value))
value = '';
else if (isObject(value))
value = toJson(value, prettyPrintJson);
parts.push(value);
}
return parts.join('');
} finally {
if (hadOwnElement) {
scope.$element = oldElement;
} else {
delete scope.$element;
}
}
};
}
return fn;
}
/**
* @workInProgress
* @ngdoc directive
* @name angular.directive.ng:bind-template
*
* @description
* The `ng:bind-template` attribute specifies that the element
* text should be replaced with the template in ng:bind-template.
* Unlike ng:bind the ng:bind-template can contain multiple `{{` `}}`
* expressions. (This is required since some HTML elements
* can not have SPAN elements such as TITLE, or OPTION to name a few.)
*
* @element ANY
* @param {string} template of form
* <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
*
* @example
* Try it here: enter text in text box and watch the greeting change.
<doc:example>
<doc:source>
Salutation: <input type="text" name="salutation" value="Hello"><br/>
Name: <input type="text" name="name" value="World"><br/>
<pre ng:bind-template="{{salutation}} {{name}}!"></pre>
</doc:source>
<doc:scenario>
it('should check ng:bind', function(){
expect(using('.doc-example-live').binding('{{salutation}} {{name}}')).
toBe('Hello World!');
using('.doc-example-live').input('salutation').enter('Greetings');
using('.doc-example-live').input('name').enter('user');
expect(using('.doc-example-live').binding('{{salutation}} {{name}}')).
toBe('Greetings user!');
});
</doc:scenario>
</doc:example>
*/
angularDirective("ng:bind-template", function(expression, element){
element.addClass('ng-binding');
var templateFn = compileBindTemplate(expression);
return function(element) {
var lastValue;
this.$watch(function(scope) {
var value = templateFn(scope, element, true);
if (value != lastValue) {
element.text(value);
lastValue = value;
}
});
};
});
var REMOVE_ATTRIBUTES = {
'disabled':'disabled',
'readonly':'readOnly',
'checked':'checked',
'selected':'selected',
'multiple':'multiple'
};
/**
* @ngdoc directive
* @name angular.directive.ng:bind-attr
*
* @description
* The `ng:bind-attr` attribute specifies that a
* {@link guide/dev_guide.templates.databinding databinding} should be created between a particular
* element attribute and a given expression. Unlike `ng:bind`, the `ng:bind-attr` contains one or
* more JSON key value pairs; each pair specifies an attribute and the
* {@link guide/dev_guide.expressions expression} to which it will be mapped.
*
* Instead of writing `ng:bind-attr` statements in your HTML, you can use double-curly markup to
* specify an <tt ng:non-bindable>{{expression}}</tt> for the value of an attribute.
* At compile time, the attribute is translated into an `<span ng:bind-attr="{attr:expression}"/>`
*
* The following HTML snippet shows how to specify `ng:bind-attr`:
* <pre>
* <a href="http://www.google.com/search?q={{query}}">Google</a>
* </pre>
*
* During compilation, the snippet gets translated to the following:
* <pre>
* <a ng:bind-attr='{"href":"http://www.google.com/search?q={{query}}"}'>Google</a>
* </pre>
*
* @element ANY
* @param {string} attribute_json one or more JSON key-value pairs representing
* the attributes to replace with expressions. Each key matches an attribute
* which needs to be replaced. Each value is a text template of
* the attribute with the embedded
* <tt ng:non-bindable>{{expression}}</tt>s. Any number of
* key-value pairs can be specified.
*
* @example
* Enter a search string in the Live Preview text box and then click "Google". The search executes instantly.
<doc:example>
<doc:source>
Google for:
<input type="text" name="query" value="AngularJS"/>
<a href="http://www.google.com/search?q={{query}}">Google</a>
</doc:source>
<doc:scenario>
it('should check ng:bind-attr', function(){
expect(using('.doc-example-live').element('a').attr('href')).
toBe('http://www.google.com/search?q=AngularJS');
using('.doc-example-live').input('query').enter('google');
expect(using('.doc-example-live').element('a').attr('href')).
toBe('http://www.google.com/search?q=google');
});
</doc:scenario>
</doc:example>
*/
angularDirective("ng:bind-attr", function(expression){
return function(element){
var lastValue = {};
this.$watch(function(scope){
var values = scope.$eval(expression);
for(var key in values) {
var value = compileBindTemplate(values[key])(scope, element),
specialName = REMOVE_ATTRIBUTES[lowercase(key)];
if (lastValue[key] !== value) {
lastValue[key] = value;
if (specialName) {
if (toBoolean(value)) {
element.attr(specialName, specialName);
element.attr('ng-' + specialName, value);
} else {
element.removeAttr(specialName);
element.removeAttr('ng-' + specialName);
}
(element.data($$validate)||noop)();
} else {
element.attr(key, value);
}
}
}
});
};
});
/**
* @workInProgress
* @ngdoc directive
* @name angular.directive.ng:click
*
* @description
* The ng:click allows you to specify custom behavior when
* element is clicked.
*
* @element ANY
* @param {expression} expression {@link guide/dev_guide.expressions Expression} to evaluate upon
* click.
*
* @example
<doc:example>
<doc:source>
<button ng:click="count = count + 1" ng:init="count=0">
Increment
</button>
count: {{count}}
</doc:source>
<doc:scenario>
it('should check ng:click', function(){
expect(binding('count')).toBe('0');
element('.doc-example-live :button').click();
expect(binding('count')).toBe('1');
});
</doc:scenario>
</doc:example>
*/
/*
* A directive that allows creation of custom onclick handlers that are defined as angular
* expressions and are compiled and executed within the current scope.
*
* Events that are handled via these handler are always configured not to propagate further.
*
* TODO: maybe we should consider allowing users to control event propagation in the future.
*/
angularDirective("ng:click", function(expression, element){
return function(element){
var self = this;
element.bind('click', function(event){
self.$apply(expression);
event.stopPropagation();
});
};
});
/**
* @workInProgress
* @ngdoc directive
* @name angular.directive.ng:submit
*
* @description
* Enables binding angular expressions to onsubmit events.
*
* Additionally it prevents the default action (which for form means sending the request to the
* server and reloading the current page).
*
* @element form
* @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval.
*
* @example
<doc:example>
<doc:source>
<form ng:submit="list.push(text);text='';" ng:init="list=[]">
Enter text and hit enter:
<input type="text" name="text" value="hello"/>
<input type="submit" id="submit" value="Submit" />
</form>
<pre>list={{list}}</pre>
</doc:source>
<doc:scenario>
it('should check ng:submit', function(){
expect(binding('list')).toBe('list=[]');
element('.doc-example-live #submit').click();
expect(binding('list')).toBe('list=["hello"]');
});
</doc:scenario>
</doc:example>
*/
angularDirective("ng:submit", function(expression, element) {
return function(element) {
var self = this;
element.bind('submit', function(event) {
self.$apply(expression);
event.preventDefault();
});
};
});
function ngClass(selector) {
return function(expression, element) {
return function(element) {
this.$watch(expression, function(scope, newVal, oldVal) {
if (selector(scope.$index)) {
element.removeClass(isArray(oldVal) ? oldVal.join(' ') : oldVal)
element.addClass(isArray(newVal) ? newVal.join(' ') : newVal);
}
});
};
};
}
/**
* @workInProgress
* @ngdoc directive
* @name angular.directive.ng:class
*
* @description
* The `ng:class` allows you to set CSS class on HTML element dynamically by databinding an
* expression that represents all classes to be added.
*
* The directive won't add duplicate classes if a particular class was already set.
*
* When the expression changes, the previously added classes are removed and only then the classes
* new classes are added.
*
* @element ANY
* @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. The result
* of the evaluation can be a string representing space delimited class names or an array.
*
* @example
<doc:example>
<doc:source>
<input type="button" value="set" ng:click="myVar='ng-input-indicator-wait'">
<input type="button" value="clear" ng:click="myVar=''">
<br>
<span ng:class="myVar">Sample Text </span>
</doc:source>
<doc:scenario>
it('should check ng:class', function(){
expect(element('.doc-example-live span').prop('className')).not().
toMatch(/ng-input-indicator-wait/);
using('.doc-example-live').element(':button:first').click();
expect(element('.doc-example-live span').prop('className')).
toMatch(/ng-input-indicator-wait/);
using('.doc-example-live').element(':button:last').click();
expect(element('.doc-example-live span').prop('className')).not().
toMatch(/ng-input-indicator-wait/);
});
</doc:scenario>
</doc:example>
*/
angularDirective("ng:class", ngClass(function(){return true;}));
/**
* @workInProgress
* @ngdoc directive
* @name angular.directive.ng:class-odd
*
* @description
* The `ng:class-odd` and `ng:class-even` works exactly as
* {@link angular.directive.ng:class ng:class}, except it works in conjunction with `ng:repeat` and
* takes affect only on odd (even) rows.
*
* This directive can be applied only within a scope of an
* {@link angular.widget.@ng:repeat ng:repeat}.
*
* @element ANY
* @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. The result
* of the evaluation can be a string representing space delimited class names or an array.
*
* @example
<doc:example>
<doc:source>
<ol ng:init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng:repeat="name in names">
<span ng:class-odd="'ng-format-negative'"
ng:class-even="'ng-input-indicator-wait'">
{{name}}
</span>
</li>
</ol>
</doc:source>
<doc:scenario>
it('should check ng:class-odd and ng:class-even', function(){
expect(element('.doc-example-live li:first span').prop('className')).
toMatch(/ng-format-negative/);
expect(element('.doc-example-live li:last span').prop('className')).
toMatch(/ng-input-indicator-wait/);
});
</doc:scenario>
</doc:example>
*/
angularDirective("ng:class-odd", ngClass(function(i){return i % 2 === 0;}));
/**
* @workInProgress
* @ngdoc directive
* @name angular.directive.ng:class-even
*
* @description
* The `ng:class-odd` and `ng:class-even` works exactly as
* {@link angular.directive.ng:class ng:class}, except it works in conjunction with `ng:repeat` and
* takes affect only on odd (even) rows.
*
* This directive can be applied only within a scope of an
* {@link angular.widget.@ng:repeat ng:repeat}.
*
* @element ANY
* @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. The result
* of the evaluation can be a string representing space delimited class names or an array.
*
* @example
<doc:example>
<doc:source>
<ol ng:init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng:repeat="name in names">
<span ng:class-odd="'ng-format-negative'"
ng:class-even="'ng-input-indicator-wait'">
{{name}}
</span>
</li>
</ol>
</doc:source>
<doc:scenario>
it('should check ng:class-odd and ng:class-even', function(){
expect(element('.doc-example-live li:first span').prop('className')).
toMatch(/ng-format-negative/);
expect(element('.doc-example-live li:last span').prop('className')).
toMatch(/ng-input-indicator-wait/);
});
</doc:scenario>
</doc:example>
*/
angularDirective("ng:class-even", ngClass(function(i){return i % 2 === 1;}));
/**
* @workInProgress
* @ngdoc directive
* @name angular.directive.ng:show
*
* @description
* The `ng:show` and `ng:hide` directives show or hide a portion of the DOM tree (HTML)
* conditionally.
*
* @element ANY
* @param {expression} expression If the {@link guide/dev_guide.expressions expression} is truthy
* then the element is shown or hidden respectively.
*
* @example
<doc:example>
<doc:source>
Click me: <input type="checkbox" name="checked"><br/>
Show: <span ng:show="checked">I show up when your checkbox is checked.</span> <br/>
Hide: <span ng:hide="checked">I hide when your checkbox is checked.</span>
</doc:source>
<doc:scenario>
it('should check ng:show / ng:hide', function(){
expect(element('.doc-example-live span:first:hidden').count()).toEqual(1);
expect(element('.doc-example-live span:last:visible').count()).toEqual(1);
input('checked').check();
expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
});
</doc:scenario>
</doc:example>
*/
angularDirective("ng:show", function(expression, element){
return function(element){
this.$watch(expression, function(scope, value){
element.css('display', toBoolean(value) ? '' : 'none');
});
};
});
/**
* @workInProgress
* @ngdoc directive
* @name angular.directive.ng:hide
*
* @description
* The `ng:hide` and `ng:show` directives hide or show a portion
* of the HTML conditionally.
*
* @element ANY
* @param {expression} expression If the {@link guide/dev_guide.expressions expression} truthy then
* the element is shown or hidden respectively.
*
* @example
<doc:example>
<doc:source>
Click me: <input type="checkbox" name="checked"><br/>
Show: <span ng:show="checked">I show up when you checkbox is checked?</span> <br/>
Hide: <span ng:hide="checked">I hide when you checkbox is checked?</span>
</doc:source>
<doc:scenario>
it('should check ng:show / ng:hide', function(){
expect(element('.doc-example-live span:first:hidden').count()).toEqual(1);
expect(element('.doc-example-live span:last:visible').count()).toEqual(1);
input('checked').check();
expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
});
</doc:scenario>
</doc:example>
*/
angularDirective("ng:hide", function(expression, element){
return function(element){
this.$watch(expression, function(scope, value){
element.css('display', toBoolean(value) ? 'none' : '');
});
};
});
/**
* @workInProgress
* @ngdoc directive
* @name angular.directive.ng:style
*
* @description
* The ng:style allows you to set CSS style on an HTML element conditionally.
*
* @element ANY
* @param {expression} expression {@link guide/dev_guide.expressions Expression} which evals to an
* object whose keys are CSS style names and values are corresponding values for those CSS
* keys.
*
* @example
<doc:example>
<doc:source>
<input type="button" value="set" ng:click="myStyle={color:'red'}">
<input type="button" value="clear" ng:click="myStyle={}">
<br/>
<span ng:style="myStyle">Sample Text</span>
<pre>myStyle={{myStyle}}</pre>
</doc:source>
<doc:scenario>
it('should check ng:style', function(){
expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
element('.doc-example-live :button[value=set]').click();
expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)');
element('.doc-example-live :button[value=clear]').click();
expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
});
</doc:scenario>
</doc:example>
*/
angularDirective("ng:style", function(expression, element){
// TODO(i): this is inefficient (runs on every $digest) and obtrusive (overrides 3rd part css)
// we should change it in a similar way as I changed ng:class
return function(element){
var resetStyle = getStyle(element);
this.$watch(function(scope){
var style = scope.$eval(expression) || {}, key, mergedStyle = {};
for(key in style) {
if (resetStyle[key] === undefined) resetStyle[key] = '';
mergedStyle[key] = style[key];
}
for(key in resetStyle) {
mergedStyle[key] = mergedStyle[key] || resetStyle[key];
}
element.css(mergedStyle);
});
};
});
/**
* @ngdoc directive
* @name angular.directive.ng:cloak
*
* @description
* The `ng:cloak` directive is used to prevent the Angular html template from being briefly
* displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
* directive to avoid the undesirable flicker effect caused by the html template display.
*
* The directive can be applied to the `<body>` element, but typically a fine-grained application is
* prefered in order to benefit from progressive rendering of the browser view.
*
* `ng:cloak` works in cooperation with a css rule that is embedded within `angular.js` and
* `angular.min.js` files. Following is the css rule:
*
* <pre>
* [ng\:cloak], .ng-cloak {
* display: none;
* }
* </pre>
*
* When this css rule is loaded by the browser, all html elements (including their children) that
* are tagged with the `ng:cloak` directive are hidden. When Angular comes across this directive
* during the compilation of the template it deletes the `ng:cloak` element attribute, which
* makes the compiled element visible.
*
* For the best result, `angular.js` script must be loaded in the head section of the html file;
* alternatively, the css rule (above) must be included in the external stylesheet of the
* application.
*
* Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
* cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
* class `ng-cloak` in addition to `ng:cloak` directive as shown in the example below.
*
* @element ANY
*
* @example
<doc:example>
<doc:source>
<div id="template1" ng:cloak>{{ 'hello' }}</div>
<div id="template2" ng:cloak class="ng-cloak">{{ 'hello IE7' }}</div>
</doc:source>
<doc:scenario>
it('should remove the template directive and css class', function() {
expect(element('.doc-example-live #template1').attr('ng:cloak')).
not().toBeDefined();
expect(element('.doc-example-live #template2').attr('ng:cloak')).
not().toBeDefined();
});
</doc:scenario>
</doc:example>
*
*/
angularDirective("ng:cloak", function(expression, element) {
element.removeAttr('ng:cloak');
element.removeClass('ng-cloak');
});
/**
* @ngdoc overview
* @name angular.markup
* @description
*
* Angular markup transforms the content of DOM elements or portions of the content into other
* text or DOM elements for further compilation.
*
* Markup extensions do not themselves produce linking functions. Think of markup as a way to
* produce shorthand for a {@link angular.widget widget} or a {@link angular.directive directive}.
*
* The most prominent example of a markup in Angular is the built-in, double curly markup
* `{{expression}}`, which is shorthand for `<span ng:bind="expression"></span>`.
*
* Create custom markup like this:
*
* <pre>
* angular.markup('newMarkup', function(text, textNode, parentElement){
* //tranformation code
* });
* </pre>
*
* For more information, see {@link guide/dev_guide.compiler.markup Understanding Angular Markup}
* in the Angular Developer Guide.
*/
/**
* @ngdoc overview
* @name angular.attrMarkup
* @description
*
* Attribute markup allows you to modify the state of an attribute's text.
*
* Attribute markup extends the Angular complier in a way similar to {@link angular.markup},
* which allows you to modify the content of a node.
*
* The most prominent example of an attribute markup in Angular is the built-in double curly markup
* which is a shorthand for {@link angular.directive.ng:bind-attr ng:bind-attr}.
*
* ## Example
*
* <pre>
* angular.attrMarkup('newAttrMarkup', function(attrValue, attrName, element){
* //tranformation code
* });
* </pre>
*
* For more information about Angular attribute markup, see {@link guide/dev_guide.compiler.markup
* Understanding Angular Markup} in the Angular Developer Guide.
*/
function parseBindings(string) {
var results = [];
var lastIndex = 0;
var index;
while((index = string.indexOf('{{', lastIndex)) > -1) {
if (lastIndex < index)
results.push(string.substr(lastIndex, index - lastIndex));
lastIndex = index;
index = string.indexOf('}}', index);
index = index < 0 ? string.length : index + 2;
results.push(string.substr(lastIndex, index - lastIndex));
lastIndex = index;
}
if (lastIndex != string.length)
results.push(string.substr(lastIndex, string.length - lastIndex));
return results.length === 0 ? [ string ] : results;
}
function binding(string) {
var binding = string.replace(/\n/gm, ' ').match(/^\{\{(.*)\}\}$/);
return binding ? binding[1] : null;
}
function hasBindings(bindings) {
return bindings.length > 1 || binding(bindings[0]) !== null;
}
angularTextMarkup('{{}}', function(text, textNode, parentElement) {
var bindings = parseBindings(text),
self = this;
if (hasBindings(bindings)) {
if (isLeafNode(parentElement[0])) {
parentElement.attr('ng:bind-template', text);
} else {
var cursor = textNode, newElement;
forEach(parseBindings(text), function(text){
var exp = binding(text);
if (exp) {
newElement = jqLite('<span>');
newElement.attr('ng:bind', exp);
} else {
newElement = jqLite(document.createTextNode(text));
}
if (msie && text.charAt(0) == ' ') {
newElement = jqLite('<span> </span>');
var nbsp = newElement.html();
newElement.text(text.substr(1));
newElement.html(nbsp + newElement.html());
}
cursor.after(newElement);
cursor = newElement;
});
textNode.remove();
}
}
});
/**
* This tries to normalize the behavior of value attribute across browsers. If value attribute is
* not specified, then specify it to be that of the text.
*/
angularTextMarkup('option', function(text, textNode, parentElement){
if (lowercase(nodeName_(parentElement)) == 'option') {
if (msie <= 7) {
// In IE7 The issue is that there is no way to see if the value was specified hence
// we have to resort to parsing HTML;
htmlParser(parentElement[0].outerHTML, {
start: function(tag, attrs) {
if (isUndefined(attrs.value)) {
parentElement.attr('value', text);
}
}
});
} else if (parentElement[0].getAttribute('value') == null) {
// jQuery does normalization on 'value' so we have to bypass it.
parentElement.attr('value', text);
}
}
});
/**
* @workInProgress
* @ngdoc directive
* @name angular.directive.ng:href
*
* @description
* Using <angular/> markup like {{hash}} in an href attribute makes
* the page open to a wrong URL, if the user clicks that link before
* angular has a chance to replace the {{hash}} with actual URL, the
* link will be broken and will most likely return a 404 error.
* The `ng:href` solves this problem by placing the `href` in the
* `ng:` namespace.
*
* The buggy way to write it:
* <pre>
* <a href="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* The correct way to write it:
* <pre>
* <a ng:href="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* @element ANY
* @param {template} template any string which can contain `{{}}` markup.
*
* @example
* This example uses `link` variable inside `href` attribute:
<doc:example>
<doc:source>
<input name="value" /><br />
<a id="link-1" href ng:click="value = 1">link 1</a> (link, don't reload)<br />
<a id="link-2" href="" ng:click="value = 2">link 2</a> (link, don't reload)<br />
<a id="link-3" ng:href="/{{'123'}}" ng:ext-link>link 3</a> (link, reload!)<br />
<a id="link-4" href="" name="xx" ng:click="value = 4">anchor</a> (link, don't reload)<br />
<a id="link-5" name="xxx" ng:click="value = 5">anchor</a> (no link)<br />
<a id="link-6" ng:href="/{{value}}" ng:ext-link>link</a> (link, change hash)
</doc:source>
<doc:scenario>
it('should execute ng:click but not reload when href without value', function() {
element('#link-1').click();
expect(input('value').val()).toEqual('1');
expect(element('#link-1').attr('href')).toBe("");
});
it('should execute ng:click but not reload when href empty string', function() {
element('#link-2').click();
expect(input('value').val()).toEqual('2');
expect(element('#link-2').attr('href')).toBe("");
});
it('should execute ng:click and change url when ng:href specified', function() {
expect(element('#link-3').attr('href')).toBe("/123");
element('#link-3').click();
expect(browser().location().path()).toEqual('/123');
});
it('should execute ng:click but not reload when href empty string and name specified', function() {
element('#link-4').click();
expect(input('value').val()).toEqual('4');
expect(element('#link-4').attr('href')).toBe("");
});
it('should execute ng:click but not reload when no href but name specified', function() {
element('#link-5').click();
expect(input('value').val()).toEqual('5');
expect(element('#link-5').attr('href')).toBe(undefined);
});
it('should only change url when only ng:href', function() {
input('value').enter('6');
expect(element('#link-6').attr('href')).toBe("/6");
element('#link-6').click();
expect(browser().location().path()).toEqual('/6');
});
</doc:scenario>
</doc:example>
*/
/**
* @workInProgress
* @ngdoc directive
* @name angular.directive.ng:src
*
* @description
* Using <angular/> markup like `{{hash}}` in a `src` attribute doesn't
* work right: The browser will fetch from the URL with the literal
* text `{{hash}}` until <angular/> replaces the expression inside
* `{{hash}}`. The `ng:src` attribute solves this problem by placing
* the `src` attribute in the `ng:` namespace.
*
* The buggy way to write it:
* <pre>
* <img src="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* The correct way to write it:
* <pre>
* <img ng:src="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* @element ANY
* @param {template} template any string which can contain `{{}}` markup.
*/
/**
* @workInProgress
* @ngdoc directive
* @name angular.directive.ng:disabled
*
* @description
*
* The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
* <pre>
* <div ng:init="scope = { isDisabled: false }">
* <button disabled="{{scope.isDisabled}}">Disabled</button>
* </div>
* </pre>
*
* The HTML specs do not require browsers to preserve the special attributes such as disabled.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce ng:disabled.
*
* @example
<doc:example>
<doc:source>
Click me to toggle: <input type="checkbox" name="checked"><br/>
<button name="button" ng:disabled="{{checked}}">Button</button>
</doc:source>
<doc:scenario>
it('should toggle button', function() {
expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element ANY
* @param {template} template any string which can contain '{{}}' markup.
*/
/**
* @workInProgress
* @ngdoc directive
* @name angular.directive.ng:checked
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as checked.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce ng:checked.
* @example
<doc:example>
<doc:source>
Check me to check both: <input type="checkbox" name="master"><br/>
<input id="checkSlave" type="checkbox" ng:checked="{{master}}">
</doc:source>
<doc:scenario>
it('should check both checkBoxes', function() {
expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy();
input('master').check();
expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element ANY
* @param {template} template any string which can contain '{{}}' markup.
*/
/**
* @workInProgress
* @ngdoc directive
* @name angular.directive.ng:multiple
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as multiple.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce ng:multiple.
*
* @example
<doc:example>
<doc:source>
Check me check multiple: <input type="checkbox" name="checked"><br/>
<select id="select" ng:multiple="{{checked}}">
<option>Misko</option>
<option>Igor</option>
<option>Vojta</option>
<option>Di</option>
</select>
</doc:source>
<doc:scenario>
it('should toggle multiple', function() {
expect(element('.doc-example-live #select').prop('multiple')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live #select').prop('multiple')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element ANY
* @param {template} template any string which can contain '{{}}' markup.
*/
/**
* @workInProgress
* @ngdoc directive
* @name angular.directive.ng:readonly
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as readonly.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce ng:readonly.
* @example
<doc:example>
<doc:source>
Check me to make text readonly: <input type="checkbox" name="checked"><br/>
<input type="text" ng:readonly="{{checked}}" value="I'm Angular"/>
</doc:source>
<doc:scenario>
it('should toggle readonly attr', function() {
expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element ANY
* @param {template} template any string which can contain '{{}}' markup.
*/
/**
* @workInProgress
* @ngdoc directive
* @name angular.directive.ng:selected
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as selected.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce ng:selected.
* @example
<doc:example>
<doc:source>
Check me to select: <input type="checkbox" name="checked"><br/>
<select>
<option>Hello!</option>
<option id="greet" ng:selected="{{checked}}">Greetings!</option>
</select>
</doc:source>
<doc:scenario>
it('should select Greetings!', function() {
expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy();
});
</doc:scenario>
</doc:example>
* @element ANY
* @param {template} template any string which can contain '{{}}' markup.
*/
var NG_BIND_ATTR = 'ng:bind-attr';
var SPECIAL_ATTRS = {};
forEach('src,href,checked,disabled,multiple,readonly,selected'.split(','), function(name) {
SPECIAL_ATTRS['ng:' + name] = name;
});
angularAttrMarkup('{{}}', function(value, name, element){
// don't process existing attribute markup
if (angularDirective(name) || angularDirective("@" + name)) return;
if (msie && name == 'src')
value = decodeURI(value);
var bindings = parseBindings(value),
bindAttr;
if (hasBindings(bindings) || SPECIAL_ATTRS[name]) {
element.removeAttr(name);
bindAttr = fromJson(element.attr(NG_BIND_ATTR) || "{}");
bindAttr[SPECIAL_ATTRS[name] || name] = value;
element.attr(NG_BIND_ATTR, toJson(bindAttr));
}
});
/**
* @workInProgress
* @ngdoc overview
* @name angular.widget
* @description
*
* An angular widget can be either a custom attribute that modifies an existing DOM element or an
* entirely new DOM element.
*
* During html compilation, widgets are processed after {@link angular.markup markup}, but before
* {@link angular.directive directives}.
*
* Following is the list of built-in angular widgets:
*
* * {@link angular.widget.@ng:format ng:format} - Formats data for display to user and for storage.
* * {@link angular.widget.@ng:non-bindable ng:non-bindable} - Blocks angular from processing an
* HTML element.
* * {@link angular.widget.@ng:repeat ng:repeat} - Creates and manages a collection of cloned HTML
* elements.
* * {@link angular.widget.@ng:required ng:required} - Verifies presence of user input.
* * {@link angular.widget.@ng:validate ng:validate} - Validates content of user input.
* * {@link angular.widget.HTML HTML input elements} - Standard HTML input elements data-bound by
* angular.
* * {@link angular.widget.ng:view ng:view} - Works with $route to "include" partial templates
* * {@link angular.widget.ng:switch ng:switch} - Conditionally changes DOM structure
* * {@link angular.widget.ng:include ng:include} - Includes an external HTML fragment
*
* For more information about angular widgets, see {@link guide/dev_guide.compiler.widgets
* Understanding Angular Widgets} in the angular Developer Guide.
*/
/**
* @workInProgress
* @ngdoc widget
* @name angular.widget.HTML
*
* @description
* The most common widgets you will use will be in the form of the
* standard HTML set. These widgets are bound using the `name` attribute
* to an expression. In addition, they can have `ng:validate`, `ng:required`,
* `ng:format`, `ng:change` attribute to further control their behavior.
*
* @usageContent
* see example below for usage
*
* <input type="text|checkbox|..." ... />
* <textarea ... />
* <select ...>
* <option>...</option>
* </select>
*
* @example
<doc:example>
<doc:source>
<table style="font-size:.9em;">
<tr>
<th>Name</th>
<th>Format</th>
<th>HTML</th>
<th>UI</th>
<th ng:non-bindable>{{input#}}</th>
</tr>
<tr>
<th>text</th>
<td>String</td>
<td><tt><input type="text" name="input1"></tt></td>
<td><input type="text" name="input1" size="4"></td>
<td><tt>{{input1|json}}</tt></td>
</tr>
<tr>
<th>textarea</th>
<td>String</td>
<td><tt><textarea name="input2"></textarea></tt></td>
<td><textarea name="input2" cols='6'></textarea></td>
<td><tt>{{input2|json}}</tt></td>
</tr>
<tr>
<th>radio</th>
<td>String</td>
<td><tt>
<input type="radio" name="input3" value="A"><br>
<input type="radio" name="input3" value="B">
</tt></td>
<td>
<input type="radio" name="input3" value="A">
<input type="radio" name="input3" value="B">
</td>
<td><tt>{{input3|json}}</tt></td>
</tr>
<tr>
<th>checkbox</th>
<td>Boolean</td>
<td><tt><input type="checkbox" name="input4" value="checked"></tt></td>
<td><input type="checkbox" name="input4" value="checked"></td>
<td><tt>{{input4|json}}</tt></td>
</tr>
<tr>
<th>pulldown</th>
<td>String</td>
<td><tt>
<select name="input5"><br>
<option value="c">C</option><br>
<option value="d">D</option><br>
</select><br>
</tt></td>
<td>
<select name="input5">
<option value="c">C</option>
<option value="d">D</option>
</select>
</td>
<td><tt>{{input5|json}}</tt></td>
</tr>
<tr>
<th>multiselect</th>
<td>Array</td>
<td><tt>
<select name="input6" multiple size="4"><br>
<option value="e">E</option><br>
<option value="f">F</option><br>
</select><br>
</tt></td>
<td>
<select name="input6" multiple size="4">
<option value="e">E</option>
<option value="f">F</option>
</select>
</td>
<td><tt>{{input6|json}}</tt></td>
</tr>
</table>
</doc:source>
<doc:scenario>
it('should exercise text', function(){
input('input1').enter('Carlos');
expect(binding('input1')).toEqual('"Carlos"');
});
it('should exercise textarea', function(){
input('input2').enter('Carlos');
expect(binding('input2')).toEqual('"Carlos"');
});
it('should exercise radio', function(){
expect(binding('input3')).toEqual('null');
input('input3').select('A');
expect(binding('input3')).toEqual('"A"');
input('input3').select('B');
expect(binding('input3')).toEqual('"B"');
});
it('should exercise checkbox', function(){
expect(binding('input4')).toEqual('false');
input('input4').check();
expect(binding('input4')).toEqual('true');
});
it('should exercise pulldown', function(){
expect(binding('input5')).toEqual('"c"');
select('input5').option('d');
expect(binding('input5')).toEqual('"d"');
});
it('should exercise multiselect', function(){
expect(binding('input6')).toEqual('[]');
select('input6').options('e');
expect(binding('input6')).toEqual('["e"]');
select('input6').options('e', 'f');
expect(binding('input6')).toEqual('["e","f"]');
});
</doc:scenario>
</doc:example>
*/
function modelAccessor(scope, element) {
var expr = element.attr('name');
var exprFn, assignFn;
if (expr) {
exprFn = parser(expr).assignable();
assignFn = exprFn.assign;
if (!assignFn) throw new Error("Expression '" + expr + "' is not assignable.");
return {
get: function() {
return exprFn(scope);
},
set: function(value) {
if (value !== undefined) {
assignFn(scope, value);
}
}
};
}
}
function modelFormattedAccessor(scope, element) {
var accessor = modelAccessor(scope, element),
formatterName = element.attr('ng:format') || NOOP,
formatter = compileFormatter(formatterName);
if (accessor) {
return {
get: function() {
return formatter.format(scope, accessor.get());
},
set: function(value) {
return accessor.set(formatter.parse(scope, value));
}
};
}
}
function compileValidator(expr) {
return parser(expr).validator()();
}
function compileFormatter(expr) {
return parser(expr).formatter()();
}
/**
* @workInProgress
* @ngdoc widget
* @name angular.widget.@ng:validate
*
* @description
* The `ng:validate` attribute widget validates the user input. If the input does not pass
* validation, the `ng-validation-error` CSS class and the `ng:error` attribute are set on the input
* element. Check out {@link angular.validator validators} to find out more.
*
* @param {string} validator The name of a built-in or custom {@link angular.validator validator} to
* to be used.
*
* @element INPUT
* @css ng-validation-error
*
* @example
* This example shows how the input element becomes red when it contains invalid input. Correct
* the input to make the error disappear.
*
<doc:example>
<doc:source>
I don't validate:
<input type="text" name="value" value="NotANumber"><br/>
I need an integer or nothing:
<input type="text" name="value" ng:validate="integer"><br/>
</doc:source>
<doc:scenario>
it('should check ng:validate', function(){
expect(element('.doc-example-live :input:last').prop('className')).
toMatch(/ng-validation-error/);
input('value').enter('123');
expect(element('.doc-example-live :input:last').prop('className')).
not().toMatch(/ng-validation-error/);
});
</doc:scenario>
</doc:example>
*/
/**
* @workInProgress
* @ngdoc widget
* @name angular.widget.@ng:required
*
* @description
* The `ng:required` attribute widget validates that the user input is present. It is a special case
* of the {@link angular.widget.@ng:validate ng:validate} attribute widget.
*
* @element INPUT
* @css ng-validation-error
*
* @example
* This example shows how the input element becomes red when it contains invalid input. Correct
* the input to make the error disappear.
*
<doc:example>
<doc:source>
I cannot be blank: <input type="text" name="value" ng:required><br/>
</doc:source>
<doc:scenario>
it('should check ng:required', function(){
expect(element('.doc-example-live :input').prop('className')).
toMatch(/ng-validation-error/);
input('value').enter('123');
expect(element('.doc-example-live :input').prop('className')).
not().toMatch(/ng-validation-error/);
});
</doc:scenario>
</doc:example>
*/
/**
* @workInProgress
* @ngdoc widget
* @name angular.widget.@ng:format
*
* @description
* The `ng:format` attribute widget formats stored data to user-readable text and parses the text
* back to the stored form. You might find this useful, for example, if you collect user input in a
* text field but need to store the data in the model as a list. Check out
* {@link angular.formatter formatters} to learn more.
*
* @param {string} formatter The name of the built-in or custom {@link angular.formatter formatter}
* to be used.
*
* @element INPUT
*
* @example
* This example shows how the user input is converted from a string and internally represented as an
* array.
*
<doc:example>
<doc:source>
Enter a comma separated list of items:
<input type="text" name="list" ng:format="list" value="table, chairs, plate">
<pre>list={{list}}</pre>
</doc:source>
<doc:scenario>
it('should check ng:format', function(){
expect(binding('list')).toBe('list=["table","chairs","plate"]');
input('list').enter(',,, a ,,,');
expect(binding('list')).toBe('list=["a"]');
});
</doc:scenario>
</doc:example>
*/
function valueAccessor(scope, element) {
var validatorName = element.attr('ng:validate') || NOOP,
validator = compileValidator(validatorName),
requiredExpr = element.attr('ng:required'),
formatterName = element.attr('ng:format') || NOOP,
formatter = compileFormatter(formatterName),
format, parse, lastError, required,
invalidWidgets = scope.$service('$invalidWidgets') || {markValid:noop, markInvalid:noop};
if (!validator) throw "Validator named '" + validatorName + "' not found.";
format = formatter.format;
parse = formatter.parse;
if (requiredExpr) {
scope.$watch(requiredExpr, function(scope, newValue) {
required = newValue;
validate();
});
} else {
required = requiredExpr === '';
}
element.data($$validate, validate);
return {
get: function(){
if (lastError)
elementError(element, NG_VALIDATION_ERROR, null);
try {
var value = parse(scope, element.val());
validate();
return value;
} catch (e) {
lastError = e;
elementError(element, NG_VALIDATION_ERROR, e);
}
},
set: function(value) {
var oldValue = element.val(),
newValue = format(scope, value);
if (oldValue != newValue) {
element.val(newValue || ''); // needed for ie
}
validate();
}
};
function validate() {
var value = trim(element.val());
if (element[0].disabled || element[0].readOnly) {
elementError(element, NG_VALIDATION_ERROR, null);
invalidWidgets.markValid(element);
} else {
var error, validateScope = inherit(scope, {$element:element});
error = required && !value
? 'Required'
: (value ? validator(validateScope, value) : null);
elementError(element, NG_VALIDATION_ERROR, error);
lastError = error;
if (error) {
invalidWidgets.markInvalid(element);
} else {
invalidWidgets.markValid(element);
}
}
}
}
function checkedAccessor(scope, element) {
var domElement = element[0], elementValue = domElement.value;
return {
get: function(){
return !!domElement.checked;
},
set: function(value){
domElement.checked = toBoolean(value);
}
};
}
function radioAccessor(scope, element) {
var domElement = element[0];
return {
get: function(){
return domElement.checked ? domElement.value : null;
},
set: function(value){
domElement.checked = value == domElement.value;
}
};
}
function optionsAccessor(scope, element) {
var formatterName = element.attr('ng:format') || NOOP,
formatter = compileFormatter(formatterName);
return {
get: function(){
var values = [];
forEach(element[0].options, function(option){
if (option.selected) values.push(formatter.parse(scope, option.value));
});
return values;
},
set: function(values){
var keys = {};
forEach(values, function(value){
keys[formatter.format(scope, value)] = true;
});
forEach(element[0].options, function(option){
option.selected = keys[option.value];
});
}
};
}
function noopAccessor() { return { get: noop, set: noop }; }
/*
* TODO: refactor
*
* The table below is not quite right. In some cases the formatter is on the model side
* and in some cases it is on the view side. This is a historical artifact
*
* The concept of model/view accessor is useful for anyone who is trying to develop UI, and
* so it should be exposed to others. There should be a form object which keeps track of the
* accessors and also acts as their factory. It should expose it as an object and allow
* the validator to publish errors to it, so that the the error messages can be bound to it.
*
*/
var textWidget = inputWidget('keydown change', modelAccessor, valueAccessor, initWidgetValue(), true),
INPUT_TYPE = {
'text': textWidget,
'textarea': textWidget,
'hidden': textWidget,
'password': textWidget,
'checkbox': inputWidget('click', modelFormattedAccessor, checkedAccessor, initWidgetValue(false)),
'radio': inputWidget('click', modelFormattedAccessor, radioAccessor, radioInit),
'select-one': inputWidget('change', modelAccessor, valueAccessor, initWidgetValue(null)),
'select-multiple': inputWidget('change', modelAccessor, optionsAccessor, initWidgetValue([]))
// 'file': fileWidget???
};
function initWidgetValue(initValue) {
return function (model, view) {
var value = view.get();
if (!value && isDefined(initValue)) {
value = copy(initValue);
}
if (isUndefined(model.get()) && isDefined(value)) {
model.set(value);
}
};
}
function radioInit(model, view, element) {
var modelValue = model.get(), viewValue = view.get(), input = element[0];
input.checked = false;
input.name = this.$id + '@' + input.name;
if (isUndefined(modelValue)) {
model.set(modelValue = null);
}
if (modelValue == null && viewValue !== null) {
model.set(viewValue);
}
view.set(modelValue);
}
/**
* @workInProgress
* @ngdoc directive
* @name angular.directive.ng:change
*
* @description
* The directive executes an expression whenever the input widget changes.
*
* @element INPUT
* @param {expression} expression to execute.
*
* @example
* @example
<doc:example>
<doc:source>
<div ng:init="checkboxCount=0; textCount=0"></div>
<input type="text" name="text" ng:change="textCount = 1 + textCount">
changeCount {{textCount}}<br/>
<input type="checkbox" name="checkbox" ng:change="checkboxCount = 1 + checkboxCount">
changeCount {{checkboxCount}}<br/>
</doc:source>
<doc:scenario>
it('should check ng:change', function(){
expect(binding('textCount')).toBe('0');
expect(binding('checkboxCount')).toBe('0');
using('.doc-example-live').input('text').enter('abc');
expect(binding('textCount')).toBe('1');
expect(binding('checkboxCount')).toBe('0');
using('.doc-example-live').input('checkbox').check();
expect(binding('textCount')).toBe('1');
expect(binding('checkboxCount')).toBe('1');
});
</doc:scenario>
</doc:example>
*/
function inputWidget(events, modelAccessor, viewAccessor, initFn, textBox) {
return annotate('$defer', function($defer, element) {
var scope = this,
model = modelAccessor(scope, element),
view = viewAccessor(scope, element),
ngChange = element.attr('ng:change') || noop,
lastValue;
if (model) {
initFn.call(scope, model, view, element);
scope.$eval(element.attr('ng:init') || noop);
element.bind(events, function(event){
function handler(){
var value = view.get();
if (!textBox || value != lastValue) {
model.set(value);
lastValue = model.get();
scope.$eval(ngChange);
}
}
event.type == 'keydown' ? $defer(handler) : scope.$apply(handler);
});
scope.$watch(model.get, function(scope, value) {
if (!equals(lastValue, value)) {
view.set(lastValue = value);
}
});
}
});
}
function inputWidgetSelector(element){
this.directives(true);
this.descend(true);
return INPUT_TYPE[lowercase(element[0].type)] || noop;
}
angularWidget('input', inputWidgetSelector);
angularWidget('textarea', inputWidgetSelector);
/**
* @workInProgress
* @ngdoc directive
* @name angular.directive.ng:options
*
* @description
* Dynamically generate a list of `<option>` elements for a `<select>` element using an array or
* an object obtained by evaluating the `ng:options` expression.
*
* When an item in the select menu is select, the value of array element or object property
* represented by the selected option will be bound to the model identified by the `name` attribute
* of the parent select element.
*
* Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
* be nested into the `<select>` element. This element will then represent `null` or "not selected"
* option. See example below for demonstration.
*
* Note: `ng:options` provides iterator facility for `<option>` element which must be used instead
* of {@link angular.widget.@ng:repeat ng:repeat}. `ng:repeat` is not suitable for use with
* `<option>` element because of the following reasons:
*
* * value attribute of the option element that we need to bind to requires a string, but the
* source of data for the iteration might be in a form of array containing objects instead of
* strings
* * {@link angular.widget.@ng:repeat ng:repeat} unrolls after the select binds causing
* incorect rendering on most browsers.
* * binding to a value not in list confuses most browsers.
*
* @element select
* @param {comprehension_expression} comprehension in one of the following forms:
*
* * for array data sources:
* * `label` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`for`** `value` **`in`** `array`
* * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array`
* * for object data sources:
* * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`group by`** `group`
* **`for` `(`**`key`**`,`** `value`**`) in`** `object`
*
* Where:
*
* * `array` / `object`: an expression which evaluates to an array / object to iterate over.
* * `value`: local variable which will refer to each item in the `array` or each property value
* of `object` during iteration.
* * `key`: local variable which will refer to a property name in `object` during iteration.
* * `label`: The result of this expression will be the label for `<option>` element. The
* `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
* * `select`: The result of this expression will be bound to the model of the parent `<select>`
* element. If not specified, `select` expression will default to `value`.
* * `group`: The result of this expression will be used to group options using the `<optgroup>`
* DOM element.
*
* @example
<doc:example>
<doc:source>
<script>
function MyCntrl(){
this.colors = [
{name:'black', shade:'dark'},
{name:'white', shade:'light'},
{name:'red', shade:'dark'},
{name:'blue', shade:'dark'},
{name:'yellow', shade:'light'}
];
this.color = this.colors[2]; // red
}
</script>
<div ng:controller="MyCntrl">
<ul>
<li ng:repeat="color in colors">
Name: <input name="color.name">
[<a href ng:click="colors.$remove(color)">X</a>]
</li>
<li>
[<a href ng:click="colors.push({})">add</a>]
</li>
</ul>
<hr/>
Color (null not allowed):
<select name="color" ng:options="c.name for c in colors"></select><br>
Color (null allowed):
<div class="nullable">
<select name="color" ng:options="c.name for c in colors">
<option value="">-- chose color --</option>
</select>
</div><br/>
Color grouped by shade:
<select name="color" ng:options="c.name group by c.shade for c in colors">
</select><br/>
Select <a href ng:click="color={name:'not in list'}">bogus</a>.<br>
<hr/>
Currently selected: {{ {selected_color:color} }}
<div style="border:solid 1px black; height:20px"
ng:style="{'background-color':color.name}">
</div>
</div>
</doc:source>
<doc:scenario>
it('should check ng:options', function(){
expect(binding('color')).toMatch('red');
select('color').option('0');
expect(binding('color')).toMatch('black');
using('.nullable').select('color').option('');
expect(binding('color')).toMatch('null');
});
</doc:scenario>
</doc:example>
*/
// 00001111100000000000222200000000000000000000003333000000000000044444444444444444000000000555555555555555550000000666666666666666660000000000000007777
var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/;
angularWidget('select', function(element){
this.descend(true);
this.directives(true);
var isMultiselect = element.attr('multiple'),
expression = element.attr('ng:options'),
onChange = expressionCompile(element.attr('ng:change') || ""),
match;
if (!expression) {
return inputWidgetSelector.call(this, element);
}
if (! (match = expression.match(NG_OPTIONS_REGEXP))) {
throw Error(
"Expected ng:options in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
" but got '" + expression + "'.");
}
var displayFn = expressionCompile(match[2] || match[1]),
valueName = match[4] || match[6],
keyName = match[5],
groupByFn = expressionCompile(match[3] || ''),
valueFn = expressionCompile(match[2] ? match[1] : valueName),
valuesFn = expressionCompile(match[7]),
// we can't just jqLite('<option>') since jqLite is not smart enough
// to create it in <select> and IE barfs otherwise.
optionTemplate = jqLite(document.createElement('option')),
optGroupTemplate = jqLite(document.createElement('optgroup')),
nullOption = false; // if false then user will not be able to select it
return function(selectElement){
// This is an array of array of existing option groups in DOM. We try to reuse these if possible
// optionGroupsCache[0] is the options with no option group
// optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
var optionGroupsCache = [[{element: selectElement, label:''}]],
scope = this,
model = modelAccessor(scope, element),
inChangeEvent;
// find existing special options
forEach(selectElement.children(), function(option){
if (option.value == '')
// User is allowed to select the null.
nullOption = {label:jqLite(option).text(), id:''};
});
selectElement.html(''); // clear contents
selectElement.bind('change', function(){
var optionGroup,
collection = valuesFn(scope) || [],
key = selectElement.val(),
tempScope = scope.$new(),
value, optionElement, index, groupIndex, length, groupLength;
// let's set a flag that the current model change is due to a change event.
// the default action of option selection will cause the appropriate option element to be
// deselected and another one to be selected - there is no need for us to be updating the DOM
// in this case.
inChangeEvent = true;
try {
if (isMultiselect) {
value = [];
for (groupIndex = 0, groupLength = optionGroupsCache.length;
groupIndex < groupLength;
groupIndex++) {
// list of options for that group. (first item has the parent)
optionGroup = optionGroupsCache[groupIndex];
for(index = 1, length = optionGroup.length; index < length; index++) {
if ((optionElement = optionGroup[index].element)[0].selected) {
if (keyName) tempScope[keyName] = key;
tempScope[valueName] = collection[optionElement.val()];
value.push(valueFn(tempScope));
}
}
}
} else {
if (key == '?') {
value = undefined;
} else if (key == ''){
value = null;
} else {
tempScope[valueName] = collection[key];
if (keyName) tempScope[keyName] = key;
value = valueFn(tempScope);
}
}
if (isDefined(value) && model.get() !== value) {
model.set(value);
onChange(scope);
}
scope.$root.$apply();
} finally {
tempScope = null; // TODO(misko): needs to be $destroy
inChangeEvent = false;
}
});
scope.$watch(function(scope) {
var optionGroups = {'':[]}, // Temporary location for the option groups before we render them
optionGroupNames = [''],
optionGroupName,
optionGroup,
option,
existingParent, existingOptions, existingOption,
values = valuesFn(scope) || [],
keys = values,
key,
groupLength, length,
fragment,
groupIndex, index,
optionElement,
optionScope = scope.$new(),
modelValue = model.get(),
selected,
selectedSet = false, // nothing is selected yet
isMulti = isMultiselect,
lastElement,
element;
try {
if (isMulti) {
selectedSet = new HashMap();
if (modelValue && isNumber(length = modelValue.length)) {
for (index = 0; index < length; index++) {
selectedSet.put(modelValue[index], true);
}
}
} else if (modelValue === null || nullOption) {
// if we are not multiselect, and we are null then we have to add the nullOption
optionGroups[''].push(extend({selected:modelValue === null, id:'', label:''}, nullOption));
selectedSet = true;
}
// If we have a keyName then we are iterating over on object. Grab the keys and sort them.
if(keyName) {
keys = [];
for (key in values) {
if (values.hasOwnProperty(key))
keys.push(key);
}
keys.sort();
}
// We now build up the list of options we need (we merge later)
for (index = 0; length = keys.length, index < length; index++) {
optionScope[valueName] = values[keyName ? optionScope[keyName]=keys[index]:index];
optionGroupName = groupByFn(optionScope) || '';
if (!(optionGroup = optionGroups[optionGroupName])) {
optionGroup = optionGroups[optionGroupName] = [];
optionGroupNames.push(optionGroupName);
}
if (isMulti) {
selected = !!selectedSet.remove(valueFn(optionScope));
} else {
selected = modelValue === valueFn(optionScope);
selectedSet = selectedSet || selected; // see if at least one item is selected
}
optionGroup.push({
id: keyName ? keys[index] : index, // either the index into array or key from object
label: displayFn(optionScope) || '', // what will be seen by the user
selected: selected // determine if we should be selected
});
}
optionGroupNames.sort();
if (!isMulti && !selectedSet) {
// nothing was selected, we have to insert the undefined item
optionGroups[''].unshift({id:'?', label:'', selected:true});
}
// Now we need to update the list of DOM nodes to match the optionGroups we computed above
for (groupIndex = 0, groupLength = optionGroupNames.length;
groupIndex < groupLength;
groupIndex++) {
// current option group name or '' if no group
optionGroupName = optionGroupNames[groupIndex];
// list of options for that group. (first item has the parent)
optionGroup = optionGroups[optionGroupName];
if (optionGroupsCache.length <= groupIndex) {
// we need to grow the optionGroups
optionGroupsCache.push(
existingOptions = [
existingParent = {
element: optGroupTemplate.clone().attr('label', optionGroupName),
label: optionGroup.label
}
]
);
selectElement.append(existingParent.element);
} else {
existingOptions = optionGroupsCache[groupIndex];
existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
// update the OPTGROUP label if not the same.
if (existingParent.label != optionGroupName) {
existingParent.element.attr('label', existingParent.label = optionGroupName);
}
}
lastElement = null; // start at the begining
for(index = 0, length = optionGroup.length; index < length; index++) {
option = optionGroup[index];
if ((existingOption = existingOptions[index+1])) {
// reuse elements
lastElement = existingOption.element;
if (existingOption.label !== option.label) {
lastElement.text(existingOption.label = option.label);
}
if (existingOption.id !== option.id) {
lastElement.val(existingOption.id = option.id);
}
if (!inChangeEvent && existingOption.selected !== option.selected) {
lastElement.prop('selected', (existingOption.selected = option.selected));
}
} else {
// grow elements
// jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
// in this version of jQuery on some browser the .text() returns a string
// rather then the element.
(element = optionTemplate.clone())
.val(option.id)
.attr('selected', option.selected)
.text(option.label);
existingOptions.push(existingOption = {
element: element,
label: option.label,
id: option.id,
selected: option.selected
});
if (lastElement) {
lastElement.after(element);
} else {
existingParent.element.append(element);
}
lastElement = element;
}
}
// remove any excessive OPTIONs in a group
index++; // increment since the existingOptions[0] is parent element not OPTION
while(existingOptions.length > index) {
existingOptions.pop().element.remove();
}
}
// remove any excessive OPTGROUPs from select
while(optionGroupsCache.length > groupIndex) {
optionGroupsCache.pop()[0].element.remove();
}
} finally {
optionScope.$destroy();
}
});
};
});
/**
* @workInProgress
* @ngdoc widget
* @name angular.widget.ng:include
*
* @description
* Fetches, compiles and includes an external HTML fragment.
*
* Keep in mind that Same Origin Policy applies to included resources
* (e.g. ng:include won't work for file:// access).
*
* @param {string} src angular expression evaluating to URL. If the source is a string constant,
* make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`.
* @param {Scope=} [scope=new_child_scope] optional expression which evaluates to an
* instance of angular.scope to set the HTML fragment to.
* @param {string=} onload Expression to evaluate when a new partial is loaded.
*
* @example
<doc:example>
<doc:source jsfiddle="false">
<select name="url">
<option value="examples/ng-include/template1.html">template1.html</option>
<option value="examples/ng-include/template2.html">template2.html</option>
<option value="">(blank)</option>
</select>
url of the template: <tt><a href="{{url}}">{{url}}</a></tt>
<hr/>
<ng:include src="url"></ng:include>
</doc:source>
<doc:scenario>
it('should load template1.html', function(){
expect(element('.doc-example-live ng\\:include').text()).
toBe('Content of template1.html\n');
});
it('should load template2.html', function(){
select('url').option('examples/ng-include/template2.html');
expect(element('.doc-example-live ng\\:include').text()).
toBe('Content of template2.html\n');
});
it('should change to blank', function(){
select('url').option('');
expect(element('.doc-example-live ng\\:include').text()).toEqual('');
});
</doc:scenario>
</doc:example>
*/
angularWidget('ng:include', function(element){
var compiler = this,
srcExp = element.attr("src"),
scopeExp = element.attr("scope") || '',
onloadExp = element[0].getAttribute('onload') || ''; //workaround for jquery bug #7537
if (element[0]['ng:compiled']) {
this.descend(true);
this.directives(true);
} else {
element[0]['ng:compiled'] = true;
return extend(function(xhr, element){
var scope = this,
changeCounter = 0,
releaseScopes = [],
childScope,
oldScope;
function incrementChange(){ changeCounter++;}
this.$watch(srcExp, incrementChange);
this.$watch(function(scope){
var newScope = scope.$eval(scopeExp);
if (newScope !== oldScope) {
oldScope = newScope;
incrementChange();
}
});
this.$watch(function(){return changeCounter;}, function(scope) {
var src = scope.$eval(srcExp),
useScope = scope.$eval(scopeExp);
while(releaseScopes.length) {
releaseScopes.pop().$destroy();
}
if (src) {
xhr('GET', src, null, function(code, response){
element.html(response);
if (useScope) {
childScope = useScope;
} else {
releaseScopes.push(childScope = scope.$new());
}
compiler.compile(element)(childScope);
scope.$eval(onloadExp);
}, false, true);
} else {
childScope = null;
element.html('');
}
});
}, {$inject:['$xhr.cache']});
}
});
/**
* @workInProgress
* @ngdoc widget
* @name angular.widget.ng:switch
*
* @description
* Conditionally change the DOM structure.
*
* @usageContent
* <any ng:switch-when="matchValue1">...</any>
* <any ng:switch-when="matchValue2">...</any>
* ...
* <any ng:switch-default>...</any>
*
* @param {*} on expression to match against <tt>ng:switch-when</tt>.
* @paramDescription
* On child elments add:
*
* * `ng:switch-when`: the case statement to match against. If match then this
* case will be displayed.
* * `ng:switch-default`: the default case when no other casses match.
*
* @example
<doc:example>
<doc:source>
<select name="switch">
<option>settings</option>
<option>home</option>
<option>other</option>
</select>
<tt>switch={{switch}}</tt>
</hr>
<ng:switch on="switch" >
<div ng:switch-when="settings">Settings Div</div>
<span ng:switch-when="home">Home Span</span>
<span ng:switch-default>default</span>
</ng:switch>
</code>
</doc:source>
<doc:scenario>
it('should start in settings', function(){
expect(element('.doc-example-live ng\\:switch').text()).toEqual('Settings Div');
});
it('should change to home', function(){
select('switch').option('home');
expect(element('.doc-example-live ng\\:switch').text()).toEqual('Home Span');
});
it('should select deafault', function(){
select('switch').option('other');
expect(element('.doc-example-live ng\\:switch').text()).toEqual('default');
});
</doc:scenario>
</doc:example>
*/
angularWidget('ng:switch', function (element) {
var compiler = this,
watchExpr = element.attr("on"),
changeExpr = element.attr('change'),
casesTemplate = {},
defaultCaseTemplate,
children = element.children(),
length = children.length,
child,
when;
if (!watchExpr) throw new Error("Missing 'on' attribute.");
while(length--) {
child = jqLite(children[length]);
// this needs to be here for IE
child.remove();
when = child.attr('ng:switch-when');
if (isString(when)) {
casesTemplate[when] = compiler.compile(child);
} else if (isString(child.attr('ng:switch-default'))) {
defaultCaseTemplate = compiler.compile(child);
}
}
children = null; // release memory;
element.html('');
return function(element){
var changeCounter = 0;
var childScope;
var selectedTemplate;
this.$watch(watchExpr, function(scope, value) {
element.html('');
if ((selectedTemplate = casesTemplate[value] || defaultCaseTemplate)) {
changeCounter++;
if (childScope) childScope.$destroy();
childScope = scope.$new();
childScope.$eval(changeExpr);
}
});
this.$watch(function(){return changeCounter;}, function() {
element.html('');
if (selectedTemplate) {
selectedTemplate(childScope, function(caseElement) {
element.append(caseElement);
});
}
});
};
});
/*
* Modifies the default behavior of html A tag, so that the default action is prevented when href
* attribute is empty.
*
* The reasoning for this change is to allow easy creation of action links with ng:click without
* changing the location or causing page reloads, e.g.:
* <a href="" ng:click="model.$save()">Save</a>
*/
angularWidget('a', function() {
this.descend(true);
this.directives(true);
return function(element) {
var hasNgHref = ((element.attr('ng:bind-attr') || '').indexOf('"href":') !== -1);
// turn <a href ng:click="..">link</a> into a link in IE
// but only if it doesn't have name attribute, in which case it's an anchor
if (!hasNgHref && !element.attr('name') && !element.attr('href')) {
element.attr('href', '');
}
if (element.attr('href') === '' && !hasNgHref) {
element.bind('click', function(event){
event.preventDefault();
});
}
};
});
/**
* @workInProgress
* @ngdoc widget
* @name angular.widget.@ng:repeat
*
* @description
* The `ng:repeat` widget instantiates a template once per item from a collection. The collection is
* enumerated with the `ng:repeat-index` attribute, starting from 0. Each template instance gets
* its own scope, where the given loop variable is set to the current collection item, and `$index`
* is set to the item index or key.
*
* Special properties are exposed on the local scope of each template instance, including:
*
* * `$index` – `{number}` – iterator offset of the repeated element (0..length-1)
* * `$position` – `{string}` – position of the repeated element in the iterator. One of:
* * `'first'`,
* * `'middle'`
* * `'last'`
*
* Note: Although `ng:repeat` looks like a directive, it is actually an attribute widget.
*
* @element ANY
* @param {string} repeat_expression The expression indicating how to enumerate a collection. Two
* formats are currently supported:
*
* * `variable in expression` – where variable is the user defined loop variable and `expression`
* is a scope expression giving the collection to enumerate.
*
* For example: `track in cd.tracks`.
*
* * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
* and `expression` is the scope expression giving the collection to enumerate.
*
* For example: `(name, age) in {'adam':10, 'amalie':12}`.
*
* @example
* This example initializes the scope to a list of names and
* then uses `ng:repeat` to display every person:
<doc:example>
<doc:source>
<div ng:init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]">
I have {{friends.length}} friends. They are:
<ul>
<li ng:repeat="friend in friends">
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
</li>
</ul>
</div>
</doc:source>
<doc:scenario>
it('should check ng:repeat', function(){
var r = using('.doc-example-live').repeater('ul li');
expect(r.count()).toBe(2);
expect(r.row(0)).toEqual(["1","John","25"]);
expect(r.row(1)).toEqual(["2","Mary","28"]);
});
</doc:scenario>
</doc:example>
*/
angularWidget('@ng:repeat', function(expression, element){
element.removeAttr('ng:repeat');
element.replaceWith(jqLite('<!-- ng:repeat: ' + expression + ' -->'));
var linker = this.compile(element);
return function(iterStartElement){
var match = expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/),
lhs, rhs, valueIdent, keyIdent;
if (! match) {
throw Error("Expected ng:repeat in form of '_item_ in _collection_' but got '" +
expression + "'.");
}
lhs = match[1];
rhs = match[2];
match = lhs.match(/^([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\)$/);
if (!match) {
throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" +
keyValue + "'.");
}
valueIdent = match[3] || match[1];
keyIdent = match[2];
var childScopes = [];
var childElements = [iterStartElement];
var parentScope = this;
this.$watch(function(scope){
var index = 0,
childCount = childScopes.length,
collection = scope.$eval(rhs),
collectionLength = size(collection, true),
fragment = document.createDocumentFragment(),
addFragmentTo = (childCount < collectionLength) ? childElements[childCount] : null,
childScope,
key;
for (key in collection) {
if (collection.hasOwnProperty(key)) {
if (index < childCount) {
// reuse existing child
childScope = childScopes[index];
childScope[valueIdent] = collection[key];
if (keyIdent) childScope[keyIdent] = key;
childScope.$position = index == 0
? 'first'
: (index == collectionLength - 1 ? 'last' : 'middle');
childScope.$eval();
} else {
// grow children
childScope = parentScope.$new();
childScope[valueIdent] = collection[key];
if (keyIdent) childScope[keyIdent] = key;
childScope.$index = index;
childScope.$position = index == 0
? 'first'
: (index == collectionLength - 1 ? 'last' : 'middle');
childScopes.push(childScope);
linker(childScope, function(clone){
clone.attr('ng:repeat-index', index);
fragment.appendChild(clone[0]);
// TODO(misko): Temporary hack - maybe think about it - removed after we add fragment after $digest()
// This causes double $digest for children
// The first flush will couse a lot of DOM access (initial)
// Second flush shuld be noop since nothing has change hence no DOM access.
childScope.$digest();
childElements[index + 1] = clone;
});
}
index ++;
}
}
//attach new nodes buffered in doc fragment
if (addFragmentTo) {
// TODO(misko): For performance reasons, we should do the addition after all other widgets
// have run. For this should happend after $digest() is done!
addFragmentTo.after(jqLite(fragment));
}
// shrink children
while(childScopes.length > index) {
// can not use $destroy(true) since there may be multiple iterators on same parent.
childScopes.pop().$destroy();
childElements.pop().remove();
}
});
};
});
/**
* @workInProgress
* @ngdoc widget
* @name angular.widget.@ng:non-bindable
*
* @description
* Sometimes it is necessary to write code which looks like bindings but which should be left alone
* by angular. Use `ng:non-bindable` to make angular ignore a chunk of HTML.
*
* Note: `ng:non-bindable` looks like a directive, but is actually an attribute widget.
*
* @element ANY
*
* @example
* In this example there are two location where a simple binding (`{{}}`) is present, but the one
* wrapped in `ng:non-bindable` is left alone.
*
* @example
<doc:example>
<doc:source>
<div>Normal: {{1 + 2}}</div>
<div ng:non-bindable>Ignored: {{1 + 2}}</div>
</doc:source>
<doc:scenario>
it('should check ng:non-bindable', function(){
expect(using('.doc-example-live').binding('1 + 2')).toBe('3');
expect(using('.doc-example-live').element('div:last').text()).
toMatch(/1 \+ 2/);
});
</doc:scenario>
</doc:example>
*/
angularWidget("@ng:non-bindable", noop);
/**
* @ngdoc widget
* @name angular.widget.ng:view
*
* @description
* # Overview
* `ng:view` is a widget that complements the {@link angular.service.$route $route} service by
* including the rendered template of the current route into the main layout (`index.html`) file.
* Every time the current route changes, the included view changes with it according to the
* configuration of the `$route` service.
*
* This widget provides functionality similar to {@link angular.widget.ng:include ng:include} when
* used like this:
*
* <ng:include src="$route.current.template" scope="$route.current.scope"></ng:include>
*
*
* # Advantages
* Compared to `ng:include`, `ng:view` offers these advantages:
*
* - shorter syntax
* - more efficient execution
* - doesn't require `$route` service to be available on the root scope
*
*
* @example
<doc:example>
<doc:source jsfiddle="false">
<script>
function MyCtrl($route) {
$route.when('/overview',
{ controller: OverviewCtrl,
template: 'partials/guide/dev_guide.overview.html'});
$route.when('/bootstrap',
{ controller: BootstrapCtrl,
template: 'partials/guide/dev_guide.bootstrap.auto_bootstrap.html'});
};
MyCtrl.$inject = ['$route'];
function BootstrapCtrl(){}
function OverviewCtrl(){}
</script>
<div ng:controller="MyCtrl">
<a href="overview">overview</a> |
<a href="bootstrap">bootstrap</a> |
<a href="undefined">undefined</a>
<br/>
The view is included below:
<hr/>
<ng:view></ng:view>
</div>
</doc:source>
<doc:scenario>
it('should load templates', function(){
element('.doc-example-live a:contains(overview)').click();
expect(element('.doc-example-live ng\\:view').text()).toMatch(/Developer Guide: Overview/);
element('.doc-example-live a:contains(bootstrap)').click();
expect(element('.doc-example-live ng\\:view').text()).toMatch(/Developer Guide: Initializing Angular: Automatic Initiialization/);
});
</doc:scenario>
</doc:example>
*/
angularWidget('ng:view', function(element) {
var compiler = this;
if (!element[0]['ng:compiled']) {
element[0]['ng:compiled'] = true;
return annotate('$xhr.cache', '$route', function($xhr, $route, element){
var template;
var changeCounter = 0;
this.$on('$afterRouteChange', function(){
changeCounter++;
});
this.$watch(function(){return changeCounter;}, function() {
var template = $route.current && $route.current.template;
if (template) {
//xhr's callback must be async, see commit history for more info
$xhr('GET', template, function(code, response) {
element.html(response);
compiler.compile(element)($route.current.scope);
});
} else {
element.html('');
}
});
});
} else {
compiler.descend(true);
compiler.directives(true);
}
});
/**
* @ngdoc widget
* @name angular.widget.ng:pluralize
*
* @description
* # Overview
* ng:pluralize is a widget that displays messages according to en-US localization rules.
* These rules are bundled with angular.js and the rules can be overridden
* (see {@link guide/dev_guide.i18n Angular i18n} dev guide). You configure ng:pluralize by
* specifying the mappings between
* {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
* plural categories} and the strings to be displayed.
*
* # Plural categories and explicit number rules
* There are two
* {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
* plural categories} in Angular's default en-US locale: "one" and "other".
*
* While a pural category may match many numbers (for example, in en-US locale, "other" can match
* any number that is not 1), an explicit number rule can only match one number. For example, the
* explicit number rule for "3" matches the number 3. You will see the use of plural categories
* and explicit number rules throughout later parts of this documentation.
*
* # Configuring ng:pluralize
* You configure ng:pluralize by providing 2 attributes: `count` and `when`.
* You can also provide an optional attribute, `offset`.
*
* The value of the `count` attribute can be either a string or an {@link guide/dev_guide.expressions
* Angular expression}; these are evaluated on the current scope for its binded value.
*
* The `when` attribute specifies the mappings between plural categories and the actual
* string to be displayed. The value of the attribute should be a JSON object so that Angular
* can interpret it correctly.
*
* The following example shows how to configure ng:pluralize:
*
* <pre>
* <ng:pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
* 'one': '1 person is viewing.',
* 'other': '{} people are viewing.'}">
* </ng:pluralize>
*</pre>
*
* In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
* specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
* would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
* other numbers, for example 12, so that instead of showing "12 people are viewing", you can
* show "a dozen people are viewing".
*
* You can use a set of closed braces(`{}`) as a placeholder for the number that you want substituted
* into pluralized strings. In the previous example, Angular will replace `{}` with
* <span ng:non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
* for <span ng:non-bindable>{{numberExpression}}</span>.
*
* # Configuring ng:pluralize with offset
* The `offset` attribute allows further customization of pluralized text, which can result in
* a better user experience. For example, instead of the message "4 people are viewing this document",
* you might display "John, Kate and 2 others are viewing this document".
* The offset attribute allows you to offset a number by any desired value.
* Let's take a look at an example:
*
* <pre>
* <ng:pluralize count="personCount" offset=2
* when="{'0': 'Nobody is viewing.',
* '1': '{{person1}} is viewing.',
* '2': '{{person1}} and {{person2}} are viewing.',
* 'one': '{{person1}}, {{person2}} and one other person are viewing.',
* 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
* </ng:pluralize>
* </pre>
*
* Notice that we are still using two plural categories(one, other), but we added
* three explicit number rules 0, 1 and 2.
* When one person, perhaps John, views the document, "John is viewing" will be shown.
* When three people view the document, no explicit number rule is found, so
* an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
* In this case, plural category 'one' is matched and "John, Marry and one other person are viewing"
* is shown.
*
* Note that when you specify offsets, you must provide explicit number rules for
* numbers from 0 up to and including the offset. If you use an offset of 3, for example,
* you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
* plural categories "one" and "other".
*
* @param {string|expression} count The variable to be bounded to.
* @param {string} when The mapping between plural category to its correspoding strings.
* @param {number=} offset Offset to deduct from the total number.
*
* @example
<doc:example>
<doc:source>
Person 1:<input type="text" name="person1" value="Igor" /><br/>
Person 2:<input type="text" name="person2" value="Misko" /><br/>
Number of People:<input type="text" name="personCount" value="1" /><br/>
<!--- Example with simple pluralization rules for en locale --->
Without Offset:
<ng:pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
'one': '1 person is viewing.',
'other': '{} people are viewing.'}">
</ng:pluralize><br>
<!--- Example with offset --->
With Offset(2):
<ng:pluralize count="personCount" offset=2
when="{'0': 'Nobody is viewing.',
'1': '{{person1}} is viewing.',
'2': '{{person1}} and {{person2}} are viewing.',
'one': '{{person1}}, {{person2}} and one other person are viewing.',
'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
</ng:pluralize>
</doc:source>
<doc:scenario>
it('should show correct pluralized string', function(){
expect(element('.doc-example-live .ng-pluralize:first').text()).
toBe('1 person is viewing.');
expect(element('.doc-example-live .ng-pluralize:last').text()).
toBe('Igor is viewing.');
using('.doc-example-live').input('personCount').enter('0');
expect(element('.doc-example-live .ng-pluralize:first').text()).
toBe('Nobody is viewing.');
expect(element('.doc-example-live .ng-pluralize:last').text()).
toBe('Nobody is viewing.');
using('.doc-example-live').input('personCount').enter('2');
expect(element('.doc-example-live .ng-pluralize:first').text()).
toBe('2 people are viewing.');
expect(element('.doc-example-live .ng-pluralize:last').text()).
toBe('Igor and Misko are viewing.');
using('.doc-example-live').input('personCount').enter('3');
expect(element('.doc-example-live .ng-pluralize:first').text()).
toBe('3 people are viewing.');
expect(element('.doc-example-live .ng-pluralize:last').text()).
toBe('Igor, Misko and one other person are viewing.');
using('.doc-example-live').input('personCount').enter('4');
expect(element('.doc-example-live .ng-pluralize:first').text()).
toBe('4 people are viewing.');
expect(element('.doc-example-live .ng-pluralize:last').text()).
toBe('Igor, Misko and 2 other people are viewing.');
});
it('should show data-binded names', function(){
using('.doc-example-live').input('personCount').enter('4');
expect(element('.doc-example-live .ng-pluralize:last').text()).
toBe('Igor, Misko and 2 other people are viewing.');
using('.doc-example-live').input('person1').enter('Di');
using('.doc-example-live').input('person2').enter('Vojta');
expect(element('.doc-example-live .ng-pluralize:last').text()).
toBe('Di, Vojta and 2 other people are viewing.');
});
</doc:scenario>
</doc:example>
*/
angularWidget('ng:pluralize', function(element) {
var numberExp = element.attr('count'),
whenExp = element.attr('when'),
offset = element.attr('offset') || 0;
return annotate('$locale', function($locale, element) {
var scope = this,
whens = scope.$eval(whenExp),
whensExpFns = {};
forEach(whens, function(expression, key) {
whensExpFns[key] = compileBindTemplate(expression.replace(/{}/g,
'{{' + numberExp + '-' + offset + '}}'));
});
scope.$watch(function() {
var value = parseFloat(scope.$eval(numberExp));
if (!isNaN(value)) {
//if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise,
//check it against pluralization rules in $locale service
if (!whens[value]) value = $locale.pluralCat(value - offset);
return whensExpFns[value](scope, element, true);
} else {
return '';
}
}, function(scope, newVal) {
element.text(newVal);
});
});
});
var browserSingleton;
angularService('$browser', function($log, $sniffer) {
if (!browserSingleton) {
browserSingleton = new Browser(window, jqLite(window.document), jqLite(window.document.body),
XHR, $log, $sniffer);
browserSingleton.bind();
}
return browserSingleton;
}, {$inject: ['$log', '$sniffer']});
extend(angular, {
// disabled for now until we agree on public name
//'annotate': annotate,
'compile': compile,
'scope': createScope,
'copy': copy,
'extend': extend,
'equals': equals,
'forEach': forEach,
'injector': createInjector,
'noop':noop,
'bind':bind,
'toJson': toJson,
'fromJson': fromJson,
'identity':identity,
'isUndefined': isUndefined,
'isDefined': isDefined,
'isString': isString,
'isFunction': isFunction,
'isObject': isObject,
'isNumber': isNumber,
'isArray': isArray,
'version': version,
'isDate': isDate,
'lowercase': lowercase,
'uppercase': uppercase
});
//try to bind to jquery now so that one can write angular.element().read()
//but we will rebind on bootstrap again.
bindJQuery();
jqLiteWrap(document).ready(function(){
angularInit(angularJsConfig(document), document);
});
})(window, document);
angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";[ng\\:cloak],.ng-cloak{display:none;}.ng-format-negative{color:red;}.ng-exception{border:2px solid #FF0000;font-family:"Courier New",Courier,monospace;font-size:smaller;white-space:pre;}.ng-validation-error{border:2px solid #FF0000;}#ng-callout{margin:0;padding:0;border:0;outline:0;font-size:13px;font-weight:normal;font-family:Verdana,Arial,Helvetica,sans-serif;vertical-align:baseline;background:transparent;text-decoration:none;}#ng-callout .ng-arrow-left{background-image:url("data:image/gif;base64,R0lGODlhCwAXAKIAAMzMzO/v7/f39////////wAAAAAAAAAAACH5BAUUAAQALAAAAAALABcAAAMrSLoc/AG8FeUUIN+sGebWAnbKSJodqqlsOxJtqYooU9vvk+vcJIcTkg+QAAA7");background-repeat:no-repeat;background-position:left top;position:absolute;z-index:101;left:-12px;height:23px;width:10px;top:-3px;}#ng-callout .ng-arrow-right{background-image:url("data:image/gif;base64,R0lGODlhCwAXAKIAAMzMzO/v7/f39////////wAAAAAAAAAAACH5BAUUAAQALAAAAAALABcAAAMrCLTcoM29yN6k9socs91e5X3EyJloipYrO4ohTMqA0Fn2XVNswJe+H+SXAAA7");background-repeat:no-repeat;background-position:left top;position:absolute;z-index:101;height:23px;width:11px;top:-2px;}#ng-callout{position:absolute;z-index:100;border:2px solid #CCCCCC;background-color:#fff;}#ng-callout .ng-content{padding:10px 10px 10px 10px;color:#333333;}#ng-callout .ng-title{background-color:#CCCCCC;text-align:left;padding-left:8px;padding-bottom:5px;padding-top:2px;font-weight:bold;}.ng-input-indicator-wait{background-image:url("data:image/png;base64,R0lGODlhEAAQAPQAAP///wAAAPDw8IqKiuDg4EZGRnp6egAAAFhYWCQkJKysrL6+vhQUFJycnAQEBDY2NmhoaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAAFdyAgAgIJIeWoAkRCCMdBkKtIHIngyMKsErPBYbADpkSCwhDmQCBethRB6Vj4kFCkQPG4IlWDgrNRIwnO4UKBXDufzQvDMaoSDBgFb886MiQadgNABAokfCwzBA8LCg0Egl8jAggGAA1kBIA1BAYzlyILczULC2UhACH5BAkKAAAALAAAAAAQABAAAAV2ICACAmlAZTmOREEIyUEQjLKKxPHADhEvqxlgcGgkGI1DYSVAIAWMx+lwSKkICJ0QsHi9RgKBwnVTiRQQgwF4I4UFDQQEwi6/3YSGWRRmjhEETAJfIgMFCnAKM0KDV4EEEAQLiF18TAYNXDaSe3x6mjidN1s3IQAh+QQJCgAAACwAAAAAEAAQAAAFeCAgAgLZDGU5jgRECEUiCI+yioSDwDJyLKsXoHFQxBSHAoAAFBhqtMJg8DgQBgfrEsJAEAg4YhZIEiwgKtHiMBgtpg3wbUZXGO7kOb1MUKRFMysCChAoggJCIg0GC2aNe4gqQldfL4l/Ag1AXySJgn5LcoE3QXI3IQAh+QQJCgAAACwAAAAAEAAQAAAFdiAgAgLZNGU5joQhCEjxIssqEo8bC9BRjy9Ag7GILQ4QEoE0gBAEBcOpcBA0DoxSK/e8LRIHn+i1cK0IyKdg0VAoljYIg+GgnRrwVS/8IAkICyosBIQpBAMoKy9dImxPhS+GKkFrkX+TigtLlIyKXUF+NjagNiEAIfkECQoAAAAsAAAAABAAEAAABWwgIAICaRhlOY4EIgjH8R7LKhKHGwsMvb4AAy3WODBIBBKCsYA9TjuhDNDKEVSERezQEL0WrhXucRUQGuik7bFlngzqVW9LMl9XWvLdjFaJtDFqZ1cEZUB0dUgvL3dgP4WJZn4jkomWNpSTIyEAIfkECQoAAAAsAAAAABAAEAAABX4gIAICuSxlOY6CIgiD8RrEKgqGOwxwUrMlAoSwIzAGpJpgoSDAGifDY5kopBYDlEpAQBwevxfBtRIUGi8xwWkDNBCIwmC9Vq0aiQQDQuK+VgQPDXV9hCJjBwcFYU5pLwwHXQcMKSmNLQcIAExlbH8JBwttaX0ABAcNbWVbKyEAIfkECQoAAAAsAAAAABAAEAAABXkgIAICSRBlOY7CIghN8zbEKsKoIjdFzZaEgUBHKChMJtRwcWpAWoWnifm6ESAMhO8lQK0EEAV3rFopIBCEcGwDKAqPh4HUrY4ICHH1dSoTFgcHUiZjBhAJB2AHDykpKAwHAwdzf19KkASIPl9cDgcnDkdtNwiMJCshACH5BAkKAAAALAAAAAAQABAAAAV3ICACAkkQZTmOAiosiyAoxCq+KPxCNVsSMRgBsiClWrLTSWFoIQZHl6pleBh6suxKMIhlvzbAwkBWfFWrBQTxNLq2RG2yhSUkDs2b63AYDAoJXAcFRwADeAkJDX0AQCsEfAQMDAIPBz0rCgcxky0JRWE1AmwpKyEAIfkECQoAAAAsAAAAABAAEAAABXkgIAICKZzkqJ4nQZxLqZKv4NqNLKK2/Q4Ek4lFXChsg5ypJjs1II3gEDUSRInEGYAw6B6zM4JhrDAtEosVkLUtHA7RHaHAGJQEjsODcEg0FBAFVgkQJQ1pAwcDDw8KcFtSInwJAowCCA6RIwqZAgkPNgVpWndjdyohACH5BAkKAAAALAAAAAAQABAAAAV5ICACAimc5KieLEuUKvm2xAKLqDCfC2GaO9eL0LABWTiBYmA06W6kHgvCqEJiAIJiu3gcvgUsscHUERm+kaCxyxa+zRPk0SgJEgfIvbAdIAQLCAYlCj4DBw0IBQsMCjIqBAcPAooCBg9pKgsJLwUFOhCZKyQDA3YqIQAh+QQJCgAAACwAAAAAEAAQAAAFdSAgAgIpnOSonmxbqiThCrJKEHFbo8JxDDOZYFFb+A41E4H4OhkOipXwBElYITDAckFEOBgMQ3arkMkUBdxIUGZpEb7kaQBRlASPg0FQQHAbEEMGDSVEAA1QBhAED1E0NgwFAooCDWljaQIQCE5qMHcNhCkjIQAh+QQJCgAAACwAAAAAEAAQAAAFeSAgAgIpnOSoLgxxvqgKLEcCC65KEAByKK8cSpA4DAiHQ/DkKhGKh4ZCtCyZGo6F6iYYPAqFgYy02xkSaLEMV34tELyRYNEsCQyHlvWkGCzsPgMCEAY7Cg04Uk48LAsDhRA8MVQPEF0GAgqYYwSRlycNcWskCkApIyEAOwAAAAAAAAAAAA==");background-position:right;background-repeat:no-repeat;}</style>');
|
test/PaginationSpec.js
|
glenjamin/react-bootstrap
|
import React from 'react';
import { mount } from 'enzyme';
import Pagination from '../src/Pagination';
describe('<Pagination>', () => {
it('should have class', () => {
mount(<Pagination>Item content</Pagination>).assertSingle('.pagination');
});
});
|
src/components/ListItemComponent.js
|
Zcyon/lait
|
'use strict';
import React from 'react';
require('styles//ListItem.css');
let ListItemComponent = (props) => (
<li className="listitem-component menu-item" onClick={() => {props.setSelectedTaskList(props.id);}}>
<a className="is-medium">
{props.listName}
{
props.isActive ? <span className="is-pulled-right" onClick={() => {props.toggleTaskList(props.id)}}>Delete</span> :
<span className="is-pulled-right" onClick={() => {props.toggleTaskList(props.id);}}>Recover</span>
}
</a>
</li>
);
ListItemComponent.displayName = 'ListItemComponent';
// Uncomment properties you need
// ListItemComponent.propTypes = {};
// ListItemComponent.defaultProps = {};
export default ListItemComponent;
|
src/index.js
|
FilmonFeMe/coloreyes
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import Logo from './components/Logo.js';
import Navbar from './components/Navbar.js';
import Header from './components/Header.js';
import Home from './components/Home.js';
import Instruction from './components/Instruction.js';
import AboutUs from './components/AboutUs.js';
import ContactForm from './components/ContactForm.js';
import ColorBlindnessView from './components/ColorBlindnessView.js';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import HueTest from './components/HueTest.js'
ReactDOM.render(
<Router>
<div>
<Navbar></Navbar>
<Header></Header>
<Route exact path="/" component={Home}/>
{/*<Route exact path="/" component={OtherComponent}/>*/}
<Route path="/instructions" component={Instruction}/>
<Route path="/quiz" component={App}/>
<Route path="/about-us" component={AboutUs}/>
<Route path="/contact-us" component={ContactForm}/>
<Route path="/color-view" component={ColorBlindnessView}/>
<Route path="/hue-test" component={HueTest}/>
</div>
</Router>,
root);
registerServiceWorker();
|
src/components/views/UnsupportedBrowser.js
|
dkadrios/zendrum-stompblock-client
|
import React from 'react'
import styles from '../../styles/unsupportedBrowser'
import ChromeIcon from '../../images/Chrome.svg.js'
import OperaIcon from '../../images/Opera.svg.js'
const UnsupportedBrowser = () => (
<div className={styles.outer}>
<div className={styles.main}>
<header>
<a href="https://zendrumstudio.com">zendrumstudio.com</a>
<a href="https://zendrumstudio.com/contact-us/">Contact Us</a>
</header>
<h1>Unsupported browser</h1>
{/* {navigator.userAgent} */}
<p>
This application makes use of bleeding edge web technologies in order to communicate with
your Stompblock over MIDI and USB.
</p>
<p>At this time, only these browsers support this emerging web technology.</p>
<footer>
<section>
<a href="https://www.google.com/chrome/browser/">
<ChromeIcon width="50%" />
</a>
<a href="https://www.google.com/chrome/browser/">Google Chrome</a>
<aside>Version 43+</aside>
</section>
<section>
<a href="https://www.opera.com/download">
<OperaIcon
width="50%"
viewBox="10 10 100 100"
/>
</a>
<a href="https://www.opera.com/download">Opera</a>
<aside>Version 33+</aside>
</section>
</footer>
</div>
</div>
)
export default UnsupportedBrowser
|
ajax/libs/rxjs/2.5.1/rx.all.js
|
khasinski/cdnjs
|
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = {
internals: {},
config: {
Promise: root.Promise
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; },
isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; },
identity = Rx.helpers.identity = function (x) { return x; },
pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },
just = Rx.helpers.just = function (value) { return function () { return value; }; },
defaultNow = Rx.helpers.defaultNow = Date.now,
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; },
isFunction = Rx.helpers.isFunction = (function () {
var isFn = function (value) {
return typeof value == 'function' || false;
}
// fallback for older versions of Chrome and Safari
if (isFn(/x/)) {
isFn = function(value) {
return typeof value == 'function' && toString.call(value) == '[object Function]';
};
}
return isFn;
}());
function cloneArray(arr) { for(var a = [], i = 0, len = arr.length; i < len; i++) { a.push(arr[i]); } return a;}
Rx.config.longStackSupport = false;
var hasStacks = false;
try {
throw new Error();
} catch (e) {
hasStacks = !!e.stack;
}
// All code after this point will be filtered from stack traces reported by RxJS
var rStartingLine = captureLine(), rFileName;
var STACK_JUMP_SEPARATOR = "From previous event:";
function makeStackTraceLong(error, observable) {
// If possible, transform the error stack trace by removing Node and RxJS
// cruft, then concatenating with the stack trace of `observable`.
if (hasStacks &&
observable.stack &&
typeof error === "object" &&
error !== null &&
error.stack &&
error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1
) {
var stacks = [];
for (var o = observable; !!o; o = o.source) {
if (o.stack) {
stacks.unshift(o.stack);
}
}
stacks.unshift(error.stack);
var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n");
error.stack = filterStackString(concatedStacks);
}
}
function filterStackString(stackString) {
var lines = stackString.split("\n"),
desiredLines = [];
for (var i = 0, len = lines.length; i < len; i++) {
var line = lines[i];
if (!isInternalFrame(line) && !isNodeFrame(line) && line) {
desiredLines.push(line);
}
}
return desiredLines.join("\n");
}
function isInternalFrame(stackLine) {
var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);
if (!fileNameAndLineNumber) {
return false;
}
var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1];
return fileName === rFileName &&
lineNumber >= rStartingLine &&
lineNumber <= rEndingLine;
}
function isNodeFrame(stackLine) {
return stackLine.indexOf("(module.js:") !== -1 ||
stackLine.indexOf("(node.js:") !== -1;
}
function captureLine() {
if (!hasStacks) { return; }
try {
throw new Error();
} catch (e) {
var lines = e.stack.split("\n");
var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2];
var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);
if (!fileNameAndLineNumber) { return; }
rFileName = fileNameAndLineNumber[0];
return fileNameAndLineNumber[1];
}
}
function getFileNameAndLineNumber(stackLine) {
// Named functions: "at functionName (filename:lineNumber:columnNumber)"
var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);
if (attempt1) { return [attempt1[1], Number(attempt1[2])]; }
// Anonymous functions: "at filename:lineNumber:columnNumber"
var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);
if (attempt2) { return [attempt2[1], Number(attempt2[2])]; }
// Firefox style: "function@filename:lineNumber or @filename:lineNumber"
var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine);
if (attempt3) { return [attempt3[1], Number(attempt3[2])]; }
}
var EmptyError = Rx.EmptyError = function() {
this.message = 'Sequence contains no elements.';
Error.call(this);
};
EmptyError.prototype = Error.prototype;
var ObjectDisposedError = Rx.ObjectDisposedError = function() {
this.message = 'Object has been disposed';
Error.call(this);
};
ObjectDisposedError.prototype = Error.prototype;
var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () {
this.message = 'Argument out of range';
Error.call(this);
};
ArgumentOutOfRangeError.prototype = Error.prototype;
var NotSupportedError = Rx.NotSupportedError = function (message) {
this.message = message || 'This operation is not supported';
Error.call(this);
};
NotSupportedError.prototype = Error.prototype;
var NotImplementedError = Rx.NotImplementedError = function (message) {
this.message = message || 'This operation is not implemented';
Error.call(this);
};
NotImplementedError.prototype = Error.prototype;
var notImplemented = Rx.helpers.notImplemented = function () {
throw new NotImplementedError();
};
var notSupported = Rx.helpers.notSupported = function () {
throw new NotSupportedError();
};
// Shim in iterator support
var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
'_es6shim_iterator_';
// Bug for mozilla version
if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined };
var isIterable = Rx.helpers.isIterable = function (o) {
return o[$iterator$] !== undefined;
}
var isArrayLike = Rx.helpers.isArrayLike = function (o) {
return o && o.length !== undefined;
}
Rx.helpers.iterator = $iterator$;
var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) {
if (typeof thisArg === 'undefined') { return func; }
switch(argCount) {
case 0:
return function() {
return func.call(thisArg)
};
case 1:
return function(arg) {
return func.call(thisArg, arg);
}
case 2:
return function(value, index) {
return func.call(thisArg, value, index);
};
case 3:
return function(value, index, collection) {
return func.call(thisArg, value, index, collection);
};
}
return function() {
return func.apply(thisArg, arguments);
};
};
/** Used to determine if values are of the language type Object */
var dontEnums = ['toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'],
dontEnumsLength = dontEnums.length;
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
supportNodeClass,
errorProto = Error.prototype,
objectProto = Object.prototype,
stringProto = String.prototype,
propertyIsEnumerable = objectProto.propertyIsEnumerable;
try {
supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch (e) {
supportNodeClass = true;
}
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
var support = {};
(function () {
var ctor = function() { this.x = 1; },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
// Detect if `name` or `message` properties of `Error.prototype` are enumerable by default.
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
// Detect if `prototype` properties are enumerable by default.
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
// Detect if `arguments` object indexes are non-enumerable
support.nonEnumArgs = key != 0;
// Detect if properties shadowing those on `Object.prototype` are non-enumerable.
support.nonEnumShadows = !/valueOf/.test(props);
}(1));
var isObject = Rx.internals.isObject = function(value) {
var type = typeof value;
return value && (type == 'function' || type == 'object') || false;
};
function keysIn(object) {
var result = [];
if (!isObject(object)) {
return result;
}
if (support.nonEnumArgs && object.length && isArguments(object)) {
object = slice.call(object);
}
var skipProto = support.enumPrototypes && typeof object == 'function',
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error);
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name'))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var ctor = object.constructor,
index = -1,
length = dontEnumsLength;
if (object === (ctor && ctor.prototype)) {
var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object),
nonEnum = nonEnumProps[className];
}
while (++index < length) {
key = dontEnums[index];
if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) {
result.push(key);
}
}
}
return result;
}
function internalFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
function internalForIn(object, callback) {
return internalFor(object, callback, keysIn);
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
var isArguments = function(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
var isEqual = Rx.internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a && (a == null || b == null ||
(type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) {
return false;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a) ?
b != +b :
// but treat `-0` vs. `+0` as not equal
(a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var initedStack = !stackA;
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
var result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
internalForIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB));
}
});
if (result) {
// ensure both objects have the same number of properties
internalForIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
}
stackA.pop();
stackB.pop();
return result;
}
var hasProp = {}.hasOwnProperty,
slice = Array.prototype.slice;
var inherits = this.inherits = Rx.internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
var addProperties = Rx.internals.addProperties = function (obj) {
for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
for (var idx = 0, ln = sources.length; idx < ln; idx++) {
var source = sources[idx];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
var errorObj = {e: {}};
var tryCatchTarget;
function tryCatcher() {
try {
return tryCatchTarget.apply(this, arguments);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatch(fn) {
if (!isFunction(fn)) { throw new TypeError('fn must be a function'); }
tryCatchTarget = fn;
return tryCatcher;
}
function thrower(e) {
throw e;
}
// Collections
function IndexedItem(id, value) {
this.id = id;
this.value = value;
}
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
c === 0 && (c = this.id - other.id);
return c;
};
// Priority Queue for Scheduling
var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) { return; }
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) { return; }
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
+index || (index = 0);
if (index >= this.length || index < 0) { return; }
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () { return this.items[0].value; };
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
this.items[this.length] = undefined;
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
var args = [], i, len;
if (Array.isArray(arguments[0])) {
args = arguments[0];
len = args.length;
} else {
len = arguments.length;
args = new Array(len);
for(i = 0; i < len; i++) { args[i] = arguments[i]; }
}
for(i = 0; i < len; i++) {
if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); }
}
this.disposables = args;
this.isDisposed = false;
this.length = args.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var len = this.disposables.length, currentDisposables = new Array(len);
for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; }
this.disposables = [];
this.length = 0;
for (i = 0; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Provides a set of static methods for creating Disposables.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
/**
* Validates whether the given object is a disposable
* @param {Object} Object to test whether it has a dispose method
* @returns {Boolean} true if a disposable object, else false.
*/
var isDisposable = Disposable.isDisposable = function (d) {
return d && isFunction(d.dispose);
};
var checkDisposed = Disposable.checkDisposed = function (disposable) {
if (disposable.isDisposed) { throw new ObjectDisposedError(); }
};
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () {
function BooleanDisposable () {
this.isDisposed = false;
this.current = null;
}
var booleanDisposablePrototype = BooleanDisposable.prototype;
/**
* Gets the underlying disposable.
* @return The underlying disposable.
*/
booleanDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
* @param {Disposable} value The new underlying disposable.
*/
booleanDisposablePrototype.setDisposable = function (value) {
var shouldDispose = this.isDisposed;
if (!shouldDispose) {
var old = this.current;
this.current = value;
}
old && old.dispose();
shouldDispose && value && value.dispose();
};
/**
* Disposes the underlying disposable as well as all future replacements.
*/
booleanDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var old = this.current;
this.current = null;
}
old && old.dispose();
};
return BooleanDisposable;
}());
var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable;
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed && !this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed && !this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
function ScheduledDisposable(scheduler, disposable) {
this.scheduler = scheduler;
this.disposable = disposable;
this.isDisposed = false;
}
function scheduleItem(s, self) {
if (!self.isDisposed) {
self.isDisposed = true;
self.disposable.dispose();
}
}
ScheduledDisposable.prototype.dispose = function () {
this.scheduler.scheduleWithState(this, scheduleItem);
};
var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
timeSpan < 0 && (timeSpan = 0);
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize;
(function (schedulerProto) {
function invokeRecImmediate(scheduler, pair) {
var state = pair[0], action = pair[1], group = new CompositeDisposable();
function recursiveAction(state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
}
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair[0], action = pair[1], group = new CompositeDisposable();
function recursiveAction(state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method](state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function scheduleInnerRecursive(action, self) {
action(function(dt) { self(action, dt); });
}
/**
* Schedules an action to be executed recursively.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, function (_action, self) {
_action(function () { self(_action); }); });
};
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState([state, action], invokeRecImmediate);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative([state, action], dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute([state, action], dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, action);
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) {
if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); }
period = normalizeTime(period);
var s = state, id = root.setInterval(function () { s = action(s); }, period);
return disposableCreate(function () { root.clearInterval(id); });
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions.
* @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false.
* @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling.
*/
schedulerProto.catchError = schedulerProto['catch'] = function (handler) {
return new CatchScheduler(this, handler);
};
}(Scheduler.prototype));
var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
/** Gets a scheduler that schedules work immediately on the current thread. */
var immediateScheduler = Scheduler.immediate = (function () {
function scheduleNow(state, action) { return action(this, state); }
return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
function runTrampoline () {
while (queue.length > 0) {
var item = queue.dequeue();
!item.isCancelled() && item.invoke();
}
}
function scheduleNow(state, action) {
var si = new ScheduledItem(this, state, action, this.now());
if (!queue) {
queue = new PriorityQueue(4);
queue.enqueue(si);
var result = tryCatch(runTrampoline)();
queue = null;
if (result === errorObj) { return thrower(result.e); }
} else {
queue.enqueue(si);
}
return si.disposable;
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported);
currentScheduler.scheduleRequired = function () { return !queue; };
return currentScheduler;
}());
var scheduleMethod, clearMethod;
var localTimer = (function () {
var localSetTimeout, localClearTimeout = noop;
if (!!root.WScript) {
localSetTimeout = function (fn, time) {
root.WScript.Sleep(time);
fn();
};
} else if (!!root.setTimeout) {
localSetTimeout = root.setTimeout;
localClearTimeout = root.clearTimeout;
} else {
throw new NotSupportedError();
}
return {
setTimeout: localSetTimeout,
clearTimeout: localClearTimeout
};
}());
var localSetTimeout = localTimer.setTimeout,
localClearTimeout = localTimer.clearTimeout;
(function () {
var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false;
clearMethod = function (handle) {
delete tasksByHandle[handle];
};
function runTask(handle) {
if (currentlyRunning) {
localSetTimeout(function () { runTask(handle) }, 0);
} else {
var task = tasksByHandle[handle];
if (task) {
currentlyRunning = true;
var result = tryCatch(task)();
clearMethod(handle);
currentlyRunning = false;
if (result === errorObj) { return thrower(result.e); }
}
}
}
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false, oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('', '*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout
if (isFunction(setImmediate)) {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
setImmediate(function () { runTask(id); });
return id;
};
} else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
process.nextTick(function () { runTask(id); });
return id;
};
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random();
function onGlobalPostMessage(event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
runTask(event.data.substring(MSG_PREFIX.length));
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else {
root.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
return id;
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel();
channel.port1.onmessage = function (e) { runTask(e.data); };
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
channel.port2.postMessage(id);
return id;
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
var id = nextHandle++;
tasksByHandle[id] = action;
scriptElement.onreadystatechange = function () {
runTask(id);
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
return id;
};
} else {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
localSetTimeout(function () {
runTask(id);
}, 0);
return id;
};
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = Scheduler.default = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this, dt = Scheduler.normalize(dueTime);
if (dt === 0) { return scheduler.scheduleWithState(state, action); }
var disposable = new SingleAssignmentDisposable();
var id = localSetTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
localClearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
var CatchScheduler = (function (__super__) {
function scheduleNow(state, action) {
return this._scheduler.scheduleWithState(state, this._wrap(action));
}
function scheduleRelative(state, dueTime, action) {
return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action));
}
function scheduleAbsolute(state, dueTime, action) {
return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action));
}
inherits(CatchScheduler, __super__);
function CatchScheduler(scheduler, handler) {
this._scheduler = scheduler;
this._handler = handler;
this._recursiveOriginal = null;
this._recursiveWrapper = null;
__super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute);
}
CatchScheduler.prototype._clone = function (scheduler) {
return new CatchScheduler(scheduler, this._handler);
};
CatchScheduler.prototype._wrap = function (action) {
var parent = this;
return function (self, state) {
try {
return action(parent._getRecursiveWrapper(self), state);
} catch (e) {
if (!parent._handler(e)) { throw e; }
return disposableEmpty;
}
};
};
CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {
if (this._recursiveOriginal !== scheduler) {
this._recursiveOriginal = scheduler;
var wrapper = this._clone(scheduler);
wrapper._recursiveOriginal = scheduler;
wrapper._recursiveWrapper = wrapper;
this._recursiveWrapper = wrapper;
}
return this._recursiveWrapper;
};
CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) {
var self = this, failed = false, d = new SingleAssignmentDisposable();
d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) {
if (failed) { return null; }
try {
return action(state1);
} catch (e) {
failed = true;
if (!self._handler(e)) { throw e; }
d.dispose();
return null;
}
}));
return d;
};
return CatchScheduler;
}(Scheduler));
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, value, exception, accept, acceptObservable, toString) {
this.kind = kind;
this.value = value;
this.exception = exception;
this._accept = accept;
this._acceptObservable = acceptObservable;
this.toString = toString;
}
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
return observerOrOnNext && typeof observerOrOnNext === 'object' ?
this._acceptObservable(observerOrOnNext) :
this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notifications
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
Notification.prototype.toObservable = function (scheduler) {
var self = this;
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithState(self, function (_, notification) {
notification._acceptObservable(observer);
notification.kind === 'N' && observer.onCompleted();
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept(onNext) { return onNext(this.value); }
function _acceptObservable(observer) { return observer.onNext(this.value); }
function toString() { return 'OnNext(' + this.value + ')'; }
return function (value) {
return new Notification('N', value, null, _accept, _acceptObservable, toString);
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) { return onError(this.exception); }
function _acceptObservable(observer) { return observer.onError(this.exception); }
function toString () { return 'OnError(' + this.exception + ')'; }
return function (e) {
return new Notification('E', null, e, _accept, _acceptObservable, toString);
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) { return onCompleted(); }
function _acceptObservable(observer) { return observer.onCompleted(); }
function toString () { return 'OnCompleted()'; }
return function () {
return new Notification('C', null, null, _accept, _acceptObservable, toString);
};
}());
var Enumerator = Rx.internals.Enumerator = function (next) {
this._next = next;
};
Enumerator.prototype.next = function () {
return this._next();
};
Enumerator.prototype[$iterator$] = function () { return this; }
var Enumerable = Rx.internals.Enumerable = function (iterator) {
this._iterator = iterator;
};
Enumerable.prototype[$iterator$] = function () {
return this._iterator();
};
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (o) {
var e = sources[$iterator$]();
var isDisposed, subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
try {
var currentItem = e.next();
} catch (ex) {
return o.onError(ex);
}
if (currentItem.done) {
return o.onCompleted();
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
function(err) { o.onError(err); },
self)
);
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchError = function () {
var sources = this;
return new AnonymousObservable(function (o) {
var e = sources[$iterator$]();
var isDisposed, subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) {
if (isDisposed) { return; }
try {
var currentItem = e.next();
} catch (ex) {
return observer.onError(ex);
}
if (currentItem.done) {
if (lastException !== null) {
o.onError(lastException);
} else {
o.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
self,
function() { o.onCompleted(); }));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchErrorWhen = function (notificationHandler) {
var sources = this;
return new AnonymousObservable(function (o) {
var exceptions = new Subject(),
notifier = new Subject(),
handled = notificationHandler(exceptions),
notificationDisposable = handled.subscribe(notifier);
var e = sources[$iterator$]();
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
try {
var currentItem = e.next();
} catch (ex) {
return o.onError(ex);
}
if (currentItem.done) {
if (lastException) {
o.onError(lastException);
} else {
o.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var outer = new SingleAssignmentDisposable();
var inner = new SingleAssignmentDisposable();
subscription.setDisposable(new CompositeDisposable(inner, outer));
outer.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
function (exn) {
inner.setDisposable(notifier.subscribe(self, function(ex) {
o.onError(ex);
}, function() {
o.onCompleted();
}));
exceptions.onNext(exn);
},
function() { o.onCompleted(); }));
});
return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
if (repeatCount == null) { repeatCount = -1; }
return new Enumerable(function () {
var left = repeatCount;
return new Enumerator(function () {
if (left === 0) { return doneEnumerator; }
if (left > 0) { left--; }
return { done: false, value: value };
});
});
};
var enumerableOf = Enumerable.of = function (source, selector, thisArg) {
if (selector) {
var selectorFn = bindCallback(selector, thisArg, 3);
}
return new Enumerable(function () {
var index = -1;
return new Enumerator(
function () {
return ++index < source.length ?
{ done: false, value: !selector ? source[index] : selectorFn(source[index], index, source) } :
doneEnumerator;
});
});
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) { return n.accept(observer); };
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
};
/**
* Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
* If a violation is detected, an Error is thrown from the offending observer method call.
* @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
*/
Observer.prototype.checked = function () { return new CheckedObserver(this); };
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Creates an observer from a notification callback.
*
* @static
* @memberOf Observer
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler, thisArg) {
return new AnonymousObserver(function (x) {
return handler.call(thisArg, notificationCreateOnNext(x));
}, function (e) {
return handler.call(thisArg, notificationCreateOnError(e));
}, function () {
return handler.call(thisArg, notificationCreateOnCompleted());
});
};
/**
* Schedules the invocation of observer methods on the given scheduler.
* @param {Scheduler} scheduler Scheduler to schedule observer messages on.
* @returns {Observer} Observer whose messages are scheduled on the given scheduler.
*/
Observer.prototype.notifyOn = function (scheduler) {
return new ObserveOnObserver(scheduler, this);
};
Observer.prototype.makeSafe = function(disposable) {
return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable);
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) {
inherits(AbstractObserver, __super__);
/**
* Creates a new observer in a non-stopped state.
*/
function AbstractObserver() {
this.isStopped = false;
__super__.call(this);
}
// Must be implemented by other observers
AbstractObserver.prototype.next = notImplemented;
AbstractObserver.prototype.error = notImplemented;
AbstractObserver.prototype.completed = notImplemented;
/**
* Notifies the observer of a new element in the sequence.
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) { this.next(value); }
};
/**
* Notifies the observer that an exception has occurred.
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) {
inherits(AnonymousObserver, __super__);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
__super__.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (error) {
this._onError(error);
};
/**
* Calls the onCompleted action.
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var CheckedObserver = (function (__super__) {
inherits(CheckedObserver, __super__);
function CheckedObserver(observer) {
__super__.call(this);
this._observer = observer;
this._state = 0; // 0 - idle, 1 - busy, 2 - done
}
var CheckedObserverPrototype = CheckedObserver.prototype;
CheckedObserverPrototype.onNext = function (value) {
this.checkAccess();
var res = tryCatch(this._observer.onNext).call(this._observer, value);
this._state = 0;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.onError = function (err) {
this.checkAccess();
var res = tryCatch(this._observer.onError).call(this._observer, err);
this._state = 2;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.onCompleted = function () {
this.checkAccess();
var res = tryCatch(this._observer.onCompleted).call(this._observer);
this._state = 2;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.checkAccess = function () {
if (this._state === 1) { throw new Error('Re-entrancy detected'); }
if (this._state === 2) { throw new Error('Observer completed'); }
if (this._state === 0) { this._state = 1; }
};
return CheckedObserver;
}(Observer));
var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) {
inherits(ScheduledObserver, __super__);
function ScheduledObserver(scheduler, observer) {
__super__.call(this);
this.scheduler = scheduler;
this.observer = observer;
this.isAcquired = false;
this.hasFaulted = false;
this.queue = [];
this.disposable = new SerialDisposable();
}
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () { self.observer.onNext(value); });
};
ScheduledObserver.prototype.error = function (e) {
var self = this;
this.queue.push(function () { self.observer.onError(e); });
};
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () { self.observer.onCompleted(); });
};
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false, parent = this;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
try {
work();
} catch (ex) {
parent.queue = [];
parent.hasFaulted = true;
throw ex;
}
self();
}));
}
};
ScheduledObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
var ObserveOnObserver = (function (__super__) {
inherits(ObserveOnObserver, __super__);
function ObserveOnObserver(scheduler, observer, cancel) {
__super__.call(this, scheduler, observer);
this._cancel = cancel;
}
ObserveOnObserver.prototype.next = function (value) {
__super__.prototype.next.call(this, value);
this.ensureActive();
};
ObserveOnObserver.prototype.error = function (e) {
__super__.prototype.error.call(this, e);
this.ensureActive();
};
ObserveOnObserver.prototype.completed = function () {
__super__.prototype.completed.call(this);
this.ensureActive();
};
ObserveOnObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this._cancel && this._cancel.dispose();
this._cancel = null;
};
return ObserveOnObserver;
})(ScheduledObserver);
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
function Observable(subscribe) {
if (Rx.config.longStackSupport && hasStacks) {
try {
throw new Error();
} catch (e) {
this.stack = e.stack.substring(e.stack.indexOf("\n") + 1);
}
var self = this;
this._subscribe = function (observer) {
var oldOnError = observer.onError.bind(observer);
observer.onError = function (err) {
makeStackTraceLong(err, self);
oldOnError(err);
};
return subscribe.call(self, observer);
};
} else {
this._subscribe = subscribe;
}
}
observableProto = Observable.prototype;
/**
* Subscribes an observer to the observable sequence.
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
return this._subscribe(typeof observerOrOnNext === 'object' ?
observerOrOnNext :
observerCreate(observerOrOnNext, onError, onCompleted));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onNext The function to invoke on each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnNext = function (onNext, thisArg) {
return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext));
};
/**
* Subscribes to an exceptional condition in the sequence with an optional "this" argument.
* @param {Function} onError The function to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnError = function (onError, thisArg) {
return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnCompleted = function (onCompleted, thisArg) {
return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted));
};
return Observable;
})();
var ObservableBase = Rx.ObservableBase = (function (__super__) {
inherits(ObservableBase, __super__);
function fixSubscriber(subscriber) {
return subscriber && isFunction(subscriber.dispose) ? subscriber :
isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
}
function setDisposable(s, state) {
var ado = state[0], self = state[1];
var sub = tryCatch(self.subscribeCore).call(self, ado);
if (sub === errorObj) {
if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); }
}
ado.setDisposable(fixSubscriber(sub));
}
function subscribe(observer) {
var ado = new AutoDetachObserver(observer), state = [ado, this];
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.scheduleWithState(state, setDisposable);
} else {
setDisposable(null, state);
}
return ado;
}
function ObservableBase() {
__super__.call(this, subscribe);
}
ObservableBase.prototype.subscribeCore = notImplemented;
return ObservableBase;
}(Observable));
/**
* Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
*
* This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
* that require to be run on a scheduler, use subscribeOn.
*
* @param {Scheduler} scheduler Scheduler to notify observers on.
* @returns {Observable} The source sequence whose observations happen on the specified scheduler.
*/
observableProto.observeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(new ObserveOnObserver(scheduler, observer));
}, source);
};
/**
* Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
* see the remarks section for more information on the distinction between subscribeOn and observeOn.
* This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
* callbacks on a scheduler, use observeOn.
* @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
* @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
d.setDisposable(m);
m.setDisposable(scheduler.schedule(function () {
d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer)));
}));
return d;
}, source);
};
/**
* Converts a Promise to an Observable sequence
* @param {Promise} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise) {
return observableDefer(function () {
var subject = new Rx.AsyncSubject();
promise.then(
function (value) {
subject.onNext(value);
subject.onCompleted();
},
subject.onError.bind(subject));
return subject;
});
};
/*
* Converts an existing observable sequence to an ES6 Compatible Promise
* @example
* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
*
* // With config
* Rx.config.Promise = RSVP.Promise;
* var promise = Rx.Observable.return(42).toPromise();
* @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
* @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
*/
observableProto.toPromise = function (promiseCtor) {
promiseCtor || (promiseCtor = Rx.config.Promise);
if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); }
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, reject, function () {
hasValue && resolve(value);
});
});
};
var ToArrayObservable = (function(__super__) {
inherits(ToArrayObservable, __super__);
function ToArrayObservable(source) {
this.source = source;
__super__.call(this);
}
ToArrayObservable.prototype.subscribeCore = function(observer) {
return this.source.subscribe(new ToArrayObserver(observer));
};
return ToArrayObservable;
}(ObservableBase));
function ToArrayObserver(observer) {
this.observer = observer;
this.a = [];
this.isStopped = false;
}
ToArrayObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } };
ToArrayObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
}
};
ToArrayObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onNext(this.a);
this.observer.onCompleted();
}
};
ToArrayObserver.prototype.dispose = function () { this.isStopped = true; }
ToArrayObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
/**
* Creates an array from an observable sequence.
* @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
return new ToArrayObservable(this);
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
* @example
* var res = Rx.Observable.create(function (observer) { return function () { } );
* var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* var res = Rx.Observable.create(function (observer) { } );
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = Observable.createWithDisposable = function (subscribe, parent) {
return new AnonymousObservable(subscribe, parent);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
isPromise(result) && (result = observableFromPromise(result));
return result.subscribe(observer);
});
};
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithState(null, function () {
observer.onCompleted();
});
});
};
var FromObservable = (function(__super__) {
inherits(FromObservable, __super__);
function FromObservable(iterable, mapper, scheduler) {
this.iterable = iterable;
this.mapper = mapper;
this.scheduler = scheduler;
__super__.call(this);
}
FromObservable.prototype.subscribeCore = function (observer) {
var sink = new FromSink(observer, this);
return sink.run();
};
return FromObservable;
}(ObservableBase));
var FromSink = (function () {
function FromSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
FromSink.prototype.run = function () {
var list = Object(this.parent.iterable),
it = getIterable(list),
observer = this.observer,
mapper = this.parent.mapper;
function loopRecursive(i, recurse) {
try {
var next = it.next();
} catch (e) {
return observer.onError(e);
}
if (next.done) {
return observer.onCompleted();
}
var result = next.value;
if (mapper) {
try {
result = mapper(result, i);
} catch (e) {
return observer.onError(e);
}
}
observer.onNext(result);
recurse(i + 1);
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
return FromSink;
}());
var maxSafeInteger = Math.pow(2, 53) - 1;
function StringIterable(str) {
this._s = s;
}
StringIterable.prototype[$iterator$] = function () {
return new StringIterator(this._s);
};
function StringIterator(str) {
this._s = s;
this._l = s.length;
this._i = 0;
}
StringIterator.prototype[$iterator$] = function () {
return this;
};
StringIterator.prototype.next = function () {
return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator;
};
function ArrayIterable(a) {
this._a = a;
}
ArrayIterable.prototype[$iterator$] = function () {
return new ArrayIterator(this._a);
};
function ArrayIterator(a) {
this._a = a;
this._l = toLength(a);
this._i = 0;
}
ArrayIterator.prototype[$iterator$] = function () {
return this;
};
ArrayIterator.prototype.next = function () {
return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator;
};
function numberIsFinite(value) {
return typeof value === 'number' && root.isFinite(value);
}
function isNan(n) {
return n !== n;
}
function getIterable(o) {
var i = o[$iterator$], it;
if (!i && typeof o === 'string') {
it = new StringIterable(o);
return it[$iterator$]();
}
if (!i && o.length !== undefined) {
it = new ArrayIterable(o);
return it[$iterator$]();
}
if (!i) { throw new TypeError('Object is not iterable'); }
return o[$iterator$]();
}
function sign(value) {
var number = +value;
if (number === 0) { return number; }
if (isNaN(number)) { return number; }
return number < 0 ? -1 : 1;
}
function toLength(o) {
var len = +o.length;
if (isNaN(len)) { return 0; }
if (len === 0 || !numberIsFinite(len)) { return len; }
len = sign(len) * Math.floor(Math.abs(len));
if (len <= 0) { return 0; }
if (len > maxSafeInteger) { return maxSafeInteger; }
return len;
}
/**
* This method creates a new Observable sequence from an array-like or iterable object.
* @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
* @param {Function} [mapFn] Map function to call on every element of the array.
* @param {Any} [thisArg] The context to use calling the mapFn if provided.
* @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
*/
var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) {
if (iterable == null) {
throw new Error('iterable cannot be null.')
}
if (mapFn && !isFunction(mapFn)) {
throw new Error('mapFn when provided must be a function');
}
if (mapFn) {
var mapper = bindCallback(mapFn, thisArg, 2);
}
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromObservable(iterable, mapper, scheduler);
}
var FromArrayObservable = (function(__super__) {
inherits(FromArrayObservable, __super__);
function FromArrayObservable(args, scheduler) {
this.args = args;
this.scheduler = scheduler;
__super__.call(this);
}
FromArrayObservable.prototype.subscribeCore = function (observer) {
var sink = new FromArraySink(observer, this);
return sink.run();
};
return FromArrayObservable;
}(ObservableBase));
function FromArraySink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
FromArraySink.prototype.run = function () {
var observer = this.observer, args = this.parent.args, len = args.length;
function loopRecursive(i, recurse) {
if (i < len) {
observer.onNext(args[i]);
recurse(i + 1);
} else {
observer.onCompleted();
}
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
* @deprecated use Observable.from or Observable.of
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromArrayObservable(array, scheduler)
};
/**
* Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
* @returns {Observable} The generated sequence.
*/
Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (o) {
var first = true;
return scheduler.scheduleRecursiveWithState(initialState, function (state, self) {
var hasResult, result;
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
hasResult && (result = resultSelector(state));
} catch (e) {
return o.onError(e);
}
if (hasResult) {
o.onNext(result);
self(state);
} else {
o.onCompleted();
}
});
});
};
function observableOf (scheduler, array) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromArrayObservable(array, scheduler);
}
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.of = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return new FromArrayObservable(args, currentThreadScheduler);
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.ofWithScheduler = function (scheduler) {
var len = arguments.length, args = new Array(len - 1);
for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; }
return new FromArrayObservable(args, scheduler);
};
/**
* Creates an Observable sequence from changes to an array using Array.observe.
* @param {Array} array An array to observe changes.
* @returns {Observable} An observable sequence containing changes to an array from Array.observe.
*/
Observable.ofArrayChanges = function(array) {
if (!Array.isArray(array)) { throw new TypeError('Array.observe only accepts arrays.'); }
if (typeof Array.observe !== 'function' && typeof Array.unobserve !== 'function') { throw new TypeError('Array.observe is not supported on your platform') }
return new AnonymousObservable(function(observer) {
function observerFn(changes) {
for(var i = 0, len = changes.length; i < len; i++) {
observer.onNext(changes[i]);
}
}
Array.observe(array, observerFn);
return function () {
Array.unobserve(array, observerFn);
};
});
};
/**
* Creates an Observable sequence from changes to an object using Object.observe.
* @param {Object} obj An object to observe changes.
* @returns {Observable} An observable sequence containing changes to an object from Object.observe.
*/
Observable.ofObjectChanges = function(obj) {
if (obj == null) { throw new TypeError('object must not be null or undefined.'); }
if (typeof Object.observe !== 'function' && typeof Object.unobserve !== 'function') { throw new TypeError('Array.observe is not supported on your platform') }
return new AnonymousObservable(function(observer) {
function observerFn(changes) {
for(var i = 0, len = changes.length; i < len; i++) {
observer.onNext(changes[i]);
}
}
Object.observe(obj, observerFn);
return function () {
Object.unobserve(obj, observerFn);
};
});
};
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new AnonymousObservable(function () {
return disposableEmpty;
});
};
/**
* Convert an object into an observable sequence of [key, value] pairs.
* @param {Object} obj The object to inspect.
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} An observable sequence of [key, value] pairs from the object.
*/
Observable.pairs = function (obj, scheduler) {
scheduler || (scheduler = Rx.Scheduler.currentThread);
return new AnonymousObservable(function (observer) {
var keys = Object.keys(obj), len = keys.length;
return scheduler.scheduleRecursiveWithState(0, function (idx, self) {
if (idx < len) {
var key = keys[idx];
observer.onNext([key, obj[key]]);
self(idx + 1);
} else {
observer.onCompleted();
}
});
});
};
var RangeObservable = (function(__super__) {
inherits(RangeObservable, __super__);
function RangeObservable(start, count, scheduler) {
this.start = start;
this.count = count;
this.scheduler = scheduler;
__super__.call(this);
}
RangeObservable.prototype.subscribeCore = function (observer) {
var sink = new RangeSink(observer, this);
return sink.run();
};
return RangeObservable;
}(ObservableBase));
var RangeSink = (function () {
function RangeSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
RangeSink.prototype.run = function () {
var start = this.parent.start, count = this.parent.count, observer = this.observer;
function loopRecursive(i, recurse) {
if (i < count) {
observer.onNext(start + i);
recurse(i + 1);
} else {
observer.onCompleted();
}
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
return RangeSink;
}());
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new RangeObservable(start, count, scheduler);
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.repeat(42);
* var res = Rx.Observable.repeat(42, 4);
* 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'just' or browsers <IE9.
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.just = Observable.returnValue = function (value, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (o) {
return scheduler.scheduleWithState(value, function(_,v) {
o.onNext(v);
o.onCompleted();
});
});
};
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwError' for browsers <IE9.
* @param {Mixed} error An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = Observable.throwError = function (error, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(error);
});
});
};
/** @deprecated use #some instead */
Observable.throwException = function () {
//deprecate('throwException', 'throwError');
return Observable.throwError.apply(null, arguments);
};
/**
* Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
* @param {Function} resourceFactory Factory function to obtain a resource object.
* @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
* @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
Observable.using = function (resourceFactory, observableFactory) {
return new AnonymousObservable(function (observer) {
var disposable = disposableEmpty, resource, source;
try {
resource = resourceFactory();
resource && (disposable = resource);
source = observableFactory(resource);
} catch (exception) {
return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable);
}
return new CompositeDisposable(source.subscribe(observer), disposable);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
* @param {Observable} rightSource Second observable sequence or Promise.
* @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
*/
observableProto.amb = function (rightSource) {
var leftSource = this;
return new AnonymousObservable(function (observer) {
var choice,
leftChoice = 'L', rightChoice = 'R',
leftSubscription = new SingleAssignmentDisposable(),
rightSubscription = new SingleAssignmentDisposable();
isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
function choiceL() {
if (!choice) {
choice = leftChoice;
rightSubscription.dispose();
}
}
function choiceR() {
if (!choice) {
choice = rightChoice;
leftSubscription.dispose();
}
}
leftSubscription.setDisposable(leftSource.subscribe(function (left) {
choiceL();
if (choice === leftChoice) {
observer.onNext(left);
}
}, function (err) {
choiceL();
if (choice === leftChoice) {
observer.onError(err);
}
}, function () {
choiceL();
if (choice === leftChoice) {
observer.onCompleted();
}
}));
rightSubscription.setDisposable(rightSource.subscribe(function (right) {
choiceR();
if (choice === rightChoice) {
observer.onNext(right);
}
}, function (err) {
choiceR();
if (choice === rightChoice) {
observer.onError(err);
}
}, function () {
choiceR();
if (choice === rightChoice) {
observer.onCompleted();
}
}));
return new CompositeDisposable(leftSubscription, rightSubscription);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
*
* @example
* var = Rx.Observable.amb(xs, ys, zs);
* @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
*/
Observable.amb = function () {
var acc = observableNever(), items = [];
if (Array.isArray(arguments[0])) {
items = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); }
}
function func(previous, current) {
return previous.amb(current);
}
for (var i = 0, len = items.length; i < len; i++) {
acc = func(acc, items[i]);
}
return acc;
};
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (o) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(function (x) { o.onNext(x); }, function (e) {
try {
var result = handler(e);
} catch (ex) {
return o.onError(ex);
}
isPromise(result) && (result = observableFromPromise(result));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(o));
}, function (x) { o.onCompleted(x); }));
return subscription;
}, source);
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) {
return typeof handlerOrSecond === 'function' ?
observableCatchHandler(this, handlerOrSecond) :
observableCatch([this, handlerOrSecond]);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs.
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchError = Observable['catch'] = Observable.catchException = function () {
var items = [];
if (Array.isArray(arguments[0])) {
items = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); }
}
return enumerableOf(items).catchError();
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var resultSelector = args.pop();
Array.isArray(args[0]) && (args = args[0]);
return new AnonymousObservable(function (o) {
var n = args.length,
falseFactory = function () { return false; },
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
var res = resultSelector.apply(null, values);
} catch (e) {
return o.onError(e);
}
o.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
o.onCompleted();
}
}
function done (i) {
isDone[i] = true;
isDone.every(identity) && o.onCompleted();
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
},
function(e) { o.onError(e); },
function () { done(i); }
));
subscriptions[i] = sad;
}(idx));
}
return new CompositeDisposable(subscriptions);
}, this);
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
args.unshift(this);
return observableConcat.apply(null, args);
};
/**
* Concatenates all the observable sequences.
* @param {Array | Arguments} args Arguments or an array to concat to the observable sequence.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
var args;
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
args = new Array(arguments.length);
for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; }
}
return enumerableOf(args).concat();
};
/**
* Concatenates an observable sequence of observable sequences.
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatAll = observableProto.concatObservable = function () {
return this.merge(1);
};
var MergeObservable = (function (__super__) {
inherits(MergeObservable, __super__);
function MergeObservable(source, maxConcurrent) {
this.source = source;
this.maxConcurrent = maxConcurrent;
__super__.call(this);
}
MergeObservable.prototype.subscribeCore = function(observer) {
var g = new CompositeDisposable();
g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g)));
return g;
};
return MergeObservable;
}(ObservableBase));
var MergeObserver = (function () {
function MergeObserver(o, max, g) {
this.o = o;
this.max = max;
this.g = g;
this.done = false;
this.q = [];
this.activeCount = 0;
this.isStopped = false;
}
MergeObserver.prototype.handleSubscribe = function (xs) {
var sad = new SingleAssignmentDisposable();
this.g.add(sad);
isPromise(xs) && (xs = observableFromPromise(xs));
sad.setDisposable(xs.subscribe(new InnerObserver(this, sad)));
};
MergeObserver.prototype.onNext = function (innerSource) {
if (this.isStopped) { return; }
if(this.activeCount < this.max) {
this.activeCount++;
this.handleSubscribe(innerSource);
} else {
this.q.push(innerSource);
}
};
MergeObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
}
};
MergeObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.done = true;
this.activeCount === 0 && this.o.onCompleted();
}
};
MergeObserver.prototype.dispose = function() { this.isStopped = true; };
MergeObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
function InnerObserver(parent, sad) {
this.parent = parent;
this.sad = sad;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.parent.o.onNext(x); } };
InnerObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
}
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
this.isStopped = true;
var parent = this.parent;
parent.g.remove(this.sad);
if (parent.q.length > 0) {
parent.handleSubscribe(parent.q.shift());
} else {
parent.activeCount--;
parent.done && parent.activeCount === 0 && parent.o.onCompleted();
}
}
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
return true;
}
return false;
};
return MergeObserver;
}());
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
return typeof maxConcurrentOrOther !== 'number' ?
observableMerge(this, maxConcurrentOrOther) :
new MergeObservable(this, maxConcurrentOrOther);
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources = [], i, len = arguments.length;
if (!arguments[0]) {
scheduler = immediateScheduler;
for(i = 1; i < len; i++) { sources.push(arguments[i]); }
} else if (isScheduler(arguments[0])) {
scheduler = arguments[0];
for(i = 1; i < len; i++) { sources.push(arguments[i]); }
} else {
scheduler = immediateScheduler;
for(i = 0; i < len; i++) { sources.push(arguments[i]); }
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableOf(scheduler, sources).mergeAll();
};
var MergeAllObservable = (function (__super__) {
inherits(MergeAllObservable, __super__);
function MergeAllObservable(source) {
this.source = source;
__super__.call(this);
}
MergeAllObservable.prototype.subscribeCore = function (observer) {
var g = new CompositeDisposable(), m = new SingleAssignmentDisposable();
g.add(m);
m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g)));
return g;
};
return MergeAllObservable;
}(ObservableBase));
var MergeAllObserver = (function() {
function MergeAllObserver(o, g) {
this.o = o;
this.g = g;
this.isStopped = false;
this.done = false;
}
MergeAllObserver.prototype.onNext = function(innerSource) {
if(this.isStopped) { return; }
var sad = new SingleAssignmentDisposable();
this.g.add(sad);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad)));
};
MergeAllObserver.prototype.onError = function (e) {
if(!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
}
};
MergeAllObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
this.isStopped = true;
this.done = true;
this.g.length === 1 && this.o.onCompleted();
}
};
MergeAllObserver.prototype.dispose = function() { this.isStopped = true; };
MergeAllObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
function InnerObserver(parent, g, sad) {
this.parent = parent;
this.g = g;
this.sad = sad;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } };
InnerObserver.prototype.onError = function (e) {
if(!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
}
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
var parent = this.parent;
this.isStopped = true;
parent.g.remove(this.sad);
parent.done && parent.g.length === 1 && parent.o.onCompleted();
}
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
return true;
}
return false;
};
return MergeAllObserver;
}());
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeAll = observableProto.mergeObservable = function () {
return new MergeAllObservable(this);
};
var CompositeError = Rx.CompositeError = function(errors) {
this.name = "NotImplementedError";
this.innerErrors = errors;
this.message = 'This contains multiple errors. Check the innerErrors';
Error.call(this);
}
CompositeError.prototype = Error.prototype;
/**
* Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to
* receive all successfully emitted items from all of the source Observables without being interrupted by
* an error notification from one of them.
*
* This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an
* error via the Observer's onError, mergeDelayError will refrain from propagating that
* error notification until all of the merged Observables have finished emitting items.
* @param {Array | Arguments} args Arguments or an array to merge.
* @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable
*/
Observable.mergeDelayError = function() {
var args;
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
var len = arguments.length;
args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
}
var source = observableOf(null, args);
return new AnonymousObservable(function (o) {
var group = new CompositeDisposable(),
m = new SingleAssignmentDisposable(),
isStopped = false,
errors = [];
function setCompletion() {
if (errors.length === 0) {
o.onCompleted();
} else if (errors.length === 1) {
o.onError(errors[0]);
} else {
o.onError(new CompositeError(errors));
}
}
group.add(m);
m.setDisposable(source.subscribe(
function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
// Check for promises support
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(
function (x) { o.onNext(x); },
function (e) {
errors.push(e);
group.remove(innerSubscription);
isStopped && group.length === 1 && setCompletion();
},
function () {
group.remove(innerSubscription);
isStopped && group.length === 1 && setCompletion();
}));
},
function (e) {
errors.push(e);
isStopped = true;
group.length === 1 && setCompletion();
},
function () {
isStopped = true;
group.length === 1 && setCompletion();
}));
return group;
});
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
* @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.
* @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.
*/
observableProto.onErrorResumeNext = function (second) {
if (!second) { throw new Error('Second observable is required'); }
return onErrorResumeNext([this, second]);
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs);
* 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]);
* @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.
*/
var onErrorResumeNext = Observable.onErrorResumeNext = function () {
var sources = [];
if (Array.isArray(arguments[0])) {
sources = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
}
return new AnonymousObservable(function (observer) {
var pos = 0, subscription = new SerialDisposable(),
cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, d;
if (pos < sources.length) {
current = sources[pos++];
isPromise(current) && (current = observableFromPromise(current));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self));
} else {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (o) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
isOpen && o.onNext(left);
}, function (e) { o.onError(e); }, function () {
isOpen && o.onCompleted();
}));
isPromise(other) && (other = observableFromPromise(other));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, function (e) { o.onError(e); }, function () {
rightSubscription.dispose();
}));
return disposables;
}, source);
};
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasLatest = false,
innerSubscription = new SerialDisposable(),
isStopped = false,
latest = 0,
subscription = sources.subscribe(
function (innerSource) {
var d = new SingleAssignmentDisposable(), id = ++latest;
hasLatest = true;
innerSubscription.setDisposable(d);
// Check if Promise or Observable
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
d.setDisposable(innerSource.subscribe(
function (x) { latest === id && observer.onNext(x); },
function (e) { latest === id && observer.onError(e); },
function () {
if (latest === id) {
hasLatest = false;
isStopped && observer.onCompleted();
}
}));
},
function (e) { observer.onError(e); },
function () {
isStopped = true;
!hasLatest && observer.onCompleted();
});
return new CompositeDisposable(subscription, innerSubscription);
}, sources);
};
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
var source = this;
return new AnonymousObservable(function (o) {
isPromise(other) && (other = observableFromPromise(other));
return new CompositeDisposable(
source.subscribe(o),
other.subscribe(function () { o.onCompleted(); }, function (e) { o.onError(e); }, noop)
);
}, source);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element.
*
* @example
* 1 - obs = obs1.withLatestFrom(obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = obs1.withLatestFrom([obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.withLatestFrom = function () {
var len = arguments.length, args = new Array(len)
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var resultSelector = args.pop(), source = this;
if (typeof source === 'undefined') {
throw new Error('Source observable not found for withLatestFrom().');
}
if (typeof resultSelector !== 'function') {
throw new Error('withLatestFrom() expects a resultSelector function.');
}
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
values = new Array(n);
var subscriptions = new Array(n + 1);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var other = args[i], sad = new SingleAssignmentDisposable();
isPromise(other) && (other = observableFromPromise(other));
sad.setDisposable(other.subscribe(function (x) {
values[i] = x;
hasValue[i] = true;
hasValueAll = hasValue.every(identity);
}, observer.onError.bind(observer), function () {}));
subscriptions[i] = sad;
}(idx));
}
var sad = new SingleAssignmentDisposable();
sad.setDisposable(source.subscribe(function (x) {
var res;
var allValues = [x].concat(values);
if (!hasValueAll) return;
try {
res = resultSelector.apply(null, allValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
}, observer.onError.bind(observer), function () {
observer.onCompleted();
}));
subscriptions[n] = sad;
return new CompositeDisposable(subscriptions);
}, this);
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], result;
try {
result = resultSelector(left, right);
} catch (e) {
return observer.onError(e);
}
observer.onNext(result);
} else {
observer.onCompleted();
}
}, function (e) { observer.onError(e); }, function () { observer.onCompleted(); });
}, first);
}
function falseFactory() { return false; }
function emptyArrayFactory() { return []; }
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args.
*
* @example
* 1 - res = obs1.zip(obs2, fn);
* 1 - res = x1.zip([1,2,3], fn);
* @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function.
*/
observableProto.zip = function () {
if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); }
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var parent = this, resultSelector = args.pop();
args.unshift(parent);
return new AnonymousObservable(function (observer) {
var n = args.length,
queues = arrayInitialize(n, emptyArrayFactory),
isDone = arrayInitialize(n, falseFactory);
function next(i) {
var res, queuedValues;
if (queues.every(function (x) { return x.length > 0; })) {
try {
queuedValues = queues.map(function (x) { return x.shift(); });
res = resultSelector.apply(parent, queuedValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
next(i);
}, function (e) { observer.onError(e); }, function () {
done(i);
}));
subscriptions[i] = sad;
})(idx);
}
return new CompositeDisposable(subscriptions);
}, parent);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var first = args.shift();
return first.zip.apply(first, args);
};
/**
* Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
* @param arguments Observable sources.
* @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
*/
Observable.zipArray = function () {
var sources;
if (Array.isArray(arguments[0])) {
sources = arguments[0];
} else {
var len = arguments.length;
sources = new Array(len);
for(var i = 0; i < len; i++) { sources[i] = arguments[i]; }
}
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
if (queues.every(function (x) { return x.length > 0; })) {
var res = queues.map(function (x) { return x.shift(); });
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
return;
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
return;
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, function (e) { observer.onError(e); }, function () {
done(i);
}));
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
var source = this;
return new AnonymousObservable(function (o) { return source.subscribe(o); }, this);
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
*
* @example
* var res = xs.bufferWithCount(10);
* var res = xs.bufferWithCount(10, 1);
* @param {Number} count Length of each buffer.
* @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithCount = function (count, skip) {
if (typeof skip !== 'number') {
skip = count;
}
return this.windowWithCount(count, skip).selectMany(function (x) {
return x.toArray();
}).where(function (x) {
return x.length > 0;
});
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (o) {
return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
*
* var obs = observable.distinctUntilChanged();
* var obs = observable.distinctUntilChanged(function (x) { return x.id; });
* var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
*
* @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keySelector, comparer) {
var source = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (o) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var key = value;
if (keySelector) {
try {
key = keySelector(value);
} catch (e) {
o.onError(e);
return;
}
}
if (hasCurrentKey) {
try {
var comparerEquals = comparer(currentKey, key);
} catch (e) {
o.onError(e);
return;
}
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
o.onNext(value);
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {
var source = this;
return new AnonymousObservable(function (observer) {
var tapObserver = !observerOrOnNext || isFunction(observerOrOnNext) ?
observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) :
observerOrOnNext;
return source.subscribe(function (x) {
try {
tapObserver.onNext(x);
} catch (e) {
observer.onError(e);
}
observer.onNext(x);
}, function (err) {
try {
tapObserver.onError(err);
} catch (e) {
observer.onError(e);
}
observer.onError(err);
}, function () {
try {
tapObserver.onCompleted();
} catch (e) {
observer.onError(e);
}
observer.onCompleted();
});
}, this);
};
/**
* Invokes an action for each element in the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onNext Action to invoke for each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) {
return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext);
};
/**
* Invokes an action upon exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onError Action to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) {
return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError);
};
/**
* Invokes an action upon graceful termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) {
return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted);
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto['finally'] = observableProto.ensure = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription;
try {
subscription = source.subscribe(observer);
} catch (e) {
action();
throw e;
}
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
}, this);
};
/**
* @deprecated use #finally or #ensure instead.
*/
observableProto.finallyAction = function (action) {
//deprecate('finallyAction', 'finally or ensure');
return this.ensure(action);
};
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
var source = this;
return new AnonymousObservable(function (o) {
return source.subscribe(noop, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (e) {
observer.onNext(notificationCreateOnError(e));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
}, source);
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
* Note if you encounter an error and want it to retry once, then you must use .retry(2);
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(2);
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchError();
};
/**
* Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates.
* if the notifier completes, the observable sequence completes.
*
* @example
* var timer = Observable.timer(500);
* var source = observable.retryWhen(timer);
* @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retryWhen = function (notifier) {
return enumerableRepeat(this).catchErrorWhen(notifier);
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @example
* var res = source.scan(function (acc, x) { return acc + x; });
* var res = source.scan(0, function (acc, x) { return acc + x; });
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (o) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
!hasValue && (hasValue = true);
try {
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
o.onError(e);
return;
}
o.onNext(accumulation);
},
function (e) { o.onError(e); },
function () {
!hasValue && hasSeed && o.onNext(seed);
o.onCompleted();
}
);
}, source);
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
* @description
* This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && o.onNext(q.shift());
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
* @example
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
* @param {Arguments} args The specified values to prepend to the observable sequence
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && isScheduler(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
return enumerableOf([observableFromArray(args, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence.
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, function (e) { o.onError(e); }, function () {
while (q.length > 0) { o.onNext(q.shift()); }
o.onCompleted();
});
}, source);
};
/**
* Returns an array with the specified number of contiguous elements from the end of an observable sequence.
*
* @description
* This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
* source sequence, this buffer is produced on the result sequence.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
*/
observableProto.takeLastBuffer = function (count) {
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, function (e) { o.onError(e); }, function () {
o.onNext(q);
o.onCompleted();
});
}, source);
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
*
* var res = xs.windowWithCount(10);
* var res = xs.windowWithCount(10, 1);
* @param {Number} count Length of each window.
* @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithCount = function (count, skip) {
var source = this;
+count || (count = 0);
Math.abs(count) === Infinity && (count = 0);
if (count <= 0) { throw new ArgumentOutOfRangeError(); }
skip == null && (skip = count);
+skip || (skip = 0);
Math.abs(skip) === Infinity && (skip = 0);
if (skip <= 0) { throw new ArgumentOutOfRangeError(); }
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(),
refCountDisposable = new RefCountDisposable(m),
n = 0,
q = [];
function createWindow () {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
}
createWindow();
m.setDisposable(source.subscribe(
function (x) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
var c = n - count + 1;
c >= 0 && c % skip === 0 && q.shift().onCompleted();
++n % skip === 0 && createWindow();
},
function (e) {
while (q.length > 0) { q.shift().onError(e); }
observer.onError(e);
},
function () {
while (q.length > 0) { q.shift().onCompleted(); }
observer.onCompleted();
}
));
return refCountDisposable;
}, source);
};
function concatMap(source, selector, thisArg) {
var selectorFunc = bindCallback(selector, thisArg, 3);
return source.map(function (x, i) {
var result = selectorFunc(x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).concatAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.concatMap(Rx.Observable.fromArray([1,2,3]));
* @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) {
if (isFunction(selector) && isFunction(resultSelector)) {
return this.concatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
});
}
return isFunction(selector) ?
concatMap(this, selector, thisArg) :
concatMap(this, function () { return selector; });
};
/**
* Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) {
var source = this,
onNextFunc = bindCallback(onNext, thisArg, 2),
onErrorFunc = bindCallback(onError, thisArg, 1),
onCompletedFunc = bindCallback(onCompleted, thisArg, 0);
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNextFunc(x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onErrorFunc(err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompletedFunc();
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}, this).concatAll();
};
/**
* Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
*
* var res = obs = xs.defaultIfEmpty();
* 2 - obs = xs.defaultIfEmpty(false);
*
* @memberOf Observable#
* @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
* @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
*/
observableProto.defaultIfEmpty = function (defaultValue) {
var source = this;
defaultValue === undefined && (defaultValue = null);
return new AnonymousObservable(function (observer) {
var found = false;
return source.subscribe(function (x) {
found = true;
observer.onNext(x);
},
function (e) { observer.onError(e); },
function () {
!found && observer.onNext(defaultValue);
observer.onCompleted();
});
}, source);
};
// Swap out for Array.findIndex
function arrayIndexOfComparer(array, item, comparer) {
for (var i = 0, len = array.length; i < len; i++) {
if (comparer(array[i], item)) { return i; }
}
return -1;
}
function HashSet(comparer) {
this.comparer = comparer;
this.set = [];
}
HashSet.prototype.push = function(value) {
var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1;
retValue && this.set.push(value);
return retValue;
};
/**
* Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
* Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
*
* @example
* var res = obs = xs.distinct();
* 2 - obs = xs.distinct(function (x) { return x.id; });
* 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; });
* @param {Function} [keySelector] A function to compute the comparison key for each element.
* @param {Function} [comparer] Used to compare items in the collection.
* @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
*/
observableProto.distinct = function (keySelector, comparer) {
var source = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (o) {
var hashSet = new HashSet(comparer);
return source.subscribe(function (x) {
var key = x;
if (keySelector) {
try {
key = keySelector(x);
} catch (e) {
o.onError(e);
return;
}
}
hashSet.push(key) && o.onNext(x);
},
function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
/**
* Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function.
*
* @example
* var res = observable.groupBy(function (x) { return x.id; });
* 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; });
* 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); });
* @param {Function} keySelector A function to extract the key for each element.
* @param {Function} [elementSelector] A function to map each source element to an element in an observable group.
* @param {Function} [comparer] Used to determine whether the objects are equal.
* @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
*/
observableProto.groupBy = function (keySelector, elementSelector, comparer) {
return this.groupByUntil(keySelector, elementSelector, observableNever, comparer);
};
/**
* Groups the elements of an observable sequence according to a specified key selector function.
* A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same
* key value as a reclaimed group occurs, the group will be reborn with a new lifetime request.
*
* @example
* var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); });
* 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); });
* 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); });
* @param {Function} keySelector A function to extract the key for each element.
* @param {Function} durationSelector A function to signal the expiration of a group.
* @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used.
* @returns {Observable}
* A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
* If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered.
*
*/
observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) {
var source = this;
elementSelector || (elementSelector = identity);
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
function handleError(e) { return function (item) { item.onError(e); }; }
var map = new Dictionary(0, comparer),
groupDisposable = new CompositeDisposable(),
refCountDisposable = new RefCountDisposable(groupDisposable);
groupDisposable.add(source.subscribe(function (x) {
var key;
try {
key = keySelector(x);
} catch (e) {
map.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
var fireNewMapEntry = false,
writer = map.tryGetValue(key);
if (!writer) {
writer = new Subject();
map.set(key, writer);
fireNewMapEntry = true;
}
if (fireNewMapEntry) {
var group = new GroupedObservable(key, writer, refCountDisposable),
durationGroup = new GroupedObservable(key, writer);
try {
duration = durationSelector(durationGroup);
} catch (e) {
map.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
observer.onNext(group);
var md = new SingleAssignmentDisposable();
groupDisposable.add(md);
var expire = function () {
map.remove(key) && writer.onCompleted();
groupDisposable.remove(md);
};
md.setDisposable(duration.take(1).subscribe(
noop,
function (exn) {
map.getValues().forEach(handleError(exn));
observer.onError(exn);
},
expire)
);
}
var element;
try {
element = elementSelector(x);
} catch (e) {
map.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
writer.onNext(element);
}, function (ex) {
map.getValues().forEach(handleError(ex));
observer.onError(ex);
}, function () {
map.getValues().forEach(function (item) { item.onCompleted(); });
observer.onCompleted();
}));
return refCountDisposable;
}, source);
};
var MapObservable = (function (__super__) {
inherits(MapObservable, __super__);
function MapObservable(source, selector, thisArg) {
this.source = source;
this.selector = bindCallback(selector, thisArg, 3);
__super__.call(this);
}
MapObservable.prototype.internalMap = function (selector, thisArg) {
var self = this;
return new MapObservable(this.source, function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); }, thisArg)
};
MapObservable.prototype.subscribeCore = function (observer) {
return this.source.subscribe(new MapObserver(observer, this.selector, this));
};
return MapObservable;
}(ObservableBase));
function MapObserver(observer, selector, source) {
this.observer = observer;
this.selector = selector;
this.source = source;
this.i = 0;
this.isStopped = false;
}
MapObserver.prototype.onNext = function(x) {
if (this.isStopped) { return; }
var result = tryCatch(this.selector).call(this, x, this.i++, this.source);
if (result === errorObj) {
return this.observer.onError(result.e);
}
this.observer.onNext(result);
};
MapObserver.prototype.onError = function (e) {
if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); }
};
MapObserver.prototype.onCompleted = function () {
if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); }
};
MapObserver.prototype.dispose = function() { this.isStopped = true; };
MapObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.map = observableProto.select = function (selector, thisArg) {
var selectorFn = typeof selector === 'function' ? selector : function () { return selector; };
return this instanceof MapObservable ?
this.internalMap(selectorFn, thisArg) :
new MapObservable(this, selectorFn, thisArg);
};
/**
* Retrieves the value of a specified nested property from all elements in
* the Observable sequence.
* @param {Arguments} arguments The nested properties to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function () {
var args = arguments, len = arguments.length;
if (len === 0) { throw new Error('List of properties cannot be empty.'); }
return this.map(function (x) {
var currentProp = x;
for (var i = 0; i < len; i++) {
var p = currentProp[args[i]];
if (typeof p !== 'undefined') {
currentProp = p;
} else {
return undefined;
}
}
return currentProp;
});
};
function flatMap(source, selector, thisArg) {
var selectorFunc = bindCallback(selector, thisArg, 3);
return source.map(function (x, i) {
var result = selectorFunc(x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).mergeAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) {
if (isFunction(selector) && isFunction(resultSelector)) {
return this.flatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
}, thisArg);
}
return isFunction(selector) ?
flatMap(this, selector, thisArg) :
flatMap(this, function () { return selector; });
};
/**
* Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNext.call(thisArg, x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onError.call(thisArg, err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompleted.call(thisArg);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}, source).mergeAll();
};
/**
* Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
* transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
* and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) {
return this.select(selector, thisArg).switchLatest();
};
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var remaining = count;
return source.subscribe(function (x) {
if (remaining <= 0) {
o.onNext(x);
} else {
remaining--;
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* var res = source.skipWhile(function (value) { return value < 10; });
* var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate, thisArg) {
var source = this,
callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !callback(x, i++, source);
} catch (e) {
o.onError(e);
return;
}
}
running && o.onNext(x);
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* var res = source.take(5);
* var res = source.take(0, Rx.Scheduler.timeout);
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
if (count === 0) { return observableEmpty(scheduler); }
var source = this;
return new AnonymousObservable(function (o) {
var remaining = count;
return source.subscribe(function (x) {
if (remaining-- > 0) {
o.onNext(x);
remaining === 0 && o.onCompleted();
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var source = this,
callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0, running = true;
return source.subscribe(function (x) {
if (running) {
try {
running = callback(x, i++, source);
} catch (e) {
o.onError(e);
return;
}
if (running) {
o.onNext(x);
} else {
o.onCompleted();
}
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
var FilterObservable = (function (__super__) {
inherits(FilterObservable, __super__);
function FilterObservable(source, predicate, thisArg) {
this.source = source;
this.predicate = bindCallback(predicate, thisArg, 3);
__super__.call(this);
}
FilterObservable.prototype.subscribeCore = function (observer) {
return this.source.subscribe(new FilterObserver(observer, this.predicate, this));
};
FilterObservable.prototype.internalFilter = function(predicate, thisArg) {
var self = this;
return new FilterObservable(this.source, function(x, i, o) { return self.predicate(x, i, o) && predicate.call(this, x, i, o); }, thisArg);
};
return FilterObservable;
}(ObservableBase));
function FilterObserver(observer, predicate, source) {
this.observer = observer;
this.predicate = predicate;
this.source = source;
this.i = 0;
this.isStopped = false;
}
FilterObserver.prototype.onNext = function(x) {
if (this.isStopped) { return; }
var shouldYield = tryCatch(this.predicate).call(this, x, this.i++, this.source);
if (shouldYield === errorObj) {
return this.observer.onError(shouldYield.e);
}
shouldYield && this.observer.onNext(x);
};
FilterObserver.prototype.onError = function (e) {
if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); }
};
FilterObserver.prototype.onCompleted = function () {
if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); }
};
FilterObserver.prototype.dispose = function() { this.isStopped = true; };
FilterObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.filter = observableProto.where = function (predicate, thisArg) {
return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) :
new FilterObservable(this, predicate, thisArg);
};
function extremaBy(source, keySelector, comparer) {
return new AnonymousObservable(function (o) {
var hasValue = false, lastKey = null, list = [];
return source.subscribe(function (x) {
var comparison, key;
try {
key = keySelector(x);
} catch (ex) {
o.onError(ex);
return;
}
comparison = 0;
if (!hasValue) {
hasValue = true;
lastKey = key;
} else {
try {
comparison = comparer(key, lastKey);
} catch (ex1) {
o.onError(ex1);
return;
}
}
if (comparison > 0) {
lastKey = key;
list = [];
}
if (comparison >= 0) { list.push(x); }
}, function (e) { o.onError(e); }, function () {
o.onNext(list);
o.onCompleted();
});
}, source);
}
function firstOnly(x) {
if (x.length === 0) { throw new EmptyError(); }
return x[0];
}
/**
* Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.
* For aggregation behavior with incremental intermediate results, see Observable.scan.
* @deprecated Use #reduce instead
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing a single element with the final accumulator value.
*/
observableProto.aggregate = function () {
var hasSeed = false, accumulator, seed, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (o) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
!hasValue && (hasValue = true);
try {
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
return o.onError(e);
}
},
function (e) { o.onError(e); },
function () {
hasValue && o.onNext(accumulation);
!hasValue && hasSeed && o.onNext(seed);
!hasValue && !hasSeed && o.onError(new EmptyError());
o.onCompleted();
}
);
}, source);
};
/**
* Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.
* For aggregation behavior with incremental intermediate results, see Observable.scan.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @param {Any} [seed] The initial accumulator value.
* @returns {Observable} An observable sequence containing a single element with the final accumulator value.
*/
observableProto.reduce = function (accumulator) {
var hasSeed = false, seed, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[1];
}
return new AnonymousObservable(function (o) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
!hasValue && (hasValue = true);
try {
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
return o.onError(e);
}
},
function (e) { o.onError(e); },
function () {
hasValue && o.onNext(accumulation);
!hasValue && hasSeed && o.onNext(seed);
!hasValue && !hasSeed && o.onError(new EmptyError());
o.onCompleted();
}
);
}, source);
};
/**
* Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence.
* @param {Function} [predicate] A function to test each element for a condition.
* @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence.
*/
observableProto.some = function (predicate, thisArg) {
var source = this;
return predicate ?
source.filter(predicate, thisArg).some() :
new AnonymousObservable(function (observer) {
return source.subscribe(function () {
observer.onNext(true);
observer.onCompleted();
}, function (e) { observer.onError(e); }, function () {
observer.onNext(false);
observer.onCompleted();
});
}, source);
};
/** @deprecated use #some instead */
observableProto.any = function () {
//deprecate('any', 'some');
return this.some.apply(this, arguments);
};
/**
* Determines whether an observable sequence is empty.
* @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty.
*/
observableProto.isEmpty = function () {
return this.any().map(not);
};
/**
* Determines whether all elements of an observable sequence satisfy a condition.
* @param {Function} [predicate] A function to test each element for a condition.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate.
*/
observableProto.every = function (predicate, thisArg) {
return this.filter(function (v) { return !predicate(v); }, thisArg).some().map(not);
};
/** @deprecated use #every instead */
observableProto.all = function () {
//deprecate('all', 'every');
return this.every.apply(this, arguments);
};
/**
* Determines whether an observable sequence includes a specified element with an optional equality comparer.
* @param searchElement The value to locate in the source sequence.
* @param {Number} [fromIndex] An equality comparer to compare elements.
* @returns {Observable} An observable sequence containing a single element determining whether the source sequence includes an element that has the specified value from the given index.
*/
observableProto.includes = function (searchElement, fromIndex) {
var source = this;
function comparer(a, b) {
return (a === 0 && b === 0) || (a === b || (isNaN(a) && isNaN(b)));
}
return new AnonymousObservable(function (o) {
var i = 0, n = +fromIndex || 0;
Math.abs(n) === Infinity && (n = 0);
if (n < 0) {
o.onNext(false);
o.onCompleted();
return disposableEmpty;
}
return source.subscribe(
function (x) {
if (i++ >= n && comparer(x, searchElement)) {
o.onNext(true);
o.onCompleted();
}
},
function (e) { o.onError(e); },
function () {
o.onNext(false);
o.onCompleted();
});
}, this);
};
/**
* @deprecated use #includes instead.
*/
observableProto.contains = function (searchElement, fromIndex) {
//deprecate('contains', 'includes');
observableProto.includes(searchElement, fromIndex);
};
/**
* Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items.
* @example
* res = source.count();
* res = source.count(function (x) { return x > 3; });
* @param {Function} [predicate]A function to test each element for a condition.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence.
*/
observableProto.count = function (predicate, thisArg) {
return predicate ?
this.filter(predicate, thisArg).count() :
this.reduce(function (count) { return count + 1; }, 0);
};
/**
* Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present.
* @param {Any} searchElement Element to locate in the array.
* @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0.
* @returns {Observable} And observable sequence containing the first index at which a given element can be found in the observable sequence, or -1 if it is not present.
*/
observableProto.indexOf = function(searchElement, fromIndex) {
var source = this;
return new AnonymousObservable(function (o) {
var i = 0, n = +fromIndex || 0;
Math.abs(n) === Infinity && (n = 0);
if (n < 0) {
o.onNext(-1);
o.onCompleted();
return disposableEmpty;
}
return source.subscribe(
function (x) {
if (i >= n && x === searchElement) {
o.onNext(i);
o.onCompleted();
}
i++;
},
function (e) { o.onError(e); },
function () {
o.onNext(-1);
o.onCompleted();
});
}, source);
};
/**
* Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence.
* @param {Function} [selector] A transform function to apply to each element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence.
*/
observableProto.sum = function (keySelector, thisArg) {
return keySelector && isFunction(keySelector) ?
this.map(keySelector, thisArg).sum() :
this.reduce(function (prev, curr) { return prev + curr; }, 0);
};
/**
* Returns the elements in an observable sequence with the minimum key value according to the specified comparer.
* @example
* var res = source.minBy(function (x) { return x.value; });
* var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; });
* @param {Function} keySelector Key selector function.
* @param {Function} [comparer] Comparer used to compare key values.
* @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value.
*/
observableProto.minBy = function (keySelector, comparer) {
comparer || (comparer = defaultSubComparer);
return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; });
};
/**
* Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check.
* @example
* var res = source.min();
* var res = source.min(function (x, y) { return x.value - y.value; });
* @param {Function} [comparer] Comparer used to compare elements.
* @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence.
*/
observableProto.min = function (comparer) {
return this.minBy(identity, comparer).map(function (x) { return firstOnly(x); });
};
/**
* Returns the elements in an observable sequence with the maximum key value according to the specified comparer.
* @example
* var res = source.maxBy(function (x) { return x.value; });
* var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; });
* @param {Function} keySelector Key selector function.
* @param {Function} [comparer] Comparer used to compare key values.
* @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value.
*/
observableProto.maxBy = function (keySelector, comparer) {
comparer || (comparer = defaultSubComparer);
return extremaBy(this, keySelector, comparer);
};
/**
* Returns the maximum value in an observable sequence according to the specified comparer.
* @example
* var res = source.max();
* var res = source.max(function (x, y) { return x.value - y.value; });
* @param {Function} [comparer] Comparer used to compare elements.
* @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence.
*/
observableProto.max = function (comparer) {
return this.maxBy(identity, comparer).map(function (x) { return firstOnly(x); });
};
/**
* Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present.
* @param {Function} [selector] A transform function to apply to each element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with the average of the sequence of values.
*/
observableProto.average = function (keySelector, thisArg) {
return keySelector && isFunction(keySelector) ?
this.map(keySelector, thisArg).average() :
this.reduce(function (prev, cur) {
return {
sum: prev.sum + cur,
count: prev.count + 1
};
}, {sum: 0, count: 0 }).map(function (s) {
if (s.count === 0) { throw new EmptyError(); }
return s.sum / s.count;
});
};
/**
* Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer.
*
* @example
* var res = res = source.sequenceEqual([1,2,3]);
* var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; });
* 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42));
* 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; });
* @param {Observable} second Second observable sequence or array to compare.
* @param {Function} [comparer] Comparer used to compare elements of both sequences.
* @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer.
*/
observableProto.sequenceEqual = function (second, comparer) {
var first = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (o) {
var donel = false, doner = false, ql = [], qr = [];
var subscription1 = first.subscribe(function (x) {
var equal, v;
if (qr.length > 0) {
v = qr.shift();
try {
equal = comparer(v, x);
} catch (e) {
o.onError(e);
return;
}
if (!equal) {
o.onNext(false);
o.onCompleted();
}
} else if (doner) {
o.onNext(false);
o.onCompleted();
} else {
ql.push(x);
}
}, function(e) { o.onError(e); }, function () {
donel = true;
if (ql.length === 0) {
if (qr.length > 0) {
o.onNext(false);
o.onCompleted();
} else if (doner) {
o.onNext(true);
o.onCompleted();
}
}
});
(isArrayLike(second) || isIterable(second)) && (second = observableFrom(second));
isPromise(second) && (second = observableFromPromise(second));
var subscription2 = second.subscribe(function (x) {
var equal;
if (ql.length > 0) {
var v = ql.shift();
try {
equal = comparer(v, x);
} catch (exception) {
o.onError(exception);
return;
}
if (!equal) {
o.onNext(false);
o.onCompleted();
}
} else if (donel) {
o.onNext(false);
o.onCompleted();
} else {
qr.push(x);
}
}, function(e) { o.onError(e); }, function () {
doner = true;
if (qr.length === 0) {
if (ql.length > 0) {
o.onNext(false);
o.onCompleted();
} else if (donel) {
o.onNext(true);
o.onCompleted();
}
}
});
return new CompositeDisposable(subscription1, subscription2);
}, first);
};
function elementAtOrDefault(source, index, hasDefault, defaultValue) {
if (index < 0) { throw new ArgumentOutOfRangeError(); }
return new AnonymousObservable(function (o) {
var i = index;
return source.subscribe(function (x) {
if (i-- === 0) {
o.onNext(x);
o.onCompleted();
}
}, function (e) { o.onError(e); }, function () {
if (!hasDefault) {
o.onError(new ArgumentOutOfRangeError());
} else {
o.onNext(defaultValue);
o.onCompleted();
}
});
}, source);
}
/**
* Returns the element at a specified index in a sequence.
* @example
* var res = source.elementAt(5);
* @param {Number} index The zero-based index of the element to retrieve.
* @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence.
*/
observableProto.elementAt = function (index) {
return elementAtOrDefault(this, index, false);
};
/**
* Returns the element at a specified index in a sequence or a default value if the index is out of range.
* @example
* var res = source.elementAtOrDefault(5);
* var res = source.elementAtOrDefault(5, 0);
* @param {Number} index The zero-based index of the element to retrieve.
* @param [defaultValue] The default value if the index is outside the bounds of the source sequence.
* @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence.
*/
observableProto.elementAtOrDefault = function (index, defaultValue) {
return elementAtOrDefault(this, index, true, defaultValue);
};
function singleOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (o) {
var value = defaultValue, seenValue = false;
return source.subscribe(function (x) {
if (seenValue) {
o.onError(new Error('Sequence contains more than one element'));
} else {
value = x;
seenValue = true;
}
}, function (e) { o.onError(e); }, function () {
if (!seenValue && !hasDefault) {
o.onError(new EmptyError());
} else {
o.onNext(value);
o.onCompleted();
}
});
}, source);
}
/**
* Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence.
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate.
*/
observableProto.single = function (predicate, thisArg) {
return predicate && isFunction(predicate) ?
this.where(predicate, thisArg).single() :
singleOrDefaultAsync(this, false);
};
/**
* Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence.
* @example
* var res = res = source.singleOrDefault();
* var res = res = source.singleOrDefault(function (x) { return x === 42; });
* res = source.singleOrDefault(function (x) { return x === 42; }, 0);
* res = source.singleOrDefault(null, 0);
* @memberOf Observable#
* @param {Function} predicate A predicate function to evaluate for elements in the source sequence.
* @param [defaultValue] The default value if the index is outside the bounds of the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) {
return predicate && isFunction(predicate) ?
this.filter(predicate, thisArg).singleOrDefault(null, defaultValue) :
singleOrDefaultAsync(this, true, defaultValue);
};
function firstOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (o) {
return source.subscribe(function (x) {
o.onNext(x);
o.onCompleted();
}, function (e) { o.onError(e); }, function () {
if (!hasDefault) {
o.onError(new EmptyError());
} else {
o.onNext(defaultValue);
o.onCompleted();
}
});
}, source);
}
/**
* Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence.
* @example
* var res = res = source.first();
* var res = res = source.first(function (x) { return x > 3; });
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence.
*/
observableProto.first = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).first() :
firstOrDefaultAsync(this, false);
};
/**
* Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) {
return predicate ?
this.where(predicate).firstOrDefault(null, defaultValue) :
firstOrDefaultAsync(this, true, defaultValue);
};
function lastOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (o) {
var value = defaultValue, seenValue = false;
return source.subscribe(function (x) {
value = x;
seenValue = true;
}, function (e) { o.onError(e); }, function () {
if (!seenValue && !hasDefault) {
o.onError(new EmptyError());
} else {
o.onNext(value);
o.onCompleted();
}
});
}, source);
}
/**
* Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element.
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate.
*/
observableProto.last = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).last() :
lastOrDefaultAsync(this, false);
};
/**
* Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param [defaultValue] The default value if no such element exists. If not specified, defaults to null.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) {
return predicate ?
this.where(predicate, thisArg).lastOrDefault(null, defaultValue) :
lastOrDefaultAsync(this, true, defaultValue);
};
function findValue (source, predicate, thisArg, yieldIndex) {
var callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0;
return source.subscribe(function (x) {
var shouldRun;
try {
shouldRun = callback(x, i, source);
} catch (e) {
o.onError(e);
return;
}
if (shouldRun) {
o.onNext(yieldIndex ? i : x);
o.onCompleted();
} else {
i++;
}
}, function (e) { o.onError(e); }, function () {
o.onNext(yieldIndex ? -1 : undefined);
o.onCompleted();
});
}, source);
}
/**
* Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence.
* @param {Function} predicate The predicate that defines the conditions of the element to search for.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined.
*/
observableProto.find = function (predicate, thisArg) {
return findValue(this, predicate, thisArg, false);
};
/**
* Searches for an element that matches the conditions defined by the specified predicate, and returns
* an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence.
* @param {Function} predicate The predicate that defines the conditions of the element to search for.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1.
*/
observableProto.findIndex = function (predicate, thisArg) {
return findValue(this, predicate, thisArg, true);
};
/**
* Converts the observable sequence to a Set if it exists.
* @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence.
*/
observableProto.toSet = function () {
if (typeof root.Set === 'undefined') { throw new TypeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var s = new root.Set();
return source.subscribe(
function (x) { s.add(x); },
function (e) { o.onError(e); },
function () {
o.onNext(s);
o.onCompleted();
});
}, source);
};
/**
* Converts the observable sequence to a Map if it exists.
* @param {Function} keySelector A function which produces the key for the Map.
* @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence.
* @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence.
*/
observableProto.toMap = function (keySelector, elementSelector) {
if (typeof root.Map === 'undefined') { throw new TypeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var m = new root.Map();
return source.subscribe(
function (x) {
var key;
try {
key = keySelector(x);
} catch (e) {
o.onError(e);
return;
}
var element = x;
if (elementSelector) {
try {
element = elementSelector(x);
} catch (e) {
o.onError(e);
return;
}
}
m.set(key, element);
},
function (e) { o.onError(e); },
function () {
o.onNext(m);
o.onCompleted();
});
}, source);
};
var fnString = 'function',
throwString = 'throw',
isObject = Rx.internals.isObject;
function toThunk(obj, ctx) {
if (Array.isArray(obj)) { return objectToThunk.call(ctx, obj); }
if (isGeneratorFunction(obj)) { return observableSpawn(obj.call(ctx)); }
if (isGenerator(obj)) { return observableSpawn(obj); }
if (isObservable(obj)) { return observableToThunk(obj); }
if (isPromise(obj)) { return promiseToThunk(obj); }
if (typeof obj === fnString) { return obj; }
if (isObject(obj) || Array.isArray(obj)) { return objectToThunk.call(ctx, obj); }
return obj;
}
function objectToThunk(obj) {
var ctx = this;
return function (done) {
var keys = Object.keys(obj),
pending = keys.length,
results = new obj.constructor(),
finished;
if (!pending) {
timeoutScheduler.schedule(function () { done(null, results); });
return;
}
for (var i = 0, len = keys.length; i < len; i++) {
run(obj[keys[i]], keys[i]);
}
function run(fn, key) {
if (finished) { return; }
try {
fn = toThunk(fn, ctx);
if (typeof fn !== fnString) {
results[key] = fn;
return --pending || done(null, results);
}
fn.call(ctx, function(err, res) {
if (finished) { return; }
if (err) {
finished = true;
return done(err);
}
results[key] = res;
--pending || done(null, results);
});
} catch (e) {
finished = true;
done(e);
}
}
}
}
function observableToThunk(observable) {
return function (fn) {
var value, hasValue = false;
observable.subscribe(
function (v) {
value = v;
hasValue = true;
},
fn,
function () {
hasValue && fn(null, value);
});
}
}
function promiseToThunk(promise) {
return function(fn) {
promise.then(function(res) {
fn(null, res);
}, fn);
}
}
function isObservable(obj) {
return obj && typeof obj.subscribe === fnString;
}
function isGeneratorFunction(obj) {
return obj && obj.constructor && obj.constructor.name === 'GeneratorFunction';
}
function isGenerator(obj) {
return obj && typeof obj.next === fnString && typeof obj[throwString] === fnString;
}
/*
* Spawns a generator function which allows for Promises, Observable sequences, Arrays, Objects, Generators and functions.
* @param {Function} The spawning function.
* @returns {Function} a function which has a done continuation.
*/
var observableSpawn = Rx.spawn = function (fn) {
var isGenFun = isGeneratorFunction(fn);
return function (done) {
var ctx = this,
gen = fn;
if (isGenFun) {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
var len = args.length,
hasCallback = len && typeof args[len - 1] === fnString;
done = hasCallback ? args.pop() : handleError;
gen = fn.apply(this, args);
} else {
done = done || handleError;
}
next();
function exit(err, res) {
timeoutScheduler.schedule(done.bind(ctx, err, res));
}
function next(err, res) {
var ret;
// multiple args
if (arguments.length > 2) {
for(var res = [], i = 1, len = arguments.length; i < len; i++) { res.push(arguments[i]); }
}
if (err) {
try {
ret = gen[throwString](err);
} catch (e) {
return exit(e);
}
}
if (!err) {
try {
ret = gen.next(res);
} catch (e) {
return exit(e);
}
}
if (ret.done) {
return exit(null, ret.value);
}
ret.value = toThunk(ret.value, ctx);
if (typeof ret.value === fnString) {
var called = false;
try {
ret.value.call(ctx, function() {
if (called) {
return;
}
called = true;
next.apply(ctx, arguments);
});
} catch (e) {
timeoutScheduler.schedule(function () {
if (called) {
return;
}
called = true;
next.call(ctx, e);
});
}
return;
}
// Not supported
next(new TypeError('Rx.spawn only supports a function, Promise, Observable, Object or Array.'));
}
}
};
function handleError(err) {
if (!err) { return; }
timeoutScheduler.schedule(function() {
throw err;
});
}
/**
* Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence.
*
* @example
* var res = Rx.Observable.start(function () { console.log('hello'); });
* var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout);
* var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console);
*
* @param {Function} func Function to run asynchronously.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*
* Remarks
* * The function is called immediately, not during the subscription of the resulting sequence.
* * Multiple subscriptions to the resulting sequence can observe the function's result.
*/
Observable.start = function (func, context, scheduler) {
return observableToAsync(func, context, scheduler)();
};
/**
* Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler.
* @param {Function} function Function to convert to an asynchronous function.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @returns {Function} Asynchronous function.
*/
var observableToAsync = Observable.toAsync = function (func, context, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return function () {
var args = arguments,
subject = new AsyncSubject();
scheduler.schedule(function () {
var result;
try {
result = func.apply(context, args);
} catch (e) {
subject.onError(e);
return;
}
subject.onNext(result);
subject.onCompleted();
});
return subject.asObservable();
};
};
/**
* Converts a callback function to an observable sequence.
*
* @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next.
* @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array.
*/
Observable.fromCallback = function (func, context, selector) {
return function () {
var len = arguments.length, args = new Array(len)
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return new AnonymousObservable(function (observer) {
function handler() {
var len = arguments.length, results = new Array(len);
for(var i = 0; i < len; i++) { results[i] = arguments[i]; }
if (selector) {
try {
results = selector.apply(context, results);
} catch (e) {
return observer.onError(e);
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
observer.onNext(results);
}
}
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
}).publishLast().refCount();
};
};
/**
* Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format.
* @param {Function} func The function to call
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next.
* @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array.
*/
Observable.fromNodeCallback = function (func, context, selector) {
return function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return new AnonymousObservable(function (observer) {
function handler(err) {
if (err) {
observer.onError(err);
return;
}
var len = arguments.length, results = [];
for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; }
if (selector) {
try {
results = selector.apply(context, results);
} catch (e) {
return observer.onError(e);
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
observer.onNext(results);
}
}
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
}).publishLast().refCount();
};
};
function createListener (element, name, handler) {
if (element.addEventListener) {
element.addEventListener(name, handler, false);
return disposableCreate(function () {
element.removeEventListener(name, handler, false);
});
}
throw new Error('No listener found');
}
function createEventListener (el, eventName, handler) {
var disposables = new CompositeDisposable();
// Asume NodeList
if (Object.prototype.toString.call(el) === '[object NodeList]') {
for (var i = 0, len = el.length; i < len; i++) {
disposables.add(createEventListener(el.item(i), eventName, handler));
}
} else if (el) {
disposables.add(createListener(el, eventName, handler));
}
return disposables;
}
/**
* Configuration option to determine whether to use native events only
*/
Rx.config.useNativeEvents = false;
/**
* Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList.
*
* @example
* var source = Rx.Observable.fromEvent(element, 'mouseup');
*
* @param {Object} element The DOMElement or NodeList to attach a listener.
* @param {String} eventName The event name to attach the observable sequence.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence of events from the specified element and the specified event.
*/
Observable.fromEvent = function (element, eventName, selector) {
// Node.js specific
if (element.addListener) {
return fromEventPattern(
function (h) { element.addListener(eventName, h); },
function (h) { element.removeListener(eventName, h); },
selector);
}
// Use only if non-native events are allowed
if (!Rx.config.useNativeEvents) {
// Handles jq, Angular.js, Zepto, Marionette, Ember.js
if (typeof element.on === 'function' && typeof element.off === 'function') {
return fromEventPattern(
function (h) { element.on(eventName, h); },
function (h) { element.off(eventName, h); },
selector);
}
}
return new AnonymousObservable(function (observer) {
return createEventListener(
element,
eventName,
function handler (e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
return observer.onError(err);
}
}
observer.onNext(results);
});
}).publish().refCount();
};
/**
* Creates an observable sequence from an event emitter via an addHandler/removeHandler pair.
* @param {Function} addHandler The function to add a handler to the emitter.
* @param {Function} [removeHandler] The optional function to remove a handler from an emitter.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence which wraps an event from an event emitter
*/
var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) {
return new AnonymousObservable(function (observer) {
function innerHandler (e) {
var result = e;
if (selector) {
try {
result = selector(arguments);
} catch (err) {
return observer.onError(err);
}
}
observer.onNext(result);
}
var returnValue = addHandler(innerHandler);
return disposableCreate(function () {
if (removeHandler) {
removeHandler(innerHandler, returnValue);
}
});
}).publish().refCount();
};
/**
* Invokes the asynchronous function, surfacing the result through an observable sequence.
* @param {Function} functionAsync Asynchronous function which returns a Promise to run.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*/
Observable.startAsync = function (functionAsync) {
var promise;
try {
promise = functionAsync();
} catch (e) {
return observableThrow(e);
}
return observableFromPromise(promise);
}
var PausableObservable = (function (__super__) {
inherits(PausableObservable, __super__);
function subscribe(observer) {
var conn = this.source.publish(),
subscription = conn.subscribe(observer),
connection = disposableEmpty;
var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) {
if (b) {
connection = conn.connect();
} else {
connection.dispose();
connection = disposableEmpty;
}
});
return new CompositeDisposable(subscription, connection, pausable);
}
function PausableObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
__super__.call(this, subscribe, source);
}
PausableObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausable(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausable = function (pauser) {
return new PausableObservable(this, pauser);
};
function combineLatestSource(source, subject, resultSelector) {
return new AnonymousObservable(function (o) {
var hasValue = [false, false],
hasValueAll = false,
isDone = false,
values = new Array(2),
err;
function next(x, i) {
values[i] = x
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
if (err) {
o.onError(err);
return;
}
try {
res = resultSelector.apply(null, values);
} catch (ex) {
o.onError(ex);
return;
}
o.onNext(res);
}
if (isDone && values[1]) {
o.onCompleted();
}
}
return new CompositeDisposable(
source.subscribe(
function (x) {
next(x, 0);
},
function (e) {
if (values[1]) {
o.onError(e);
} else {
err = e;
}
},
function () {
isDone = true;
values[1] && o.onCompleted();
}),
subject.subscribe(
function (x) {
next(x, 1);
},
function (e) { o.onError(e); },
function () {
isDone = true;
next(true, 1);
})
);
}, source);
}
var PausableBufferedObservable = (function (__super__) {
inherits(PausableBufferedObservable, __super__);
function subscribe(o) {
var q = [], previousShouldFire;
var subscription =
combineLatestSource(
this.source,
this.pauser.distinctUntilChanged().startWith(false),
function (data, shouldFire) {
return { data: data, shouldFire: shouldFire };
})
.subscribe(
function (results) {
if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) {
previousShouldFire = results.shouldFire;
// change in shouldFire
if (results.shouldFire) {
while (q.length > 0) {
o.onNext(q.shift());
}
}
} else {
previousShouldFire = results.shouldFire;
// new data
if (results.shouldFire) {
o.onNext(results.data);
} else {
q.push(results.data);
}
}
},
function (err) {
// Empty buffer before sending error
while (q.length > 0) {
o.onNext(q.shift());
}
o.onError(err);
},
function () {
// Empty buffer before sending completion
while (q.length > 0) {
o.onNext(q.shift());
}
o.onCompleted();
}
);
return subscription;
}
function PausableBufferedObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
__super__.call(this, subscribe, source);
}
PausableBufferedObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableBufferedObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableBufferedObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false,
* and yields the values that were buffered while paused.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausableBuffered(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausableBuffered = function (subject) {
return new PausableBufferedObservable(this, subject);
};
var ControlledObservable = (function (__super__) {
inherits(ControlledObservable, __super__);
function subscribe (observer) {
return this.source.subscribe(observer);
}
function ControlledObservable (source, enableQueue) {
__super__.call(this, subscribe, source);
this.subject = new ControlledSubject(enableQueue);
this.source = source.multicast(this.subject).refCount();
}
ControlledObservable.prototype.request = function (numberOfItems) {
if (numberOfItems == null) { numberOfItems = -1; }
return this.subject.request(numberOfItems);
};
return ControlledObservable;
}(Observable));
var ControlledSubject = (function (__super__) {
function subscribe (observer) {
return this.subject.subscribe(observer);
}
inherits(ControlledSubject, __super__);
function ControlledSubject(enableQueue) {
enableQueue == null && (enableQueue = true);
__super__.call(this, subscribe);
this.subject = new Subject();
this.enableQueue = enableQueue;
this.queue = enableQueue ? [] : null;
this.requestedCount = 0;
this.requestedDisposable = disposableEmpty;
this.error = null;
this.hasFailed = false;
this.hasCompleted = false;
}
addProperties(ControlledSubject.prototype, Observer, {
onCompleted: function () {
this.hasCompleted = true;
if (!this.enableQueue || this.queue.length === 0)
this.subject.onCompleted();
else
this.queue.push(Rx.Notification.createOnCompleted());
},
onError: function (error) {
this.hasFailed = true;
this.error = error;
if (!this.enableQueue || this.queue.length === 0)
this.subject.onError(error);
else
this.queue.push(Rx.Notification.createOnError(error));
},
onNext: function (value) {
var hasRequested = false;
if (this.requestedCount === 0) {
this.enableQueue && this.queue.push(Rx.Notification.createOnNext(value));
} else {
(this.requestedCount !== -1 && this.requestedCount-- === 0) && this.disposeCurrentRequest();
hasRequested = true;
}
hasRequested && this.subject.onNext(value);
},
_processRequest: function (numberOfItems) {
if (this.enableQueue) {
while ((this.queue.length >= numberOfItems && numberOfItems > 0) ||
(this.queue.length > 0 && this.queue[0].kind !== 'N')) {
var first = this.queue.shift();
first.accept(this.subject);
if (first.kind === 'N') numberOfItems--;
else { this.disposeCurrentRequest(); this.queue = []; }
}
return { numberOfItems : numberOfItems, returnValue: this.queue.length !== 0};
}
//TODO I don't think this is ever necessary, since termination of a sequence without a queue occurs in the onCompletion or onError function
//if (this.hasFailed) {
// this.subject.onError(this.error);
//} else if (this.hasCompleted) {
// this.subject.onCompleted();
//}
return { numberOfItems: numberOfItems, returnValue: false };
},
request: function (number) {
this.disposeCurrentRequest();
var self = this, r = this._processRequest(number);
var number = r.numberOfItems;
if (!r.returnValue) {
this.requestedCount = number;
this.requestedDisposable = disposableCreate(function () {
self.requestedCount = 0;
});
return this.requestedDisposable;
} else {
return disposableEmpty;
}
},
disposeCurrentRequest: function () {
this.requestedDisposable.dispose();
this.requestedDisposable = disposableEmpty;
}
});
return ControlledSubject;
}(Observable));
/**
* Attaches a controller to the observable sequence with the ability to queue.
* @example
* var source = Rx.Observable.interval(100).controlled();
* source.request(3); // Reads 3 values
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.controlled = function (enableQueue) {
if (enableQueue == null) { enableQueue = true; }
return new ControlledObservable(this, enableQueue);
};
var StopAndWaitObservable = (function (__super__) {
function subscribe (observer) {
this.subscription = this.source.subscribe(new StopAndWaitObserver(observer, this, this.subscription));
var self = this;
timeoutScheduler.schedule(function () { self.source.request(1); });
return this.subscription;
}
inherits(StopAndWaitObservable, __super__);
function StopAndWaitObservable (source) {
__super__.call(this, subscribe, source);
this.source = source;
}
var StopAndWaitObserver = (function (__sub__) {
inherits(StopAndWaitObserver, __sub__);
function StopAndWaitObserver (observer, observable, cancel) {
__sub__.call(this);
this.observer = observer;
this.observable = observable;
this.cancel = cancel;
}
var stopAndWaitObserverProto = StopAndWaitObserver.prototype;
stopAndWaitObserverProto.completed = function () {
this.observer.onCompleted();
this.dispose();
};
stopAndWaitObserverProto.error = function (error) {
this.observer.onError(error);
this.dispose();
}
stopAndWaitObserverProto.next = function (value) {
this.observer.onNext(value);
var self = this;
timeoutScheduler.schedule(function () {
self.observable.source.request(1);
});
};
stopAndWaitObserverProto.dispose = function () {
this.observer = null;
if (this.cancel) {
this.cancel.dispose();
this.cancel = null;
}
__sub__.prototype.dispose.call(this);
};
return StopAndWaitObserver;
}(AbstractObserver));
return StopAndWaitObservable;
}(Observable));
/**
* Attaches a stop and wait observable to the current observable.
* @returns {Observable} A stop and wait observable.
*/
ControlledObservable.prototype.stopAndWait = function () {
return new StopAndWaitObservable(this);
};
var WindowedObservable = (function (__super__) {
function subscribe (observer) {
this.subscription = this.source.subscribe(new WindowedObserver(observer, this, this.subscription));
var self = this;
timeoutScheduler.schedule(function () {
self.source.request(self.windowSize);
});
return this.subscription;
}
inherits(WindowedObservable, __super__);
function WindowedObservable(source, windowSize) {
__super__.call(this, subscribe, source);
this.source = source;
this.windowSize = windowSize;
}
var WindowedObserver = (function (__sub__) {
inherits(WindowedObserver, __sub__);
function WindowedObserver(observer, observable, cancel) {
this.observer = observer;
this.observable = observable;
this.cancel = cancel;
this.received = 0;
}
var windowedObserverPrototype = WindowedObserver.prototype;
windowedObserverPrototype.completed = function () {
this.observer.onCompleted();
this.dispose();
};
windowedObserverPrototype.error = function (error) {
this.observer.onError(error);
this.dispose();
};
windowedObserverPrototype.next = function (value) {
this.observer.onNext(value);
this.received = ++this.received % this.observable.windowSize;
if (this.received === 0) {
var self = this;
timeoutScheduler.schedule(function () {
self.observable.source.request(self.observable.windowSize);
});
}
};
windowedObserverPrototype.dispose = function () {
this.observer = null;
if (this.cancel) {
this.cancel.dispose();
this.cancel = null;
}
__sub__.prototype.dispose.call(this);
};
return WindowedObserver;
}(AbstractObserver));
return WindowedObservable;
}(Observable));
/**
* Creates a sliding windowed observable based upon the window size.
* @param {Number} windowSize The number of items in the window
* @returns {Observable} A windowed observable based upon the window size.
*/
ControlledObservable.prototype.windowed = function (windowSize) {
return new WindowedObservable(this, windowSize);
};
/**
* Pipes the existing Observable sequence into a Node.js Stream.
* @param {Stream} dest The destination Node.js stream.
* @returns {Stream} The destination stream.
*/
observableProto.pipe = function (dest) {
var source = this.pausableBuffered();
function onDrain() {
source.resume();
}
dest.addListener('drain', onDrain);
source.subscribe(
function (x) {
!dest.write(String(x)) && source.pause();
},
function (err) {
dest.emit('error', err);
},
function () {
// Hack check because STDIO is not closable
!dest._isStdio && dest.end();
dest.removeListener('drain', onDrain);
});
source.resume();
return dest;
};
/**
* Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each
* subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's
* invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay.
*
* @example
* 1 - res = source.multicast(observable);
* 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; });
*
* @param {Function|Subject} subjectOrSubjectSelector
* Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.
* Or:
* Subject to push source elements into.
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.multicast = function (subjectOrSubjectSelector, selector) {
var source = this;
return typeof subjectOrSubjectSelector === 'function' ?
new AnonymousObservable(function (observer) {
var connectable = source.multicast(subjectOrSubjectSelector());
return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect());
}, source) :
new ConnectableObservable(source, subjectOrSubjectSelector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of Multicast using a regular Subject.
*
* @example
* var resres = source.publish();
* var res = source.publish(function (x) { return x; });
*
* @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publish = function (selector) {
return selector && isFunction(selector) ?
this.multicast(function () { return new Subject(); }, selector) :
this.multicast(new Subject());
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.share = function () {
return this.publish().refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification.
* This operator is a specialization of Multicast using a AsyncSubject.
*
* @example
* var res = source.publishLast();
* var res = source.publishLast(function (x) { return x; });
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishLast = function (selector) {
return selector && isFunction(selector) ?
this.multicast(function () { return new AsyncSubject(); }, selector) :
this.multicast(new AsyncSubject());
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue.
* This operator is a specialization of Multicast using a BehaviorSubject.
*
* @example
* var res = source.publishValue(42);
* var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42);
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishValue = function (initialValueOrSelector, initialValue) {
return arguments.length === 2 ?
this.multicast(function () {
return new BehaviorSubject(initialValue);
}, initialValueOrSelector) :
this.multicast(new BehaviorSubject(initialValueOrSelector));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue.
* This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareValue = function (initialValue) {
return this.publishValue(initialValue).refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of Multicast using a ReplaySubject.
*
* @example
* var res = source.replay(null, 3);
* var res = source.replay(null, 3, 500);
* var res = source.replay(null, 3, 500, scheduler);
* var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler);
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy.
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param windowSize [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.replay = function (selector, bufferSize, windowSize, scheduler) {
return selector && isFunction(selector) ?
this.multicast(function () { return new ReplaySubject(bufferSize, windowSize, scheduler); }, selector) :
this.multicast(new ReplaySubject(bufferSize, windowSize, scheduler));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.shareReplay(3);
* var res = source.shareReplay(3, 500);
* var res = source.shareReplay(3, 500, scheduler);
*
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareReplay = function (bufferSize, windowSize, scheduler) {
return this.replay(null, bufferSize, windowSize, scheduler).refCount();
};
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents a value that changes over time.
* Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
*/
var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
observer.onNext(this.value);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(BehaviorSubject, __super__);
/**
* Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value.
* @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet.
*/
function BehaviorSubject(value) {
__super__.call(this, subscribe);
this.value = value,
this.observers = [],
this.isDisposed = false,
this.isStopped = false,
this.hasError = false;
}
addProperties(BehaviorSubject.prototype, Observer, {
/**
* Gets the current value or throws an exception.
* Value is frozen after onCompleted is called.
* After onError is called always throws the specified exception.
* An exception is always thrown after dispose is called.
* @returns {Mixed} The initial value passed to the constructor until onNext is called; after which, the last value passed to onNext.
*/
getValue: function () {
checkDisposed(this);
if (this.hasError) {
throw this.error;
}
return this.value;
},
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () { return this.observers.length > 0; },
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
this.hasError = true;
this.error = error;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
this.value = value;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onNext(value);
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.value = null;
this.exception = null;
}
});
return BehaviorSubject;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
*/
var ReplaySubject = Rx.ReplaySubject = (function (__super__) {
var maxSafeInteger = Math.pow(2, 53) - 1;
function createRemovableDisposable(subject, observer) {
return disposableCreate(function () {
observer.dispose();
!subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1);
});
}
function subscribe(observer) {
var so = new ScheduledObserver(this.scheduler, observer),
subscription = createRemovableDisposable(this, so);
checkDisposed(this);
this._trim(this.scheduler.now());
this.observers.push(so);
for (var i = 0, len = this.q.length; i < len; i++) {
so.onNext(this.q[i].value);
}
if (this.hasError) {
so.onError(this.error);
} else if (this.isStopped) {
so.onCompleted();
}
so.ensureActive();
return subscription;
}
inherits(ReplaySubject, __super__);
/**
* Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler.
* @param {Number} [bufferSize] Maximum element count of the replay buffer.
* @param {Number} [windowSize] Maximum time length of the replay buffer.
* @param {Scheduler} [scheduler] Scheduler the observers are invoked on.
*/
function ReplaySubject(bufferSize, windowSize, scheduler) {
this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize;
this.windowSize = windowSize == null ? maxSafeInteger : windowSize;
this.scheduler = scheduler || currentThreadScheduler;
this.q = [];
this.observers = [];
this.isStopped = false;
this.isDisposed = false;
this.hasError = false;
this.error = null;
__super__.call(this, subscribe);
}
addProperties(ReplaySubject.prototype, Observer.prototype, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
_trim: function (now) {
while (this.q.length > this.bufferSize) {
this.q.shift();
}
while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) {
this.q.shift();
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
var now = this.scheduler.now();
this.q.push({ interval: now, value: value });
this._trim(now);
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
var observer = os[i];
observer.onNext(value);
observer.ensureActive();
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
this.error = error;
this.hasError = true;
var now = this.scheduler.now();
this._trim(now);
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
var observer = os[i];
observer.onError(error);
observer.ensureActive();
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
var now = this.scheduler.now();
this._trim(now);
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
var observer = os[i];
observer.onCompleted();
observer.ensureActive();
}
this.observers.length = 0;
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
return ReplaySubject;
}(Observable));
var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) {
inherits(ConnectableObservable, __super__);
function ConnectableObservable(source, subject) {
var hasSubscription = false,
subscription,
sourceObservable = source.asObservable();
this.connect = function () {
if (!hasSubscription) {
hasSubscription = true;
subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () {
hasSubscription = false;
}));
}
return subscription;
};
__super__.call(this, function (o) { return subject.subscribe(o); });
}
ConnectableObservable.prototype.refCount = function () {
var connectableSubscription, count = 0, source = this;
return new AnonymousObservable(function (observer) {
var shouldConnect = ++count === 1,
subscription = source.subscribe(observer);
shouldConnect && (connectableSubscription = source.connect());
return function () {
subscription.dispose();
--count === 0 && connectableSubscription.dispose();
};
});
};
return ConnectableObservable;
}(Observable));
var Dictionary = (function () {
var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647],
noSuchkey = "no such key",
duplicatekey = "duplicate key";
function isPrime(candidate) {
if ((candidate & 1) === 0) { return candidate === 2; }
var num1 = Math.sqrt(candidate),
num2 = 3;
while (num2 <= num1) {
if (candidate % num2 === 0) { return false; }
num2 += 2;
}
return true;
}
function getPrime(min) {
var index, num, candidate;
for (index = 0; index < primes.length; ++index) {
num = primes[index];
if (num >= min) { return num; }
}
candidate = min | 1;
while (candidate < primes[primes.length - 1]) {
if (isPrime(candidate)) { return candidate; }
candidate += 2;
}
return min;
}
function stringHashFn(str) {
var hash = 757602046;
if (!str.length) { return hash; }
for (var i = 0, len = str.length; i < len; i++) {
var character = str.charCodeAt(i);
hash = ((hash << 5) - hash) + character;
hash = hash & hash;
}
return hash;
}
function numberHashFn(key) {
var c2 = 0x27d4eb2d;
key = (key ^ 61) ^ (key >>> 16);
key = key + (key << 3);
key = key ^ (key >>> 4);
key = key * c2;
key = key ^ (key >>> 15);
return key;
}
var getHashCode = (function () {
var uniqueIdCounter = 0;
return function (obj) {
if (obj == null) { throw new Error(noSuchkey); }
// Check for built-ins before tacking on our own for any object
if (typeof obj === 'string') { return stringHashFn(obj); }
if (typeof obj === 'number') { return numberHashFn(obj); }
if (typeof obj === 'boolean') { return obj === true ? 1 : 0; }
if (obj instanceof Date) { return numberHashFn(obj.valueOf()); }
if (obj instanceof RegExp) { return stringHashFn(obj.toString()); }
if (typeof obj.valueOf === 'function') {
// Hack check for valueOf
var valueOf = obj.valueOf();
if (typeof valueOf === 'number') { return numberHashFn(valueOf); }
if (typeof valueOf === 'string') { return stringHashFn(valueOf); }
}
if (obj.hashCode) { return obj.hashCode(); }
var id = 17 * uniqueIdCounter++;
obj.hashCode = function () { return id; };
return id;
};
}());
function newEntry() {
return { key: null, value: null, next: 0, hashCode: 0 };
}
function Dictionary(capacity, comparer) {
if (capacity < 0) { throw new ArgumentOutOfRangeError(); }
if (capacity > 0) { this._initialize(capacity); }
this.comparer = comparer || defaultComparer;
this.freeCount = 0;
this.size = 0;
this.freeList = -1;
}
var dictionaryProto = Dictionary.prototype;
dictionaryProto._initialize = function (capacity) {
var prime = getPrime(capacity), i;
this.buckets = new Array(prime);
this.entries = new Array(prime);
for (i = 0; i < prime; i++) {
this.buckets[i] = -1;
this.entries[i] = newEntry();
}
this.freeList = -1;
};
dictionaryProto.add = function (key, value) {
this._insert(key, value, true);
};
dictionaryProto._insert = function (key, value, add) {
if (!this.buckets) { this._initialize(0); }
var index3,
num = getHashCode(key) & 2147483647,
index1 = num % this.buckets.length;
for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) {
if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) {
if (add) { throw new Error(duplicatekey); }
this.entries[index2].value = value;
return;
}
}
if (this.freeCount > 0) {
index3 = this.freeList;
this.freeList = this.entries[index3].next;
--this.freeCount;
} else {
if (this.size === this.entries.length) {
this._resize();
index1 = num % this.buckets.length;
}
index3 = this.size;
++this.size;
}
this.entries[index3].hashCode = num;
this.entries[index3].next = this.buckets[index1];
this.entries[index3].key = key;
this.entries[index3].value = value;
this.buckets[index1] = index3;
};
dictionaryProto._resize = function () {
var prime = getPrime(this.size * 2),
numArray = new Array(prime);
for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; }
var entryArray = new Array(prime);
for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; }
for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); }
for (var index1 = 0; index1 < this.size; ++index1) {
var index2 = entryArray[index1].hashCode % prime;
entryArray[index1].next = numArray[index2];
numArray[index2] = index1;
}
this.buckets = numArray;
this.entries = entryArray;
};
dictionaryProto.remove = function (key) {
if (this.buckets) {
var num = getHashCode(key) & 2147483647,
index1 = num % this.buckets.length,
index2 = -1;
for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) {
if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) {
if (index2 < 0) {
this.buckets[index1] = this.entries[index3].next;
} else {
this.entries[index2].next = this.entries[index3].next;
}
this.entries[index3].hashCode = -1;
this.entries[index3].next = this.freeList;
this.entries[index3].key = null;
this.entries[index3].value = null;
this.freeList = index3;
++this.freeCount;
return true;
} else {
index2 = index3;
}
}
}
return false;
};
dictionaryProto.clear = function () {
var index, len;
if (this.size <= 0) { return; }
for (index = 0, len = this.buckets.length; index < len; ++index) {
this.buckets[index] = -1;
}
for (index = 0; index < this.size; ++index) {
this.entries[index] = newEntry();
}
this.freeList = -1;
this.size = 0;
};
dictionaryProto._findEntry = function (key) {
if (this.buckets) {
var num = getHashCode(key) & 2147483647;
for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) {
if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) {
return index;
}
}
}
return -1;
};
dictionaryProto.count = function () {
return this.size - this.freeCount;
};
dictionaryProto.tryGetValue = function (key) {
var entry = this._findEntry(key);
return entry >= 0 ?
this.entries[entry].value :
undefined;
};
dictionaryProto.getValues = function () {
var index = 0, results = [];
if (this.entries) {
for (var index1 = 0; index1 < this.size; index1++) {
if (this.entries[index1].hashCode >= 0) {
results[index++] = this.entries[index1].value;
}
}
}
return results;
};
dictionaryProto.get = function (key) {
var entry = this._findEntry(key);
if (entry >= 0) { return this.entries[entry].value; }
throw new Error(noSuchkey);
};
dictionaryProto.set = function (key, value) {
this._insert(key, value, false);
};
dictionaryProto.containskey = function (key) {
return this._findEntry(key) >= 0;
};
return Dictionary;
}());
/**
* Correlates the elements of two sequences based on overlapping durations.
*
* @param {Observable} right The right observable sequence to join elements for.
* @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
* @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
* @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs.
* @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
*/
observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
var left = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable();
var leftDone = false, rightDone = false;
var leftId = 0, rightId = 0;
var leftMap = new Dictionary(), rightMap = new Dictionary();
group.add(left.subscribe(
function (value) {
var id = leftId++;
var md = new SingleAssignmentDisposable();
leftMap.add(id, value);
group.add(md);
var expire = function () {
leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted();
group.remove(md);
};
var duration;
try {
duration = leftDurationSelector(value);
} catch (e) {
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire));
rightMap.getValues().forEach(function (v) {
var result;
try {
result = resultSelector(value, v);
} catch (exn) {
observer.onError(exn);
return;
}
observer.onNext(result);
});
},
observer.onError.bind(observer),
function () {
leftDone = true;
(rightDone || leftMap.count() === 0) && observer.onCompleted();
})
);
group.add(right.subscribe(
function (value) {
var id = rightId++;
var md = new SingleAssignmentDisposable();
rightMap.add(id, value);
group.add(md);
var expire = function () {
rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted();
group.remove(md);
};
var duration;
try {
duration = rightDurationSelector(value);
} catch (e) {
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire));
leftMap.getValues().forEach(function (v) {
var result;
try {
result = resultSelector(v, value);
} catch (exn) {
observer.onError(exn);
return;
}
observer.onNext(result);
});
},
observer.onError.bind(observer),
function () {
rightDone = true;
(leftDone || rightMap.count() === 0) && observer.onCompleted();
})
);
return group;
}, left);
};
/**
* Correlates the elements of two sequences based on overlapping durations, and groups the results.
*
* @param {Observable} right The right observable sequence to join elements for.
* @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
* @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
* @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element.
* @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
*/
observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
var left = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable();
var r = new RefCountDisposable(group);
var leftMap = new Dictionary(), rightMap = new Dictionary();
var leftId = 0, rightId = 0;
function handleError(e) { return function (v) { v.onError(e); }; };
group.add(left.subscribe(
function (value) {
var s = new Subject();
var id = leftId++;
leftMap.add(id, s);
var result;
try {
result = resultSelector(value, addRef(s, r));
} catch (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
observer.onNext(result);
rightMap.getValues().forEach(function (v) { s.onNext(v); });
var md = new SingleAssignmentDisposable();
group.add(md);
var expire = function () {
leftMap.remove(id) && s.onCompleted();
group.remove(md);
};
var duration;
try {
duration = leftDurationSelector(value);
} catch (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(
noop,
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
},
expire)
);
},
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
},
observer.onCompleted.bind(observer))
);
group.add(right.subscribe(
function (value) {
var id = rightId++;
rightMap.add(id, value);
var md = new SingleAssignmentDisposable();
group.add(md);
var expire = function () {
rightMap.remove(id);
group.remove(md);
};
var duration;
try {
duration = rightDurationSelector(value);
} catch (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(
noop,
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
},
expire)
);
leftMap.getValues().forEach(function (v) { v.onNext(value); });
},
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
})
);
return r;
}, left);
};
/**
* Projects each element of an observable sequence into zero or more buffers.
*
* @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
* @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) {
return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); });
};
/**
* Projects each element of an observable sequence into zero or more windows.
*
* @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
* @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) {
if (arguments.length === 1 && typeof arguments[0] !== 'function') {
return observableWindowWithBoundaries.call(this, windowOpeningsOrClosingSelector);
}
return typeof windowOpeningsOrClosingSelector === 'function' ?
observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) :
observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector);
};
function observableWindowWithOpenings(windowOpenings, windowClosingSelector) {
return windowOpenings.groupJoin(this, windowClosingSelector, observableEmpty, function (_, win) {
return win;
});
}
function observableWindowWithBoundaries(windowBoundaries) {
var source = this;
return new AnonymousObservable(function (observer) {
var win = new Subject(),
d = new CompositeDisposable(),
r = new RefCountDisposable(d);
observer.onNext(addRef(win, r));
d.add(source.subscribe(function (x) {
win.onNext(x);
}, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
observer.onCompleted();
}));
isPromise(windowBoundaries) && (windowBoundaries = observableFromPromise(windowBoundaries));
d.add(windowBoundaries.subscribe(function (w) {
win.onCompleted();
win = new Subject();
observer.onNext(addRef(win, r));
}, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
observer.onCompleted();
}));
return r;
}, source);
}
function observableWindowWithClosingSelector(windowClosingSelector) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new SerialDisposable(),
d = new CompositeDisposable(m),
r = new RefCountDisposable(d),
win = new Subject();
observer.onNext(addRef(win, r));
d.add(source.subscribe(function (x) {
win.onNext(x);
}, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
observer.onCompleted();
}));
function createWindowClose () {
var windowClose;
try {
windowClose = windowClosingSelector();
} catch (e) {
observer.onError(e);
return;
}
isPromise(windowClose) && (windowClose = observableFromPromise(windowClose));
var m1 = new SingleAssignmentDisposable();
m.setDisposable(m1);
m1.setDisposable(windowClose.take(1).subscribe(noop, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
win = new Subject();
observer.onNext(addRef(win, r));
createWindowClose();
}));
}
createWindowClose();
return r;
}, source);
}
/**
* Returns a new observable that triggers on the second and subsequent triggerings of the input observable.
* The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair.
* The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs.
* @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array.
*/
observableProto.pairwise = function () {
var source = this;
return new AnonymousObservable(function (observer) {
var previous, hasPrevious = false;
return source.subscribe(
function (x) {
if (hasPrevious) {
observer.onNext([previous, x]);
} else {
hasPrevious = true;
}
previous = x;
},
observer.onError.bind(observer),
observer.onCompleted.bind(observer));
}, source);
};
/**
* Returns two observables which partition the observations of the source by the given function.
* The first will trigger observations for those values for which the predicate returns true.
* The second will trigger observations for those values where the predicate returns false.
* The predicate is executed once for each subscribed observer.
* Both also propagate all error observations arising from the source and each completes
* when the source completes.
* @param {Function} predicate
* The function to determine which output Observable will trigger a particular observation.
* @returns {Array}
* An array of observables. The first triggers when the predicate returns true,
* and the second triggers when the predicate returns false.
*/
observableProto.partition = function(predicate, thisArg) {
return [
this.filter(predicate, thisArg),
this.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); })
];
};
function enumerableWhile(condition, source) {
return new Enumerable(function () {
return new Enumerator(function () {
return condition() ?
{ done: false, value: source } :
{ done: true, value: undefined };
});
});
}
/**
* Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions.
* This operator allows for a fluent style of writing queries that use the same sequence multiple times.
*
* @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.letBind = observableProto['let'] = function (func) {
return func(this);
};
/**
* Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9
*
* @example
* 1 - res = Rx.Observable.if(condition, obs1);
* 2 - res = Rx.Observable.if(condition, obs1, obs2);
* 3 - res = Rx.Observable.if(condition, obs1, scheduler);
* @param {Function} condition The condition which determines if the thenSource or elseSource will be run.
* @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true.
* @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler.
* @returns {Observable} An observable sequence which is either the thenSource or elseSource.
*/
Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) {
return observableDefer(function () {
elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty());
isPromise(thenSource) && (thenSource = observableFromPromise(thenSource));
isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler));
// Assume a scheduler for empty only
typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler));
return condition() ? thenSource : elseSourceOrScheduler;
});
};
/**
* Concatenates the observable sequences obtained by running the specified result selector for each element in source.
* There is an alias for this method called 'forIn' for browsers <IE9
* @param {Array} sources An array of values to turn into an observable sequence.
* @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence.
* @returns {Observable} An observable sequence from the concatenated observable sequences.
*/
Observable['for'] = Observable.forIn = function (sources, resultSelector, thisArg) {
return enumerableOf(sources, resultSelector, thisArg).concat();
};
/**
* Repeats source as long as condition holds emulating a while loop.
* There is an alias for this method called 'whileDo' for browsers <IE9
*
* @param {Function} condition The condition which determines if the source will be repeated.
* @param {Observable} source The observable sequence that will be run if the condition function returns true.
* @returns {Observable} An observable sequence which is repeated as long as the condition holds.
*/
var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) {
isPromise(source) && (source = observableFromPromise(source));
return enumerableWhile(condition, source).concat();
};
/**
* Repeats source as long as condition holds emulating a do while loop.
*
* @param {Function} condition The condition which determines if the source will be repeated.
* @param {Observable} source The observable sequence that will be run if the condition function returns true.
* @returns {Observable} An observable sequence which is repeated as long as the condition holds.
*/
observableProto.doWhile = function (condition) {
return observableConcat([this, observableWhileDo(condition, this)]);
};
/**
* Uses selector to determine which source in sources to use.
* There is an alias 'switchCase' for browsers <IE9.
*
* @example
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 });
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0);
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler);
*
* @param {Function} selector The function which extracts the value for to test in a case statement.
* @param {Array} sources A object which has keys which correspond to the case statement labels.
* @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler.
*
* @returns {Observable} An observable sequence which is determined by a case statement.
*/
Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) {
return observableDefer(function () {
isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler));
defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty());
typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler));
var result = sources[selector()];
isPromise(result) && (result = observableFromPromise(result));
return result || defaultSourceOrScheduler;
});
};
/**
* Expands an observable sequence by recursively invoking selector.
*
* @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again.
* @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler.
* @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion.
*/
observableProto.expand = function (selector, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var q = [],
m = new SerialDisposable(),
d = new CompositeDisposable(m),
activeCount = 0,
isAcquired = false;
var ensureActive = function () {
var isOwner = false;
if (q.length > 0) {
isOwner = !isAcquired;
isAcquired = true;
}
if (isOwner) {
m.setDisposable(scheduler.scheduleRecursive(function (self) {
var work;
if (q.length > 0) {
work = q.shift();
} else {
isAcquired = false;
return;
}
var m1 = new SingleAssignmentDisposable();
d.add(m1);
m1.setDisposable(work.subscribe(function (x) {
observer.onNext(x);
var result = null;
try {
result = selector(x);
} catch (e) {
observer.onError(e);
}
q.push(result);
activeCount++;
ensureActive();
}, observer.onError.bind(observer), function () {
d.remove(m1);
activeCount--;
if (activeCount === 0) {
observer.onCompleted();
}
}));
self();
}));
}
};
q.push(source);
activeCount++;
ensureActive();
return d;
}, this);
};
/**
* Runs all observable sequences in parallel and collect their last elements.
*
* @example
* 1 - res = Rx.Observable.forkJoin([obs1, obs2]);
* 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...);
* @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences.
*/
Observable.forkJoin = function () {
var allSources = [];
if (Array.isArray(arguments[0])) {
allSources = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { allSources.push(arguments[i]); }
}
return new AnonymousObservable(function (subscriber) {
var count = allSources.length;
if (count === 0) {
subscriber.onCompleted();
return disposableEmpty;
}
var group = new CompositeDisposable(),
finished = false,
hasResults = new Array(count),
hasCompleted = new Array(count),
results = new Array(count);
for (var idx = 0; idx < count; idx++) {
(function (i) {
var source = allSources[i];
isPromise(source) && (source = observableFromPromise(source));
group.add(
source.subscribe(
function (value) {
if (!finished) {
hasResults[i] = true;
results[i] = value;
}
},
function (e) {
finished = true;
subscriber.onError(e);
group.dispose();
},
function () {
if (!finished) {
if (!hasResults[i]) {
subscriber.onCompleted();
return;
}
hasCompleted[i] = true;
for (var ix = 0; ix < count; ix++) {
if (!hasCompleted[ix]) { return; }
}
finished = true;
subscriber.onNext(results);
subscriber.onCompleted();
}
}));
})(idx);
}
return group;
});
};
/**
* Runs two observable sequences in parallel and combines their last elemenets.
*
* @param {Observable} second Second observable sequence.
* @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences.
* @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences.
*/
observableProto.forkJoin = function (second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var leftStopped = false, rightStopped = false,
hasLeft = false, hasRight = false,
lastLeft, lastRight,
leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable();
isPromise(second) && (second = observableFromPromise(second));
leftSubscription.setDisposable(
first.subscribe(function (left) {
hasLeft = true;
lastLeft = left;
}, function (err) {
rightSubscription.dispose();
observer.onError(err);
}, function () {
leftStopped = true;
if (rightStopped) {
if (!hasLeft) {
observer.onCompleted();
} else if (!hasRight) {
observer.onCompleted();
} else {
var result;
try {
result = resultSelector(lastLeft, lastRight);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
observer.onCompleted();
}
}
})
);
rightSubscription.setDisposable(
second.subscribe(function (right) {
hasRight = true;
lastRight = right;
}, function (err) {
leftSubscription.dispose();
observer.onError(err);
}, function () {
rightStopped = true;
if (leftStopped) {
if (!hasLeft) {
observer.onCompleted();
} else if (!hasRight) {
observer.onCompleted();
} else {
var result;
try {
result = resultSelector(lastLeft, lastRight);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
observer.onCompleted();
}
}
})
);
return new CompositeDisposable(leftSubscription, rightSubscription);
}, first);
};
/**
* Comonadic bind operator.
* @param {Function} selector A transform function to apply to each element.
* @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler.
* @returns {Observable} An observable sequence which results from the comonadic bind operation.
*/
observableProto.manySelect = function (selector, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
var source = this;
return observableDefer(function () {
var chain;
return source
.map(function (x) {
var curr = new ChainObservable(x);
chain && chain.onNext(x);
chain = curr;
return curr;
})
.tap(
noop,
function (e) { chain && chain.onError(e); },
function () { chain && chain.onCompleted(); }
)
.observeOn(scheduler)
.map(selector);
}, source);
};
var ChainObservable = (function (__super__) {
function subscribe (observer) {
var self = this, g = new CompositeDisposable();
g.add(currentThreadScheduler.schedule(function () {
observer.onNext(self.head);
g.add(self.tail.mergeAll().subscribe(observer));
}));
return g;
}
inherits(ChainObservable, __super__);
function ChainObservable(head) {
__super__.call(this, subscribe);
this.head = head;
this.tail = new AsyncSubject();
}
addProperties(ChainObservable.prototype, Observer, {
onCompleted: function () {
this.onNext(Observable.empty());
},
onError: function (e) {
this.onNext(Observable.throwError(e));
},
onNext: function (v) {
this.tail.onNext(v);
this.tail.onCompleted();
}
});
return ChainObservable;
}(Observable));
/** @private */
var Map = root.Map || (function () {
function Map() {
this._keys = [];
this._values = [];
}
Map.prototype.get = function (key) {
var i = this._keys.indexOf(key);
return i !== -1 ? this._values[i] : undefined;
};
Map.prototype.set = function (key, value) {
var i = this._keys.indexOf(key);
i !== -1 && (this._values[i] = value);
this._values[this._keys.push(key) - 1] = value;
};
Map.prototype.forEach = function (callback, thisArg) {
for (var i = 0, len = this._keys.length; i < len; i++) {
callback.call(thisArg, this._values[i], this._keys[i]);
}
};
return Map;
}());
/**
* @constructor
* Represents a join pattern over observable sequences.
*/
function Pattern(patterns) {
this.patterns = patterns;
}
/**
* Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value.
* @param other Observable sequence to match in addition to the current pattern.
* @return {Pattern} Pattern object that matches when all observable sequences in the pattern have an available value.
*/
Pattern.prototype.and = function (other) {
return new Pattern(this.patterns.concat(other));
};
/**
* Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values.
* @param {Function} selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern.
* @return {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator.
*/
Pattern.prototype.thenDo = function (selector) {
return new Plan(this, selector);
};
function Plan(expression, selector) {
this.expression = expression;
this.selector = selector;
}
Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) {
var self = this;
var joinObservers = [];
for (var i = 0, len = this.expression.patterns.length; i < len; i++) {
joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer)));
}
var activePlan = new ActivePlan(joinObservers, function () {
var result;
try {
result = self.selector.apply(self, arguments);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
}, function () {
for (var j = 0, jlen = joinObservers.length; j < jlen; j++) {
joinObservers[j].removeActivePlan(activePlan);
}
deactivate(activePlan);
});
for (i = 0, len = joinObservers.length; i < len; i++) {
joinObservers[i].addActivePlan(activePlan);
}
return activePlan;
};
function planCreateObserver(externalSubscriptions, observable, onError) {
var entry = externalSubscriptions.get(observable);
if (!entry) {
var observer = new JoinObserver(observable, onError);
externalSubscriptions.set(observable, observer);
return observer;
}
return entry;
}
function ActivePlan(joinObserverArray, onNext, onCompleted) {
this.joinObserverArray = joinObserverArray;
this.onNext = onNext;
this.onCompleted = onCompleted;
this.joinObservers = new Map();
for (var i = 0, len = this.joinObserverArray.length; i < len; i++) {
var joinObserver = this.joinObserverArray[i];
this.joinObservers.set(joinObserver, joinObserver);
}
}
ActivePlan.prototype.dequeue = function () {
this.joinObservers.forEach(function (v) { v.queue.shift(); });
};
ActivePlan.prototype.match = function () {
var i, len, hasValues = true;
for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
if (this.joinObserverArray[i].queue.length === 0) {
hasValues = false;
break;
}
}
if (hasValues) {
var firstValues = [],
isCompleted = false;
for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
firstValues.push(this.joinObserverArray[i].queue[0]);
this.joinObserverArray[i].queue[0].kind === 'C' && (isCompleted = true);
}
if (isCompleted) {
this.onCompleted();
} else {
this.dequeue();
var values = [];
for (i = 0, len = firstValues.length; i < firstValues.length; i++) {
values.push(firstValues[i].value);
}
this.onNext.apply(this, values);
}
}
};
var JoinObserver = (function (__super__) {
inherits(JoinObserver, __super__);
function JoinObserver(source, onError) {
__super__.call(this);
this.source = source;
this.onError = onError;
this.queue = [];
this.activePlans = [];
this.subscription = new SingleAssignmentDisposable();
this.isDisposed = false;
}
var JoinObserverPrototype = JoinObserver.prototype;
JoinObserverPrototype.next = function (notification) {
if (!this.isDisposed) {
if (notification.kind === 'E') {
return this.onError(notification.exception);
}
this.queue.push(notification);
var activePlans = this.activePlans.slice(0);
for (var i = 0, len = activePlans.length; i < len; i++) {
activePlans[i].match();
}
}
};
JoinObserverPrototype.error = noop;
JoinObserverPrototype.completed = noop;
JoinObserverPrototype.addActivePlan = function (activePlan) {
this.activePlans.push(activePlan);
};
JoinObserverPrototype.subscribe = function () {
this.subscription.setDisposable(this.source.materialize().subscribe(this));
};
JoinObserverPrototype.removeActivePlan = function (activePlan) {
this.activePlans.splice(this.activePlans.indexOf(activePlan), 1);
this.activePlans.length === 0 && this.dispose();
};
JoinObserverPrototype.dispose = function () {
__super__.prototype.dispose.call(this);
if (!this.isDisposed) {
this.isDisposed = true;
this.subscription.dispose();
}
};
return JoinObserver;
} (AbstractObserver));
/**
* Creates a pattern that matches when both observable sequences have an available value.
*
* @param right Observable sequence to match with the current sequence.
* @return {Pattern} Pattern object that matches when both observable sequences have an available value.
*/
observableProto.and = function (right) {
return new Pattern([this, right]);
};
/**
* Matches when the observable sequence has an available value and projects the value.
*
* @param {Function} selector Selector that will be invoked for values in the source sequence.
* @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator.
*/
observableProto.thenDo = function (selector) {
return new Pattern([this]).thenDo(selector);
};
/**
* Joins together the results from several patterns.
*
* @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns.
* @returns {Observable} Observable sequence with the results form matching several patterns.
*/
Observable.when = function () {
var len = arguments.length, plans;
if (Array.isArray(arguments[0])) {
plans = arguments[0];
} else {
plans = new Array(len);
for(var i = 0; i < len; i++) { plans[i] = arguments[i]; }
}
return new AnonymousObservable(function (o) {
var activePlans = [],
externalSubscriptions = new Map();
var outObserver = observerCreate(
function (x) { o.onNext(x); },
function (err) {
externalSubscriptions.forEach(function (v) { v.onError(err); });
o.onError(err);
},
function (x) { o.onCompleted(); }
);
try {
for (var i = 0, len = plans.length; i < len; i++) {
activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) {
var idx = activePlans.indexOf(activePlan);
activePlans.splice(idx, 1);
activePlans.length === 0 && o.onCompleted();
}));
}
} catch (e) {
observableThrow(e).subscribe(o);
}
var group = new CompositeDisposable();
externalSubscriptions.forEach(function (joinObserver) {
joinObserver.subscribe();
group.add(joinObserver);
});
return group;
});
};
function observableTimerDate(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithAbsolute(dueTime, function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerDateAndPeriod(dueTime, period, scheduler) {
return new AnonymousObservable(function (observer) {
var d = dueTime, p = normalizeTime(period);
return scheduler.scheduleRecursiveWithAbsoluteAndState(0, d, function (count, self) {
if (p > 0) {
var now = scheduler.now();
d = d + p;
d <= now && (d = now + p);
}
observer.onNext(count);
self(count + 1, d);
});
});
}
function observableTimerTimeSpan(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) {
return dueTime === period ?
new AnonymousObservable(function (observer) {
return scheduler.schedulePeriodicWithState(0, period, function (count) {
observer.onNext(count);
return count + 1;
});
}) :
observableDefer(function () {
return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler);
});
}
/**
* Returns an observable sequence that produces a value after each period.
*
* @example
* 1 - res = Rx.Observable.interval(1000);
* 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout);
*
* @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used.
* @returns {Observable} An observable sequence that produces a value after each period.
*/
var observableinterval = Observable.interval = function (period, scheduler) {
return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler);
};
/**
* Returns an observable sequence that produces a value after dueTime has elapsed and then after each period.
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value.
* @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period.
*/
var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) {
var period;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') {
period = periodOrScheduler;
} else if (isScheduler(periodOrScheduler)) {
scheduler = periodOrScheduler;
}
if (dueTime instanceof Date && period === undefined) {
return observableTimerDate(dueTime.getTime(), scheduler);
}
if (dueTime instanceof Date && period !== undefined) {
period = periodOrScheduler;
return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler);
}
return period === undefined ?
observableTimerTimeSpan(dueTime, scheduler) :
observableTimerTimeSpanAndPeriod(dueTime, period, scheduler);
};
function observableDelayTimeSpan(source, dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
var active = false,
cancelable = new SerialDisposable(),
exception = null,
q = [],
running = false,
subscription;
subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) {
var d, shouldRun;
if (notification.value.kind === 'E') {
q = [];
q.push(notification);
exception = notification.value.exception;
shouldRun = !running;
} else {
q.push({ value: notification.value, timestamp: notification.timestamp + dueTime });
shouldRun = !active;
active = true;
}
if (shouldRun) {
if (exception !== null) {
observer.onError(exception);
} else {
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) {
var e, recurseDueTime, result, shouldRecurse;
if (exception !== null) {
return;
}
running = true;
do {
result = null;
if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) {
result = q.shift().value;
}
if (result !== null) {
result.accept(observer);
}
} while (result !== null);
shouldRecurse = false;
recurseDueTime = 0;
if (q.length > 0) {
shouldRecurse = true;
recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now());
} else {
active = false;
}
e = exception;
running = false;
if (e !== null) {
observer.onError(e);
} else if (shouldRecurse) {
self(recurseDueTime);
}
}));
}
}
});
return new CompositeDisposable(subscription, cancelable);
}, source);
}
function observableDelayDate(source, dueTime, scheduler) {
return observableDefer(function () {
return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler);
});
}
/**
* Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved.
*
* @example
* 1 - res = Rx.Observable.delay(new Date());
* 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout);
*
* 3 - res = Rx.Observable.delay(5000);
* 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout);
* @memberOf Observable#
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence.
* @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delay = function (dueTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return dueTime instanceof Date ?
observableDelayDate(this, dueTime.getTime(), scheduler) :
observableDelayTimeSpan(this, dueTime, scheduler);
};
/**
* Ignores values from an observable sequence which are followed by another value before dueTime.
* @param {Number} dueTime Duration of the debounce period for each value (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the debounce timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The debounced sequence.
*/
observableProto.debounce = observableProto.throttleWithTimeout = function (dueTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0;
var subscription = source.subscribe(
function (x) {
hasvalue = true;
value = x;
id++;
var currentId = id,
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () {
hasvalue && id === currentId && observer.onNext(value);
hasvalue = false;
}));
},
function (e) {
cancelable.dispose();
observer.onError(e);
hasvalue = false;
id++;
},
function () {
cancelable.dispose();
hasvalue && observer.onNext(value);
observer.onCompleted();
hasvalue = false;
id++;
});
return new CompositeDisposable(subscription, cancelable);
}, this);
};
/**
* @deprecated use #debounce or #throttleWithTimeout instead.
*/
observableProto.throttle = function(dueTime, scheduler) {
//deprecate('throttle', 'debounce or throttleWithTimeout');
return this.debounce(dueTime, scheduler);
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on timing information.
* @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds).
* @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows.
* @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
var source = this, timeShift;
timeShiftOrScheduler == null && (timeShift = timeSpan);
isScheduler(scheduler) || (scheduler = timeoutScheduler);
if (typeof timeShiftOrScheduler === 'number') {
timeShift = timeShiftOrScheduler;
} else if (isScheduler(timeShiftOrScheduler)) {
timeShift = timeSpan;
scheduler = timeShiftOrScheduler;
}
return new AnonymousObservable(function (observer) {
var groupDisposable,
nextShift = timeShift,
nextSpan = timeSpan,
q = [],
refCountDisposable,
timerD = new SerialDisposable(),
totalTime = 0;
groupDisposable = new CompositeDisposable(timerD),
refCountDisposable = new RefCountDisposable(groupDisposable);
function createTimer () {
var m = new SingleAssignmentDisposable(),
isSpan = false,
isShift = false;
timerD.setDisposable(m);
if (nextSpan === nextShift) {
isSpan = true;
isShift = true;
} else if (nextSpan < nextShift) {
isSpan = true;
} else {
isShift = true;
}
var newTotalTime = isSpan ? nextSpan : nextShift,
ts = newTotalTime - totalTime;
totalTime = newTotalTime;
if (isSpan) {
nextSpan += timeShift;
}
if (isShift) {
nextShift += timeShift;
}
m.setDisposable(scheduler.scheduleWithRelative(ts, function () {
if (isShift) {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
}
isSpan && q.shift().onCompleted();
createTimer();
}));
};
q.push(new Subject());
observer.onNext(addRef(q[0], refCountDisposable));
createTimer();
groupDisposable.add(source.subscribe(
function (x) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
},
function (e) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onError(e); }
observer.onError(e);
},
function () {
for (var i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); }
observer.onCompleted();
}
));
return refCountDisposable;
}, source);
};
/**
* Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed.
* @param {Number} timeSpan Maximum time length of a window.
* @param {Number} count Maximum element count of a window.
* @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var timerD = new SerialDisposable(),
groupDisposable = new CompositeDisposable(timerD),
refCountDisposable = new RefCountDisposable(groupDisposable),
n = 0,
windowId = 0,
s = new Subject();
function createTimer(id) {
var m = new SingleAssignmentDisposable();
timerD.setDisposable(m);
m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () {
if (id !== windowId) { return; }
n = 0;
var newId = ++windowId;
s.onCompleted();
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
createTimer(newId);
}));
}
observer.onNext(addRef(s, refCountDisposable));
createTimer(0);
groupDisposable.add(source.subscribe(
function (x) {
var newId = 0, newWindow = false;
s.onNext(x);
if (++n === count) {
newWindow = true;
n = 0;
newId = ++windowId;
s.onCompleted();
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
}
newWindow && createTimer(newId);
},
function (e) {
s.onError(e);
observer.onError(e);
}, function () {
s.onCompleted();
observer.onCompleted();
}
));
return refCountDisposable;
}, source);
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on timing information.
*
* @example
* 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second
* 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds
*
* @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds).
* @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers.
* @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); });
};
/**
* Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed.
*
* @example
* 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array
* 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array
*
* @param {Number} timeSpan Maximum time length of a buffer.
* @param {Number} count Maximum element count of a buffer.
* @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) {
return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) {
return x.toArray();
});
};
/**
* Records the time interval between consecutive values in an observable sequence.
*
* @example
* 1 - res = source.timeInterval();
* 2 - res = source.timeInterval(Rx.Scheduler.timeout);
*
* @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with time interval information on values.
*/
observableProto.timeInterval = function (scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return observableDefer(function () {
var last = scheduler.now();
return source.map(function (x) {
var now = scheduler.now(), span = now - last;
last = now;
return { value: x, interval: span };
});
});
};
/**
* Records the timestamp for each value in an observable sequence.
*
* @example
* 1 - res = source.timestamp(); // produces { value: x, timestamp: ts }
* 2 - res = source.timestamp(Rx.Scheduler.timeout);
*
* @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with timestamp information on values.
*/
observableProto.timestamp = function (scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return this.map(function (x) {
return { value: x, timestamp: scheduler.now() };
});
};
function sampleObservable(source, sampler) {
return new AnonymousObservable(function (observer) {
var atEnd, value, hasValue;
function sampleSubscribe() {
if (hasValue) {
hasValue = false;
observer.onNext(value);
}
atEnd && observer.onCompleted();
}
return new CompositeDisposable(
source.subscribe(function (newValue) {
hasValue = true;
value = newValue;
}, observer.onError.bind(observer), function () {
atEnd = true;
}),
sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe)
);
}, source);
}
/**
* Samples the observable sequence at each interval.
*
* @example
* 1 - res = source.sample(sampleObservable); // Sampler tick sequence
* 2 - res = source.sample(5000); // 5 seconds
* 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable.
* @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Sampled observable sequence.
*/
observableProto.sample = observableProto.throttleLatest = function (intervalOrSampler, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return typeof intervalOrSampler === 'number' ?
sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) :
sampleObservable(this, intervalOrSampler);
};
/**
* Returns the source observable sequence or the other observable sequence if dueTime elapses.
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs.
* @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used.
* @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeout = function (dueTime, other, scheduler) {
(other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout')));
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = dueTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
var id = 0,
original = new SingleAssignmentDisposable(),
subscription = new SerialDisposable(),
switched = false,
timer = new SerialDisposable();
subscription.setDisposable(original);
function createTimer() {
var myId = id;
timer.setDisposable(scheduler[schedulerMethod](dueTime, function () {
if (id === myId) {
isPromise(other) && (other = observableFromPromise(other));
subscription.setDisposable(other.subscribe(observer));
}
}));
}
createTimer();
original.setDisposable(source.subscribe(function (x) {
if (!switched) {
id++;
observer.onNext(x);
createTimer();
}
}, function (e) {
if (!switched) {
id++;
observer.onError(e);
}
}, function () {
if (!switched) {
id++;
observer.onCompleted();
}
}));
return new CompositeDisposable(subscription, timer);
}, source);
};
/**
* Generates an observable sequence by iterating a state from an initial state until the condition fails.
*
* @example
* res = source.generateWithAbsoluteTime(0,
* function (x) { return return true; },
* function (x) { return x + 1; },
* function (x) { return x; },
* function (x) { return new Date(); }
* });
*
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.
* @returns {Observable} The generated sequence.
*/
Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var first = true,
hasResult = false,
result,
state = initialState,
time;
return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) {
hasResult && observer.onNext(result);
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
time = timeSelector(state);
}
} catch (e) {
observer.onError(e);
return;
}
if (hasResult) {
self(time);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence by iterating a state from an initial state until the condition fails.
*
* @example
* res = source.generateWithRelativeTime(0,
* function (x) { return return true; },
* function (x) { return x + 1; },
* function (x) { return x; },
* function (x) { return 500; }
* );
*
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.
* @returns {Observable} The generated sequence.
*/
Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var first = true,
hasResult = false,
result,
state = initialState,
time;
return scheduler.scheduleRecursiveWithRelative(0, function (self) {
hasResult && observer.onNext(result);
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
time = timeSelector(state);
}
} catch (e) {
observer.onError(e);
return;
}
if (hasResult) {
self(time);
} else {
observer.onCompleted();
}
});
});
};
/**
* Time shifts the observable sequence by delaying the subscription.
*
* @example
* 1 - res = source.delaySubscription(5000); // 5s
* 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Number} dueTime Absolute or relative time to perform the subscription at.
* @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delaySubscription = function (dueTime, scheduler) {
return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), observableEmpty);
};
/**
* Time shifts the observable sequence based on a subscription delay and a delay selector function for each element.
*
* @example
* 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only
* 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector
*
* @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source.
* @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) {
var source = this, subDelay, selector;
if (typeof subscriptionDelay === 'function') {
selector = subscriptionDelay;
} else {
subDelay = subscriptionDelay;
selector = delayDurationSelector;
}
return new AnonymousObservable(function (observer) {
var delays = new CompositeDisposable(), atEnd = false, done = function () {
if (atEnd && delays.length === 0) { observer.onCompleted(); }
}, subscription = new SerialDisposable(), start = function () {
subscription.setDisposable(source.subscribe(function (x) {
var delay;
try {
delay = selector(x);
} catch (error) {
observer.onError(error);
return;
}
var d = new SingleAssignmentDisposable();
delays.add(d);
d.setDisposable(delay.subscribe(function () {
observer.onNext(x);
delays.remove(d);
done();
}, observer.onError.bind(observer), function () {
observer.onNext(x);
delays.remove(d);
done();
}));
}, observer.onError.bind(observer), function () {
atEnd = true;
subscription.dispose();
done();
}));
};
if (!subDelay) {
start();
} else {
subscription.setDisposable(subDelay.subscribe(start, observer.onError.bind(observer), start));
}
return new CompositeDisposable(subscription, delays);
}, this);
};
/**
* Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled.
* @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never().
* @param {Function} timeoutDurationSelector Selector to retrieve an observable sequence that represents the timeout between the current element and the next element.
* @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException().
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) {
if (arguments.length === 1) {
timeoutdurationSelector = firstTimeout;
firstTimeout = observableNever();
}
other || (other = observableThrow(new Error('Timeout')));
var source = this;
return new AnonymousObservable(function (observer) {
var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable();
subscription.setDisposable(original);
var id = 0, switched = false;
function setTimer(timeout) {
var myId = id;
function timerWins () {
return id === myId;
}
var d = new SingleAssignmentDisposable();
timer.setDisposable(d);
d.setDisposable(timeout.subscribe(function () {
timerWins() && subscription.setDisposable(other.subscribe(observer));
d.dispose();
}, function (e) {
timerWins() && observer.onError(e);
}, function () {
timerWins() && subscription.setDisposable(other.subscribe(observer));
}));
};
setTimer(firstTimeout);
function observerWins() {
var res = !switched;
if (res) { id++; }
return res;
}
original.setDisposable(source.subscribe(function (x) {
if (observerWins()) {
observer.onNext(x);
var timeout;
try {
timeout = timeoutdurationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
setTimer(isPromise(timeout) ? observableFromPromise(timeout) : timeout);
}
}, function (e) {
observerWins() && observer.onError(e);
}, function () {
observerWins() && observer.onCompleted();
}));
return new CompositeDisposable(subscription, timer);
}, source);
};
/**
* Ignores values from an observable sequence which are followed by another value within a computed throttle duration.
* @param {Function} durationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element.
* @returns {Observable} The debounced sequence.
*/
observableProto.debounceWithSelector = function (durationSelector) {
var source = this;
return new AnonymousObservable(function (observer) {
var value, hasValue = false, cancelable = new SerialDisposable(), id = 0;
var subscription = source.subscribe(function (x) {
var throttle;
try {
throttle = durationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
isPromise(throttle) && (throttle = observableFromPromise(throttle));
hasValue = true;
value = x;
id++;
var currentid = id, d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(throttle.subscribe(function () {
hasValue && id === currentid && observer.onNext(value);
hasValue = false;
d.dispose();
}, observer.onError.bind(observer), function () {
hasValue && id === currentid && observer.onNext(value);
hasValue = false;
d.dispose();
}));
}, function (e) {
cancelable.dispose();
observer.onError(e);
hasValue = false;
id++;
}, function () {
cancelable.dispose();
hasValue && observer.onNext(value);
observer.onCompleted();
hasValue = false;
id++;
});
return new CompositeDisposable(subscription, cancelable);
}, source);
};
/**
* @deprecated use #debounceWithSelector instead.
*/
observableProto.throttleWithSelector = function (durationSelector) {
//deprecate('throttleWithSelector', 'debounceWithSelector');
return this.debounceWithSelector(durationSelector);
};
/**
* Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
*
* 1 - res = source.skipLastWithTime(5000);
* 2 - res = source.skipLastWithTime(5000, scheduler);
*
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for skipping elements from the end of the sequence.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence.
*/
observableProto.skipLastWithTime = function (duration, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
o.onNext(q.shift().value);
}
}, function (e) { o.onError(e); }, function () {
var now = scheduler.now();
while (q.length > 0 && now - q[0].interval >= duration) {
o.onNext(q.shift().value);
}
o.onCompleted();
});
}, source);
};
/**
* Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements.
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
q.shift();
}
}, function (e) { o.onError(e); }, function () {
var now = scheduler.now();
while (q.length > 0) {
var next = q.shift();
if (now - next.interval <= duration) { o.onNext(next.value); }
}
o.onCompleted();
});
}, source);
};
/**
* Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastBufferWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
q.shift();
}
}, function (e) { o.onError(e); }, function () {
var now = scheduler.now(), res = [];
while (q.length > 0) {
var next = q.shift();
now - next.interval <= duration && res.push(next.value);
}
o.onNext(res);
o.onCompleted();
});
}, source);
};
/**
* Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.takeWithTime(5000, [optional scheduler]);
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence.
*/
observableProto.takeWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (o) {
return new CompositeDisposable(scheduler.scheduleWithRelative(duration, function () { o.onCompleted(); }), source.subscribe(o));
}, source);
};
/**
* Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.skipWithTime(5000, [optional scheduler]);
*
* @description
* Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence.
* This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded
* may not execute immediately, despite the zero due time.
*
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration.
* @param {Number} duration Duration for skipping elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence.
*/
observableProto.skipWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var open = false;
return new CompositeDisposable(
scheduler.scheduleWithRelative(duration, function () { open = true; }),
source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)));
}, source);
};
/**
* Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers.
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time.
*
* @examples
* 1 - res = source.skipUntilWithTime(new Date(), [scheduler]);
* 2 - res = source.skipUntilWithTime(5000, [scheduler]);
* @param {Date|Number} startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped until the specified start time.
*/
observableProto.skipUntilWithTime = function (startTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = startTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (o) {
var open = false;
return new CompositeDisposable(
scheduler[schedulerMethod](startTime, function () { open = true; }),
source.subscribe(
function (x) { open && o.onNext(x); },
function (e) { o.onError(e); }, function () { o.onCompleted(); }));
}, source);
};
/**
* Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers.
* @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately.
* @param {Scheduler} [scheduler] Scheduler to run the timer on.
* @returns {Observable} An observable sequence with the elements taken until the specified end time.
*/
observableProto.takeUntilWithTime = function (endTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = endTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (o) {
return new CompositeDisposable(
scheduler[schedulerMethod](endTime, function () { o.onCompleted(); }),
source.subscribe(o));
}, source);
};
/**
* Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration.
* @param {Number} windowDuration time to wait before emitting another item after emitting the last item
* @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout.
* @returns {Observable} An Observable that performs the throttle operation.
*/
observableProto.throttleFirst = function (windowDuration, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var duration = +windowDuration || 0;
if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); }
var source = this;
return new AnonymousObservable(function (o) {
var lastOnNext = 0;
return source.subscribe(
function (x) {
var now = scheduler.now();
if (lastOnNext === 0 || now - lastOnNext >= duration) {
lastOnNext = now;
o.onNext(x);
}
},function (e) { o.onError(e); }, function () { o.onCompleted(); }
);
}, source);
};
/**
* Executes a transducer to transform the observable sequence
* @param {Transducer} transducer A transducer to execute
* @returns {Observable} An Observable sequence containing the results from the transducer.
*/
observableProto.transduce = function(transducer) {
var source = this;
function transformForObserver(o) {
return {
'@@transducer/init': function() {
return o;
},
'@@transducer/step': function(obs, input) {
return obs.onNext(input);
},
'@@transducer/result': function(obs) {
return obs.onCompleted();
}
};
}
return new AnonymousObservable(function(o) {
var xform = transducer(transformForObserver(o));
return source.subscribe(
function(v) {
try {
xform['@@transducer/step'](o, v);
} catch (e) {
o.onError(e);
}
},
function (e) { o.onError(e); },
function() { xform['@@transducer/result'](o); }
);
}, source);
};
/*
* Performs a exclusive waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @returns {Observable} A exclusive observable with only the results that happen when subscribed.
*/
observableProto.exclusive = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasCurrent = false,
isStopped = false,
m = new SingleAssignmentDisposable(),
g = new CompositeDisposable();
g.add(m);
m.setDisposable(sources.subscribe(
function (innerSource) {
if (!hasCurrent) {
hasCurrent = true;
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
var innerSubscription = new SingleAssignmentDisposable();
g.add(innerSubscription);
innerSubscription.setDisposable(innerSource.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () {
g.remove(innerSubscription);
hasCurrent = false;
if (isStopped && g.length === 1) {
observer.onCompleted();
}
}));
}
},
observer.onError.bind(observer),
function () {
isStopped = true;
if (!hasCurrent && g.length === 1) {
observer.onCompleted();
}
}));
return g;
}, this);
};
/*
* Performs a exclusive map waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @param {Function} selector Selector to invoke for every item in the current subscription.
* @param {Any} [thisArg] An optional context to invoke with the selector parameter.
* @returns {Observable} An exclusive observable with only the results that happen when subscribed.
*/
observableProto.exclusiveMap = function (selector, thisArg) {
var sources = this,
selectorFunc = bindCallback(selector, thisArg, 3);
return new AnonymousObservable(function (observer) {
var index = 0,
hasCurrent = false,
isStopped = true,
m = new SingleAssignmentDisposable(),
g = new CompositeDisposable();
g.add(m);
m.setDisposable(sources.subscribe(
function (innerSource) {
if (!hasCurrent) {
hasCurrent = true;
innerSubscription = new SingleAssignmentDisposable();
g.add(innerSubscription);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(
function (x) {
var result;
try {
result = selectorFunc(x, index++, innerSource);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
},
function (e) { observer.onError(e); },
function () {
g.remove(innerSubscription);
hasCurrent = false;
if (isStopped && g.length === 1) {
observer.onCompleted();
}
}));
}
},
function (e) { observer.onError(e); },
function () {
isStopped = true;
if (g.length === 1 && !hasCurrent) {
observer.onCompleted();
}
}));
return g;
}, this);
};
/** Provides a set of extension methods for virtual time scheduling. */
Rx.VirtualTimeScheduler = (function (__super__) {
function localNow() {
return this.toDateTimeOffset(this.clock);
}
function scheduleNow(state, action) {
return this.scheduleAbsoluteWithState(state, this.clock, action);
}
function scheduleRelative(state, dueTime, action) {
return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action);
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
inherits(VirtualTimeScheduler, __super__);
/**
* Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer.
*
* @constructor
* @param {Number} initialClock Initial value for the clock.
* @param {Function} comparer Comparer to determine causality of events based on absolute time.
*/
function VirtualTimeScheduler(initialClock, comparer) {
this.clock = initialClock;
this.comparer = comparer;
this.isEnabled = false;
this.queue = new PriorityQueue(1024);
__super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}
var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype;
/**
* Adds a relative time value to an absolute time value.
* @param {Number} absolute Absolute virtual time value.
* @param {Number} relative Relative virtual time value to add.
* @return {Number} Resulting absolute virtual time sum value.
*/
VirtualTimeSchedulerPrototype.add = notImplemented;
/**
* Converts an absolute time to a number
* @param {Any} The absolute time.
* @returns {Number} The absolute time in ms
*/
VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented;
/**
* Converts the TimeSpan value to a relative virtual time value.
* @param {Number} timeSpan TimeSpan value to convert.
* @return {Number} Corresponding relative virtual time value.
*/
VirtualTimeSchedulerPrototype.toRelative = notImplemented;
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) {
var s = new SchedulePeriodicRecursive(this, state, period, action);
return s.start();
};
/**
* Schedules an action to be executed after dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) {
var runAt = this.add(this.clock, dueTime);
return this.scheduleAbsoluteWithState(state, runAt, action);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Number} dueTime Relative time after which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) {
return this.scheduleRelativeWithState(action, dueTime, invokeAction);
};
/**
* Starts the virtual time scheduler.
*/
VirtualTimeSchedulerPrototype.start = function () {
if (!this.isEnabled) {
this.isEnabled = true;
do {
var next = this.getNext();
if (next !== null) {
this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime);
next.invoke();
} else {
this.isEnabled = false;
}
} while (this.isEnabled);
}
};
/**
* Stops the virtual time scheduler.
*/
VirtualTimeSchedulerPrototype.stop = function () {
this.isEnabled = false;
};
/**
* Advances the scheduler's clock to the specified time, running all work till that point.
* @param {Number} time Absolute time to advance the scheduler's clock to.
*/
VirtualTimeSchedulerPrototype.advanceTo = function (time) {
var dueToClock = this.comparer(this.clock, time);
if (this.comparer(this.clock, time) > 0) { throw new ArgumentOutOfRangeError(); }
if (dueToClock === 0) { return; }
if (!this.isEnabled) {
this.isEnabled = true;
do {
var next = this.getNext();
if (next !== null && this.comparer(next.dueTime, time) <= 0) {
this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime);
next.invoke();
} else {
this.isEnabled = false;
}
} while (this.isEnabled);
this.clock = time;
}
};
/**
* Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan.
* @param {Number} time Relative time to advance the scheduler's clock by.
*/
VirtualTimeSchedulerPrototype.advanceBy = function (time) {
var dt = this.add(this.clock, time),
dueToClock = this.comparer(this.clock, dt);
if (dueToClock > 0) { throw new ArgumentOutOfRangeError(); }
if (dueToClock === 0) { return; }
this.advanceTo(dt);
};
/**
* Advances the scheduler's clock by the specified relative time.
* @param {Number} time Relative time to advance the scheduler's clock by.
*/
VirtualTimeSchedulerPrototype.sleep = function (time) {
var dt = this.add(this.clock, time);
if (this.comparer(this.clock, dt) >= 0) { throw new ArgumentOutOfRangeError(); }
this.clock = dt;
};
/**
* Gets the next scheduled item to be executed.
* @returns {ScheduledItem} The next scheduled item.
*/
VirtualTimeSchedulerPrototype.getNext = function () {
while (this.queue.length > 0) {
var next = this.queue.peek();
if (next.isCancelled()) {
this.queue.dequeue();
} else {
return next;
}
}
return null;
};
/**
* Schedules an action to be executed at dueTime.
* @param {Scheduler} scheduler Scheduler to execute the action on.
* @param {Number} dueTime Absolute time at which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) {
return this.scheduleAbsoluteWithState(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Number} dueTime Absolute time at which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) {
var self = this;
function run(scheduler, state1) {
self.queue.remove(si);
return action(scheduler, state1);
}
var si = new ScheduledItem(this, state, run, dueTime, this.comparer);
this.queue.enqueue(si);
return si.disposable;
};
return VirtualTimeScheduler;
}(Scheduler));
/** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */
Rx.HistoricalScheduler = (function (__super__) {
inherits(HistoricalScheduler, __super__);
/**
* Creates a new historical scheduler with the specified initial clock value.
* @constructor
* @param {Number} initialClock Initial value for the clock.
* @param {Function} comparer Comparer to determine causality of events based on absolute time.
*/
function HistoricalScheduler(initialClock, comparer) {
var clock = initialClock == null ? 0 : initialClock;
var cmp = comparer || defaultSubComparer;
__super__.call(this, clock, cmp);
}
var HistoricalSchedulerProto = HistoricalScheduler.prototype;
/**
* Adds a relative time value to an absolute time value.
* @param {Number} absolute Absolute virtual time value.
* @param {Number} relative Relative virtual time value to add.
* @return {Number} Resulting absolute virtual time sum value.
*/
HistoricalSchedulerProto.add = function (absolute, relative) {
return absolute + relative;
};
HistoricalSchedulerProto.toDateTimeOffset = function (absolute) {
return new Date(absolute).getTime();
};
/**
* Converts the TimeSpan value to a relative virtual time value.
* @memberOf HistoricalScheduler
* @param {Number} timeSpan TimeSpan value to convert.
* @return {Number} Corresponding relative virtual time value.
*/
HistoricalSchedulerProto.toRelative = function (timeSpan) {
return timeSpan;
};
return HistoricalScheduler;
}(Rx.VirtualTimeScheduler));
var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
inherits(AnonymousObservable, __super__);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
return subscriber && isFunction(subscriber.dispose) ? subscriber :
isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
}
function setDisposable(s, state) {
var ado = state[0], subscribe = state[1];
var sub = tryCatch(subscribe)(ado);
if (sub === errorObj) {
if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); }
}
ado.setDisposable(fixSubscriber(sub));
}
function AnonymousObservable(subscribe, parent) {
this.source = parent;
function s(observer) {
var ado = new AutoDetachObserver(observer), state = [ado, subscribe];
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.scheduleWithState(state, setDisposable);
} else {
setDisposable(null, state);
}
return ado;
}
__super__.call(this, s);
}
return AnonymousObservable;
}(Observable));
var AutoDetachObserver = (function (__super__) {
inherits(AutoDetachObserver, __super__);
function AutoDetachObserver(observer) {
__super__.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var result = tryCatch(this.observer.onNext).call(this.observer, value);
if (result === errorObj) {
this.dispose();
thrower(result.e);
}
};
AutoDetachObserverPrototype.error = function (err) {
var result = tryCatch(this.observer.onError).call(this.observer, err);
this.dispose();
result === errorObj && thrower(result.e);
};
AutoDetachObserverPrototype.completed = function () {
var result = tryCatch(this.observer.onCompleted).call(this.observer);
this.dispose();
result === errorObj && thrower(result.e);
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); };
AutoDetachObserverPrototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
var GroupedObservable = (function (__super__) {
inherits(GroupedObservable, __super__);
function subscribe(observer) {
return this.underlyingObservable.subscribe(observer);
}
function GroupedObservable(key, underlyingObservable, mergedDisposable) {
__super__.call(this, subscribe);
this.key = key;
this.underlyingObservable = !mergedDisposable ?
underlyingObservable :
new AnonymousObservable(function (observer) {
return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer));
});
}
return GroupedObservable;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, __super__);
/**
* Creates a subject.
*/
function Subject() {
__super__.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
this.hasError = false;
}
addProperties(Subject.prototype, Observer.prototype, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () { return this.observers.length > 0; },
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
this.error = error;
this.hasError = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (!this.isStopped) {
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
} else if (this.hasValue) {
observer.onNext(this.value);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, __super__);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
* @constructor
*/
function AsyncSubject() {
__super__.call(this, subscribe);
this.isDisposed = false;
this.isStopped = false;
this.hasValue = false;
this.observers = [];
this.hasError = false;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
checkDisposed(this);
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*/
onCompleted: function () {
var i, len;
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
var os = cloneArray(this.observers), len = os.length;
if (this.hasValue) {
for (i = 0; i < len; i++) {
var o = os[i];
o.onNext(this.value);
o.onCompleted();
}
} else {
for (i = 0; i < len; i++) {
os[i].onCompleted();
}
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the error.
* @param {Mixed} error The Error to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
this.hasError = true;
this.error = error;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
this.value = value;
this.hasValue = true;
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.exception = null;
this.value = null;
}
});
return AsyncSubject;
}(Observable));
var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) {
inherits(AnonymousSubject, __super__);
function subscribe(observer) {
return this.observable.subscribe(observer);
}
function AnonymousSubject(observer, observable) {
this.observer = observer;
this.observable = observable;
__super__.call(this, subscribe);
}
addProperties(AnonymousSubject.prototype, Observer.prototype, {
onCompleted: function () {
this.observer.onCompleted();
},
onError: function (error) {
this.observer.onError(error);
},
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
/**
* Used to pause and resume streams.
*/
Rx.Pauser = (function (__super__) {
inherits(Pauser, __super__);
function Pauser() {
__super__.call(this);
}
/**
* Pauses the underlying sequence.
*/
Pauser.prototype.pause = function () { this.onNext(false); };
/**
* Resumes the underlying sequence.
*/
Pauser.prototype.resume = function () { this.onNext(true); };
return Pauser;
}(Subject));
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
root.Rx = Rx;
define(function() {
return Rx;
});
} else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = Rx).Rx = Rx;
} else {
freeExports.Rx = Rx;
}
} else {
// in a browser or Rhino
root.Rx = Rx;
}
// All code before this point will be filtered from stack traces.
var rEndingLine = captureLine();
}.call(this));
|
website/server/server.js
|
tarkus/react-native-appletv
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
"use strict";
var connect = require('connect');
var http = require('http');
var optimist = require('optimist');
var path = require('path');
var reactMiddleware = require('react-page-middleware');
var convert = require('./convert.js');
var argv = optimist.argv;
var PROJECT_ROOT = path.resolve(__dirname, '..');
var FILE_SERVE_ROOT = path.join(PROJECT_ROOT, 'src');
var port = argv.port;
if (argv.$0 === 'node ./server/generate.js') {
// Using a different port so that you can publish the website
// and keeping the server up at the same time.
port = 8079;
}
var buildOptions = {
projectRoot: PROJECT_ROOT,
pageRouteRoot: FILE_SERVE_ROOT,
useBrowserBuiltins: false,
logTiming: true,
useSourceMaps: true,
ignorePaths: function(p) {
return p.indexOf('__tests__') !== -1;
},
serverRender: true,
dev: argv.dev !== 'false',
static: true
};
var app = connect()
.use(function(req, res, next) {
// convert all the md files on every request. This is not optimal
// but fast enough that we don't really need to care right now.
if (!server.noconvert && req.url.match(/\.html|\/$/)) {
convert();
}
next();
})
.use(reactMiddleware.provide(buildOptions))
.use(connect['static'](FILE_SERVE_ROOT))
.use(connect.favicon(path.join(FILE_SERVE_ROOT, 'react-native', 'img', 'favicon.png')))
.use(connect.logger())
.use(connect.compress())
.use(connect.errorHandler());
var portToUse = port || 8079;
var server = http.createServer(app);
server.listen(portToUse, function(){
console.log('Open http://localhost:' + portToUse + '/react-native/index.html');
});
module.exports = server;
|
ajax/libs/rxjs/2.3.3/rx.js
|
blairvanderhoof/cdnjs
|
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = {
internals: {},
config: {
Promise: root.Promise // Detect if promise exists
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; },
isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; },
identity = Rx.helpers.identity = function (x) { return x; },
pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },
just = Rx.helpers.just = function (value) { return function () { return value; }; },
defaultNow = Rx.helpers.defaultNow = Date.now,
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; };
// Errors
var sequenceContainsNoElements = 'Sequence contains no elements.';
var argumentOutOfRange = 'Argument out of range';
var objectDisposed = 'Object has been disposed';
function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } }
// Shim in iterator support
var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
'_es6shim_iterator_';
// Bug for mozilla version
if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var doneEnumerator = { done: true, value: undefined };
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
suportNodeClass,
errorProto = Error.prototype,
objectProto = Object.prototype,
propertyIsEnumerable = objectProto.propertyIsEnumerable;
try {
suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch(e) {
suportNodeClass = true;
}
var shadowedProps = [
'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf'
];
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
var support = {};
(function () {
var ctor = function() { this.x = 1; },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
// Detect if `name` or `message` properties of `Error.prototype` are enumerable by default.
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
// Detect if `prototype` properties are enumerable by default.
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
// Detect if `arguments` object indexes are non-enumerable
support.nonEnumArgs = key != 0;
// Detect if properties shadowing those on `Object.prototype` are non-enumerable.
support.nonEnumShadows = !/valueOf/.test(props);
}(1));
function isObject(value) {
// check if the value is the ECMAScript language type of Object
// http://es5.github.io/#x8
// and avoid a V8 bug
// https://code.google.com/p/v8/issues/detail?id=2291
var type = typeof value;
return value && (type == 'function' || type == 'object') || false;
}
function keysIn(object) {
var result = [];
if (!isObject(object)) {
return result;
}
if (support.nonEnumArgs && object.length && isArguments(object)) {
object = slice.call(object);
}
var skipProto = support.enumPrototypes && typeof object == 'function',
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error);
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name'))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var ctor = object.constructor,
index = -1,
length = shadowedProps.length;
if (object === (ctor && ctor.prototype)) {
var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object),
nonEnum = nonEnumProps[className];
}
while (++index < length) {
key = shadowedProps[index];
if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) {
result.push(key);
}
}
}
return result;
}
function internalFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
function internalForIn(object, callback) {
return internalFor(object, callback, keysIn);
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
function isArguments(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
function isFunction(value) {
return typeof value == 'function' || false;
}
// fallback for older versions of Chrome and Safari
if (isFunction(/x/)) {
isFunction = function(value) {
return typeof value == 'function' && toString.call(value) == funcClass;
};
}
var isEqual = Rx.internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a && (a == null || b == null ||
(type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) {
return false;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a)
? b != +b
// but treat `-0` vs. `+0` as not equal
: (a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var initedStack = !stackA;
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
internalForIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB));
}
});
if (result) {
// ensure both objects have the same number of properties
internalForIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
}
stackA.pop();
stackB.pop();
return result;
}
var slice = Array.prototype.slice;
function argsOrArray(args, idx) {
return args.length === 1 && Array.isArray(args[idx]) ?
args[idx] :
slice.call(args);
}
var hasProp = {}.hasOwnProperty;
/** @private */
var inherits = this.inherits = Rx.internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
/** @private */
var addProperties = Rx.internals.addProperties = function (obj) {
var sources = slice.call(arguments, 1);
for (var i = 0, len = sources.length; i < len; i++) {
var source = sources[i];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
// Collection polyfills
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
// Collections
var IndexedItem = function (id, value) {
this.id = id;
this.value = value;
};
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
if (c === 0) {
c = this.id - other.id;
}
return c;
};
// Priority Queue for Scheduling
var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) {
return;
}
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) {
return;
}
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
if (index === undefined) {
index = 0;
}
if (index >= this.length || index < 0) {
return;
}
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () { return this.items[0].value; };
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
delete this.items[this.length];
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
this.disposables = argsOrArray(arguments, 0);
this.isDisposed = false;
this.length = this.disposables.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable.
*/
CompositeDisposablePrototype.clear = function () {
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
};
/**
* Determines whether the CompositeDisposable contains a specific disposable.
* @param {Mixed} item Disposable to search for.
* @returns {Boolean} true if the disposable was found; otherwise, false.
*/
CompositeDisposablePrototype.contains = function (item) {
return this.disposables.indexOf(item) !== -1;
};
/**
* Converts the existing CompositeDisposable to an array of disposables
* @returns {Array} An array of disposable objects.
*/
CompositeDisposablePrototype.toArray = function () {
return this.disposables.slice(0);
};
/**
* Provides a set of static methods for creating Disposables.
*
* @constructor
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
var BooleanDisposable = (function () {
function BooleanDisposable (isSingle) {
this.isSingle = isSingle;
this.isDisposed = false;
this.current = null;
}
var booleanDisposablePrototype = BooleanDisposable.prototype;
/**
* Gets the underlying disposable.
* @return The underlying disposable.
*/
booleanDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
* @param {Disposable} value The new underlying disposable.
*/
booleanDisposablePrototype.setDisposable = function (value) {
if (this.current && this.isSingle) {
throw new Error('Disposable has already been assigned');
}
var shouldDispose = this.isDisposed, old;
if (!shouldDispose) {
old = this.current;
this.current = value;
}
old && old.dispose();
shouldDispose && value && value.dispose();
};
/**
* Disposes the underlying disposable as well as all future replacements.
*/
booleanDisposablePrototype.dispose = function () {
var old;
if (!this.isDisposed) {
this.isDisposed = true;
old = this.current;
this.current = null;
}
old && old.dispose();
};
return BooleanDisposable;
}());
/**
* Represents a disposable resource which only allows a single assignment of its underlying disposable resource.
* If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error.
*/
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) {
inherits(SingleAssignmentDisposable, super_);
function SingleAssignmentDisposable() {
super_.call(this, true);
}
return SingleAssignmentDisposable;
}(BooleanDisposable));
/**
* Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource.
*/
var SerialDisposable = Rx.SerialDisposable = (function (super_) {
inherits(SerialDisposable, super_);
function SerialDisposable() {
super_.call(this, false);
}
return SerialDisposable;
}(BooleanDisposable));
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed) {
if (!this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
if (!this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
function ScheduledDisposable(scheduler, disposable) {
this.scheduler = scheduler;
this.disposable = disposable;
this.isDisposed = false;
}
ScheduledDisposable.prototype.dispose = function () {
var parent = this;
this.scheduler.schedule(function () {
if (!parent.isDisposed) {
parent.isDisposed = true;
parent.disposable.dispose();
}
});
};
var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
/**
* @constructor
* @private
*/
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
function invokeRecImmediate(scheduler, pair) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions.
* @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false.
* @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling.
*/
schedulerProto.catchException = schedulerProto['catch'] = function (handler) {
return new CatchScheduler(this, handler);
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
schedulerProto.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, function () {
action();
});
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
schedulerProto.schedulePeriodicWithState = function (state, period, action) {
var s = state, id = setInterval(function () {
s = action(s);
}, period);
return disposableCreate(function () {
clearInterval(id);
});
};
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/**
* Schedules an action to be executed recursively.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, function (_action, self) {
_action(function () {
self(_action);
});
});
};
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState({ first: state, second: action }, function (s, p) {
return invokeRecImmediate(s, p);
});
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) {
_action(function (dt) {
self(_action, dt);
});
});
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) {
_action(function (dt) {
self(_action, dt);
});
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
if (timeSpan < 0) {
timeSpan = 0;
}
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize;
var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
/**
* Gets a scheduler that schedules work immediately on the current thread.
*/
var immediateScheduler = Scheduler.immediate = (function () {
function scheduleNow(state, action) { return action(this, state); }
function scheduleRelative(state, dueTime, action) {
var dt = normalizeTime(dt);
while (dt - this.now() > 0) { }
return action(this, state);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
function runTrampoline (q) {
var item;
while (q.length > 0) {
item = q.dequeue();
if (!item.isCancelled()) {
// Note, do not schedule blocking work!
while (item.dueTime - Scheduler.now() > 0) {
}
if (!item.isCancelled()) {
item.invoke();
}
}
}
}
function scheduleNow(state, action) {
return this.scheduleWithRelativeAndState(state, 0, action);
}
function scheduleRelative(state, dueTime, action) {
var dt = this.now() + Scheduler.normalize(dueTime),
si = new ScheduledItem(this, state, action, dt);
if (!queue) {
queue = new PriorityQueue(4);
queue.enqueue(si);
try {
runTrampoline(queue);
} catch (e) {
throw e;
} finally {
queue = null;
}
} else {
queue.enqueue(si);
}
return si.disposable;
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
currentScheduler.scheduleRequired = function () { return !queue; };
currentScheduler.ensureTrampoline = function (action) {
if (!queue) { this.schedule(action); } else { action(); }
};
return currentScheduler;
}());
var scheduleMethod, clearMethod = noop;
(function () {
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate,
clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' &&
!reNative.test(clearImmediate) && clearImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false,
oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('','*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = process.nextTick;
} else if (typeof setImmediate === 'function') {
scheduleMethod = setImmediate;
clearMethod = clearImmediate;
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random(),
tasks = {},
taskId = 0;
function onGlobalPostMessage(event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
var handleId = event.data.substring(MSG_PREFIX.length),
action = tasks[handleId];
action();
delete tasks[handleId];
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else {
root.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var currentId = taskId++;
tasks[currentId] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel(),
channelTasks = {},
channelTaskId = 0;
channel.port1.onmessage = function (event) {
var id = event.data,
action = channelTasks[id];
action();
delete channelTasks[id];
};
scheduleMethod = function (action) {
var id = channelTaskId++;
channelTasks[id] = action;
channel.port2.postMessage(id);
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
scriptElement.onreadystatechange = function () {
action();
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
};
} else {
scheduleMethod = function (action) { return setTimeout(action, 0); };
clearMethod = clearTimeout;
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this,
dt = Scheduler.normalize(dueTime);
if (dt === 0) {
return scheduler.scheduleWithState(state, action);
}
var disposable = new SingleAssignmentDisposable();
var id = setTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
clearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
/** @private */
var CatchScheduler = (function (_super) {
function localNow() {
return this._scheduler.now();
}
function scheduleNow(state, action) {
return this._scheduler.scheduleWithState(state, this._wrap(action));
}
function scheduleRelative(state, dueTime, action) {
return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action));
}
function scheduleAbsolute(state, dueTime, action) {
return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action));
}
inherits(CatchScheduler, _super);
/** @private */
function CatchScheduler(scheduler, handler) {
this._scheduler = scheduler;
this._handler = handler;
this._recursiveOriginal = null;
this._recursiveWrapper = null;
_super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}
/** @private */
CatchScheduler.prototype._clone = function (scheduler) {
return new CatchScheduler(scheduler, this._handler);
};
/** @private */
CatchScheduler.prototype._wrap = function (action) {
var parent = this;
return function (self, state) {
try {
return action(parent._getRecursiveWrapper(self), state);
} catch (e) {
if (!parent._handler(e)) { throw e; }
return disposableEmpty;
}
};
};
/** @private */
CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {
if (this._recursiveOriginal !== scheduler) {
this._recursiveOriginal = scheduler;
var wrapper = this._clone(scheduler);
wrapper._recursiveOriginal = scheduler;
wrapper._recursiveWrapper = wrapper;
this._recursiveWrapper = wrapper;
}
return this._recursiveWrapper;
};
/** @private */
CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) {
var self = this, failed = false, d = new SingleAssignmentDisposable();
d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) {
if (failed) { return null; }
try {
return action(state1);
} catch (e) {
failed = true;
if (!self._handler(e)) { throw e; }
d.dispose();
return null;
}
}));
return d;
};
return CatchScheduler;
}(Scheduler));
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, hasValue) {
this.hasValue = hasValue == null ? false : hasValue;
this.kind = kind;
}
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
return observerOrOnNext && typeof observerOrOnNext === 'object' ?
this._acceptObservable(observerOrOnNext) :
this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notifications
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
Notification.prototype.toObservable = function (scheduler) {
var notification = this;
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
notification._acceptObservable(observer);
notification.kind === 'N' && observer.onCompleted();
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept (onNext) { return onNext(this.value); }
function _acceptObservable(observer) { return observer.onNext(this.value); }
function toString () { return 'OnNext(' + this.value + ')'; }
return function (value) {
var notification = new Notification('N', true);
notification.value = value;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) { return onError(this.exception); }
function _acceptObservable(observer) { return observer.onError(this.exception); }
function toString () { return 'OnError(' + this.exception + ')'; }
return function (exception) {
var notification = new Notification('E');
notification.exception = exception;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) { return onCompleted(); }
function _acceptObservable(observer) { return observer.onCompleted(); }
function toString () { return 'OnCompleted()'; }
return function () {
var notification = new Notification('C');
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
var Enumerator = Rx.internals.Enumerator = function (next) {
this._next = next;
};
Enumerator.prototype.next = function () {
return this._next();
};
Enumerator.prototype[$iterator$] = function () { return this; }
var Enumerable = Rx.internals.Enumerable = function (iterator) {
this._iterator = iterator;
};
Enumerable.prototype[$iterator$] = function () {
return this._iterator();
};
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch(err) {
observer.onError();
return;
}
var isDisposed,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
var currentItem;
if (isDisposed) { return; }
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
observer.onCompleted();
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () { self(); })
);
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchException = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch(err) {
observer.onError();
return;
}
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
var currentItem;
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
if (lastException) {
observer.onError(lastException);
} else {
observer.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
function (exn) {
lastException = exn;
self();
},
observer.onCompleted.bind(observer)));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
if (repeatCount == null) { repeatCount = -1; }
return new Enumerable(function () {
var left = repeatCount;
return new Enumerator(function () {
if (left === 0) { return doneEnumerator; }
if (left > 0) { left--; }
return { done: false, value: value };
});
});
};
var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) {
selector || (selector = identity);
return new Enumerable(function () {
var index = -1;
return new Enumerator(
function () {
return ++index < source.length ?
{ done: false, value: selector.call(thisArg, source[index], index, source) } :
doneEnumerator;
});
});
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
*
* @param observer Observer object.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) {
return n.accept(observer);
};
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
};
/**
* Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
* If a violation is detected, an Error is thrown from the offending observer method call.
*
* @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
*/
Observer.prototype.checked = function () { return new CheckedObserver(this); };
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
*
* @static
* @memberOf Observer
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Creates an observer from a notification callback.
*
* @static
* @memberOf Observer
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler) {
return new AnonymousObserver(function (x) {
return handler(notificationCreateOnNext(x));
}, function (exception) {
return handler(notificationCreateOnError(exception));
}, function () {
return handler(notificationCreateOnCompleted());
});
};
/**
* Schedules the invocation of observer methods on the given scheduler.
* @param {Scheduler} scheduler Scheduler to schedule observer messages on.
* @returns {Observer} Observer whose messages are scheduled on the given scheduler.
*/
Observer.notifyOn = function (scheduler) {
return new ObserveOnObserver(scheduler, this);
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) {
inherits(AbstractObserver, _super);
/**
* Creates a new observer in a non-stopped state.
*
* @constructor
*/
function AbstractObserver() {
this.isStopped = false;
_super.call(this);
}
/**
* Notifies the observer of a new element in the sequence.
*
* @memberOf AbstractObserver
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) {
this.next(value);
}
};
/**
* Notifies the observer that an exception has occurred.
*
* @memberOf AbstractObserver
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (_super) {
inherits(AnonymousObserver, _super);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
_super.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (exception) {
this._onError(exception);
};
/**
* Calls the onCompleted action.
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var CheckedObserver = (function (_super) {
inherits(CheckedObserver, _super);
function CheckedObserver(observer) {
_super.call(this);
this._observer = observer;
this._state = 0; // 0 - idle, 1 - busy, 2 - done
}
var CheckedObserverPrototype = CheckedObserver.prototype;
CheckedObserverPrototype.onNext = function (value) {
this.checkAccess();
try {
this._observer.onNext(value);
} catch (e) {
throw e;
} finally {
this._state = 0;
}
};
CheckedObserverPrototype.onError = function (err) {
this.checkAccess();
try {
this._observer.onError(err);
} catch (e) {
throw e;
} finally {
this._state = 2;
}
};
CheckedObserverPrototype.onCompleted = function () {
this.checkAccess();
try {
this._observer.onCompleted();
} catch (e) {
throw e;
} finally {
this._state = 2;
}
};
CheckedObserverPrototype.checkAccess = function () {
if (this._state === 1) { throw new Error('Re-entrancy detected'); }
if (this._state === 2) { throw new Error('Observer completed'); }
if (this._state === 0) { this._state = 1; }
};
return CheckedObserver;
}(Observer));
var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) {
inherits(ScheduledObserver, _super);
function ScheduledObserver(scheduler, observer) {
_super.call(this);
this.scheduler = scheduler;
this.observer = observer;
this.isAcquired = false;
this.hasFaulted = false;
this.queue = [];
this.disposable = new SerialDisposable();
}
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () {
self.observer.onNext(value);
});
};
ScheduledObserver.prototype.error = function (exception) {
var self = this;
this.queue.push(function () {
self.observer.onError(exception);
});
};
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () {
self.observer.onCompleted();
});
};
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false, parent = this;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
try {
work();
} catch (ex) {
parent.queue = [];
parent.hasFaulted = true;
throw ex;
}
self();
}));
}
};
ScheduledObserver.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
/** @private */
var ObserveOnObserver = (function (_super) {
inherits(ObserveOnObserver, _super);
/** @private */
function ObserveOnObserver() {
_super.apply(this, arguments);
}
/** @private */
ObserveOnObserver.prototype.next = function (value) {
_super.prototype.next.call(this, value);
this.ensureActive();
};
/** @private */
ObserveOnObserver.prototype.error = function (e) {
_super.prototype.error.call(this, e);
this.ensureActive();
};
/** @private */
ObserveOnObserver.prototype.completed = function () {
_super.prototype.completed.call(this);
this.ensureActive();
};
return ObserveOnObserver;
})(ScheduledObserver);
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
function Observable(subscribe) {
this._subscribe = subscribe;
}
observableProto = Observable.prototype;
/**
* Subscribes an observer to the observable sequence.
*
* @example
* 1 - source.subscribe();
* 2 - source.subscribe(observer);
* 3 - source.subscribe(function (x) { console.log(x); });
* 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); });
* 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); });
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
var subscriber = typeof observerOrOnNext === 'object' ?
observerOrOnNext :
observerCreate(observerOrOnNext, onError, onCompleted);
return this._subscribe(subscriber);
};
return Observable;
})();
/**
* Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
*
* This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
* that require to be run on a scheduler, use subscribeOn.
*
* @param {Scheduler} scheduler Scheduler to notify observers on.
* @returns {Observable} The source sequence whose observations happen on the specified scheduler.
*/
observableProto.observeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(new ObserveOnObserver(scheduler, observer));
});
};
/**
* Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
* see the remarks section for more information on the distinction between subscribeOn and observeOn.
* This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
* callbacks on a scheduler, use observeOn.
* @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
* @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
d.setDisposable(m);
m.setDisposable(scheduler.schedule(function () {
d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer)));
}));
return d;
});
};
/**
* Converts a Promise to an Observable sequence
* @param {Promise} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise) {
return new AnonymousObservable(function (observer) {
promise.then(
function (value) {
observer.onNext(value);
observer.onCompleted();
},
function (reason) {
observer.onError(reason);
});
return function () {
if (promise && promise.abort) {
promise.abort();
}
}
});
};
/*
* Converts an existing observable sequence to an ES6 Compatible Promise
* @example
* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
*
* // With config
* Rx.config.Promise = RSVP.Promise;
* var promise = Rx.Observable.return(42).toPromise();
* @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
* @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
*/
observableProto.toPromise = function (promiseCtor) {
promiseCtor || (promiseCtor = Rx.config.Promise);
if (!promiseCtor) {
throw new Error('Promise type not provided nor in Rx.config.Promise');
}
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, function (err) {
reject(err);
}, function () {
if (hasValue) {
resolve(value);
}
});
});
};
/**
* Creates a list from an observable sequence.
* @returns An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
var self = this;
return new AnonymousObservable(function(observer) {
var arr = [];
return self.subscribe(
arr.push.bind(arr),
observer.onError.bind(observer),
function () {
observer.onNext(arr);
observer.onCompleted();
});
});
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
*
* @example
* var res = Rx.Observable.create(function (observer) { return function () { } );
* var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* var res = Rx.Observable.create(function (observer) { } );
*
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = Observable.createWithDisposable = function (subscribe) {
return new AnonymousObservable(subscribe);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
isPromise(result) && (result = observableFromPromise(result));
return result.subscribe(observer);
});
};
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onCompleted();
});
});
};
var maxSafeInteger = Math.pow(2, 53) - 1;
function numberIsFinite(value) {
return typeof value === 'number' && root.isFinite(value);
}
function isNan(n) {
return n !== n;
}
function isIterable(o) {
return o[$iterator$] !== undefined;
}
function sign(value) {
var number = +value;
if (number === 0) { return number; }
if (isNaN(number)) { return number; }
return number < 0 ? -1 : 1;
}
function toLength(o) {
var len = +o.length;
if (isNaN(len)) { return 0; }
if (len === 0 || !numberIsFinite(len)) { return len; }
len = sign(len) * Math.floor(Math.abs(len));
if (len <= 0) { return 0; }
if (len > maxSafeInteger) { return maxSafeInteger; }
return len;
}
function isCallable(f) {
return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function';
}
/**
* This method creates a new Observable sequence from an array-like or iterable object.
* @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
* @param {Function} [mapFn] Map function to call on every element of the array.
* @param {Any} [thisArg] The context to use calling the mapFn if provided.
* @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
*/
Observable.from = function (iterable, mapFn, thisArg, scheduler) {
if (iterable == null) {
throw new Error('iterable cannot be null.')
}
if (mapFn && !isCallable(mapFn)) {
throw new Error('mapFn when provided must be a function');
}
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var list = Object(iterable),
objIsIterable = isIterable(list),
len = objIsIterable ? 0 : toLength(list),
it = objIsIterable ? list[$iterator$]() : null,
i = 0;
return scheduler.scheduleRecursive(function (self) {
if (i < len || objIsIterable) {
var result;
if (objIsIterable) {
var next = it.next();
if (next.done) {
observer.onCompleted();
return;
}
result = next.value;
} else {
result = list[i];
}
if (mapFn && isCallable(mapFn)) {
try {
result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i);
} catch (e) {
observer.onError(e);
return;
}
}
observer.onNext(result);
i++;
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
*
* @example
* var res = Rx.Observable.fromArray([1,2,3]);
* var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var count = 0, len = array.length;
return scheduler.scheduleRecursive(function (self) {
if (count < len) {
observer.onNext(array[count++]);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
* @returns {Observable} The generated sequence.
*/
Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var first = true, state = initialState;
return scheduler.scheduleRecursive(function (self) {
var hasResult, result;
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
}
} catch (exception) {
observer.onError(exception);
return;
}
if (hasResult) {
observer.onNext(result);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new AnonymousObservable(function () {
return disposableEmpty;
});
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @example
* var res = Rx.Observable.of(1,2,3);
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.of = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return observableFromArray(args);
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @example
* var res = Rx.Observable.of(1,2,3);
* @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
var observableOf = Observable.ofWithScheduler = function (scheduler) {
var len = arguments.length - 1, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; }
return observableFromArray(args, scheduler);
};
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.range(0, 10);
* var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout);
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleRecursiveWithState(0, function (i, self) {
if (i < count) {
observer.onNext(start + i);
self(i + 1);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.repeat(42);
* var res = Rx.Observable.repeat(42, 4);
* 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'just', and 'returnValue' for browsers <IE9.
*
* @example
* var res = Rx.Observable.return(42);
* var res = Rx.Observable.return(42, Rx.Scheduler.timeout);
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.returnValue = Observable.just = function (value, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onNext(value);
observer.onCompleted();
});
});
};
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwException' for browsers <IE9.
*
* @example
* var res = Rx.Observable.throw(new Error('Error'));
* var res = Rx.Observable.throw(new Error('Error'), Rx.Scheduler.timeout);
* @param {Mixed} exception An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(exception);
});
});
};
/**
* Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
*
* @example
* var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; });
* @param {Function} resourceFactory Factory function to obtain a resource object.
* @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
* @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
Observable.using = function (resourceFactory, observableFactory) {
return new AnonymousObservable(function (observer) {
var disposable = disposableEmpty, resource, source;
try {
resource = resourceFactory();
if (resource) {
disposable = resource;
}
source = observableFactory(resource);
} catch (exception) {
return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable);
}
return new CompositeDisposable(source.subscribe(observer), disposable);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
* @param {Observable} rightSource Second observable sequence or Promise.
* @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
*/
observableProto.amb = function (rightSource) {
var leftSource = this;
return new AnonymousObservable(function (observer) {
var choice,
leftChoice = 'L', rightChoice = 'R',
leftSubscription = new SingleAssignmentDisposable(),
rightSubscription = new SingleAssignmentDisposable();
isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
function choiceL() {
if (!choice) {
choice = leftChoice;
rightSubscription.dispose();
}
}
function choiceR() {
if (!choice) {
choice = rightChoice;
leftSubscription.dispose();
}
}
leftSubscription.setDisposable(leftSource.subscribe(function (left) {
choiceL();
if (choice === leftChoice) {
observer.onNext(left);
}
}, function (err) {
choiceL();
if (choice === leftChoice) {
observer.onError(err);
}
}, function () {
choiceL();
if (choice === leftChoice) {
observer.onCompleted();
}
}));
rightSubscription.setDisposable(rightSource.subscribe(function (right) {
choiceR();
if (choice === rightChoice) {
observer.onNext(right);
}
}, function (err) {
choiceR();
if (choice === rightChoice) {
observer.onError(err);
}
}, function () {
choiceR();
if (choice === rightChoice) {
observer.onCompleted();
}
}));
return new CompositeDisposable(leftSubscription, rightSubscription);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
*
* @example
* var = Rx.Observable.amb(xs, ys, zs);
* @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
*/
Observable.amb = function () {
var acc = observableNever(),
items = argsOrArray(arguments, 0);
function func(previous, current) {
return previous.amb(current);
}
for (var i = 0, len = items.length; i < len; i++) {
acc = func(acc, items[i]);
}
return acc;
};
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (observer) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) {
var d, result;
try {
result = handler(exception);
} catch (ex) {
observer.onError(ex);
return;
}
isPromise(result) && (result = observableFromPromise(result));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(observer));
}, observer.onCompleted.bind(observer)));
return subscription;
});
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) {
return typeof handlerOrSecond === 'function' ?
observableCatchHandler(this, handlerOrSecond) :
observableCatch([this, handlerOrSecond]);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.catchException(xs, ys, zs);
* 2 - res = Rx.Observable.catchException([xs, ys, zs]);
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchException = Observable['catch'] = function () {
var items = argsOrArray(arguments, 0);
return enumerableFor(items).catchException();
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var args = slice.call(arguments);
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var args = slice.call(arguments), resultSelector = args.pop();
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
}
function done (i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
}(idx));
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
*
* @example
* 1 - concatenated = xs.concat(ys, zs);
* 2 - concatenated = xs.concat([ys, zs]);
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
var items = slice.call(arguments, 0);
items.unshift(this);
return observableConcat.apply(this, items);
};
/**
* Concatenates all the observable sequences.
*
* @example
* 1 - res = Rx.Observable.concat(xs, ys, zs);
* 2 - res = Rx.Observable.concat([xs, ys, zs]);
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
var sources = argsOrArray(arguments, 0);
return enumerableFor(sources).concat();
};
/**
* Concatenates an observable sequence of observable sequences.
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatObservable = observableProto.concatAll =function () {
return this.merge(1);
};
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
if (typeof maxConcurrentOrOther !== 'number') {
return observableMerge(this, maxConcurrentOrOther);
}
var sources = this;
return new AnonymousObservable(function (observer) {
var activeCount = 0,
group = new CompositeDisposable(),
isStopped = false,
q = [],
subscribe = function (xs) {
var subscription = new SingleAssignmentDisposable();
group.add(subscription);
// Check for promises support
if (isPromise(xs)) { xs = observableFromPromise(xs); }
subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () {
var s;
group.remove(subscription);
if (q.length > 0) {
s = q.shift();
subscribe(s);
} else {
activeCount--;
if (isStopped && activeCount === 0) {
observer.onCompleted();
}
}
}));
};
group.add(sources.subscribe(function (innerSource) {
if (activeCount < maxConcurrentOrOther) {
activeCount++;
subscribe(innerSource);
} else {
q.push(innerSource);
}
}, observer.onError.bind(observer), function () {
isStopped = true;
if (activeCount === 0) {
observer.onCompleted();
}
}));
return group;
});
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
*
* @example
* 1 - merged = Rx.Observable.merge(xs, ys, zs);
* 2 - merged = Rx.Observable.merge([xs, ys, zs]);
* 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs);
* 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]);
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources;
if (!arguments[0]) {
scheduler = immediateScheduler;
sources = slice.call(arguments, 1);
} else if (arguments[0].now) {
scheduler = arguments[0];
sources = slice.call(arguments, 1);
} else {
scheduler = immediateScheduler;
sources = slice.call(arguments, 0);
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableFromArray(sources, scheduler).mergeObservable();
};
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeObservable = observableProto.mergeAll =function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable(),
isStopped = false,
m = new SingleAssignmentDisposable();
group.add(m);
m.setDisposable(sources.subscribe(function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
// Check if Promise or Observable
if (isPromise(innerSource)) {
innerSource = observableFromPromise(innerSource);
}
innerSubscription.setDisposable(innerSource.subscribe(function (x) {
observer.onNext(x);
}, observer.onError.bind(observer), function () {
group.remove(innerSubscription);
if (isStopped && group.length === 1) { observer.onCompleted(); }
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
if (group.length === 1) { observer.onCompleted(); }
}));
return group;
});
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
* @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.
* @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.
*/
observableProto.onErrorResumeNext = function (second) {
if (!second) {
throw new Error('Second observable is required');
}
return onErrorResumeNext([this, second]);
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs);
* 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]);
* @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.
*/
var onErrorResumeNext = Observable.onErrorResumeNext = function () {
var sources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var pos = 0, subscription = new SerialDisposable(),
cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, d;
if (pos < sources.length) {
current = sources[pos++];
isPromise(current) && (current = observableFromPromise(current));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () {
self();
}, function () {
self();
}));
} else {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
isOpen && observer.onNext(left);
}, observer.onError.bind(observer), function () {
isOpen && observer.onCompleted();
}));
isPromise(other) && (other = observableFromPromise(other));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, observer.onError.bind(observer), function () {
rightSubscription.dispose();
}));
return disposables;
});
};
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasLatest = false,
innerSubscription = new SerialDisposable(),
isStopped = false,
latest = 0,
subscription = sources.subscribe(function (innerSource) {
var d = new SingleAssignmentDisposable(), id = ++latest;
hasLatest = true;
innerSubscription.setDisposable(d);
// Check if Promise or Observable
if (isPromise(innerSource)) {
innerSource = observableFromPromise(innerSource);
}
d.setDisposable(innerSource.subscribe(function (x) {
if (latest === id) {
observer.onNext(x);
}
}, function (e) {
if (latest === id) {
observer.onError(e);
}
}, function () {
if (latest === id) {
hasLatest = false;
if (isStopped) {
observer.onCompleted();
}
}
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
if (!hasLatest) {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, innerSubscription);
});
};
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
isPromise(other) && (other = observableFromPromise(other));
return new CompositeDisposable(
source.subscribe(observer),
other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop)
);
});
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], result;
try {
result = resultSelector(left, right);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
} else {
observer.onCompleted();
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
}
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources.
*
* @example
* 1 - res = obs1.zip(obs2, fn);
* 1 - res = x1.zip([1,2,3], fn);
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.zip = function () {
if (Array.isArray(arguments[0])) {
return zipArray.apply(this, arguments);
}
var parent = this, sources = slice.call(arguments), resultSelector = sources.pop();
sources.unshift(parent);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
var res, queuedValues;
if (queues.every(function (x) { return x.length > 0; })) {
try {
queuedValues = queues.map(function (x) { return x.shift(); });
res = resultSelector.apply(parent, queuedValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = sources[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
var args = slice.call(arguments, 0),
first = args.shift();
return first.zip.apply(first, args);
};
/**
* Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
* @param arguments Observable sources.
* @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
*/
Observable.zipArray = function () {
var sources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
if (queues.every(function (x) { return x.length > 0; })) {
var res = queues.map(function (x) { return x.shift(); });
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
return;
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
return;
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
})(idx);
}
var compositeDisposable = new CompositeDisposable(subscriptions);
compositeDisposable.add(disposableCreate(function () {
for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) {
queues[qIdx] = [];
}
}));
return compositeDisposable;
});
};
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(observer);
});
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
*
* @example
* var res = xs.bufferWithCount(10);
* var res = xs.bufferWithCount(10, 1);
* @param {Number} count Length of each buffer.
* @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithCount = function (count, skip) {
if (typeof skip !== 'number') {
skip = count;
}
return this.windowWithCount(count, skip).selectMany(function (x) {
return x.toArray();
}).where(function (x) {
return x.length > 0;
});
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
return x.accept(observer);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
*
* var obs = observable.distinctUntilChanged();
* var obs = observable.distinctUntilChanged(function (x) { return x.id; });
* var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
*
* @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keySelector, comparer) {
var source = this;
keySelector || (keySelector = identity);
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var comparerEquals = false, key;
try {
key = keySelector(value);
} catch (exception) {
observer.onError(exception);
return;
}
if (hasCurrentKey) {
try {
comparerEquals = comparer(currentKey, key);
} catch (exception) {
observer.onError(exception);
return;
}
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
*
* @example
* var res = observable.do(observer);
* var res = observable.do(onNext);
* var res = observable.do(onNext, onError);
* var res = observable.do(onNext, onError, onCompleted);
* @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) {
var source = this, onNextFunc;
if (typeof observerOrOnNext === 'function') {
onNextFunc = observerOrOnNext;
} else {
onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext);
onError = observerOrOnNext.onError.bind(observerOrOnNext);
onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext);
}
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
try {
onNextFunc(x);
} catch (e) {
observer.onError(e);
}
observer.onNext(x);
}, function (err) {
if (!onError) {
observer.onError(err);
} else {
try {
onError(err);
} catch (e) {
observer.onError(e);
}
observer.onError(err);
}
}, function () {
if (!onCompleted) {
observer.onCompleted();
} else {
try {
onCompleted();
} catch (e) {
observer.onError(e);
}
observer.onCompleted();
}
});
});
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
*
* @example
* var res = observable.finallyAction(function () { console.log('sequence ended'; });
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto['finally'] = observableProto.finallyAction = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription;
try {
subscription = source.subscribe(observer);
} catch (e) {
action();
throw e;
}
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
});
};
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (e) {
observer.onNext(notificationCreateOnError(e));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
});
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
*
* @example
* var res = repeated = source.repeat();
* var res = repeated = source.repeat(42);
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
* Note if you encounter an error and want it to retry once, then you must use .retry(2);
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(2);
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchException();
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @example
* var res = source.scan(function (acc, x) { return acc + x; });
* var res = source.scan(0, function (acc, x) { return acc + x; });
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (observer) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
try {
if (!hasValue) {
hasValue = true;
}
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(accumulation);
},
observer.onError.bind(observer),
function () {
if (!hasValue && hasSeed) {
observer.onNext(seed);
}
observer.onCompleted();
}
);
});
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
* @description
* This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
if (q.length > count) {
observer.onNext(q.shift());
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
*
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
*
* @memberOf Observable#
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && 'now' in Object(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
values = slice.call(arguments, start);
return enumerableFor([observableFromArray(values, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence.
*
* @example
* var res = source.takeLast(5);
*
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, observer.onError.bind(observer), function () {
while(q.length > 0) { observer.onNext(q.shift()); }
observer.onCompleted();
});
});
};
/**
* Returns an array with the specified number of contiguous elements from the end of an observable sequence.
*
* @description
* This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
* source sequence, this buffer is produced on the result sequence.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
*/
observableProto.takeLastBuffer = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, observer.onError.bind(observer), function () {
observer.onNext(q);
observer.onCompleted();
});
});
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
*
* var res = xs.windowWithCount(10);
* var res = xs.windowWithCount(10, 1);
* @param {Number} count Length of each window.
* @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithCount = function (count, skip) {
var source = this;
if (count <= 0) {
throw new Error(argumentOutOfRange);
}
if (arguments.length === 1) {
skip = count;
}
if (skip <= 0) {
throw new Error(argumentOutOfRange);
}
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(),
refCountDisposable = new RefCountDisposable(m),
n = 0,
q = [],
createWindow = function () {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
};
createWindow();
m.setDisposable(source.subscribe(function (x) {
var s;
for (var i = 0, len = q.length; i < len; i++) {
q[i].onNext(x);
}
var c = n - count + 1;
if (c >= 0 && c % skip === 0) {
s = q.shift();
s.onCompleted();
}
n++;
if (n % skip === 0) {
createWindow();
}
}, function (exception) {
while (q.length > 0) {
q.shift().onError(exception);
}
observer.onError(exception);
}, function () {
while (q.length > 0) {
q.shift().onCompleted();
}
observer.onCompleted();
}));
return refCountDisposable;
});
};
function concatMap(source, selector, thisArg) {
return source.map(function (x, i) {
var result = selector.call(thisArg, x, i);
return isPromise(result) ? observableFromPromise(result) : result;
}).concatAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.concatMap(Rx.Observable.fromArray([1,2,3]));
* @param selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) {
if (resultSelector) {
return this.concatMap(function (x, i) {
var selectorResult = selector(x, i),
result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult;
return result.map(function (y) {
return resultSelector(x, y, i);
});
});
}
return typeof selector === 'function' ?
concatMap(this, selector, thisArg) :
concatMap(this, function () { return selector; });
};
observableProto.concatMapObserver = function(onNext, onError, onCompleted, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNext.call(thisArg, x, index++);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
},
function (err) {
var result;
try {
result = onError.call(thisArg, err);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompleted.call(thisArg);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
observer.onCompleted();
});
}).concatAll();
};
/**
* Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
*
* var res = obs = xs.defaultIfEmpty();
* 2 - obs = xs.defaultIfEmpty(false);
*
* @memberOf Observable#
* @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
* @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
*/
observableProto.defaultIfEmpty = function (defaultValue) {
var source = this;
if (defaultValue === undefined) {
defaultValue = null;
}
return new AnonymousObservable(function (observer) {
var found = false;
return source.subscribe(function (x) {
found = true;
observer.onNext(x);
}, observer.onError.bind(observer), function () {
if (!found) {
observer.onNext(defaultValue);
}
observer.onCompleted();
});
});
};
// Swap out for Array.findIndex
function arrayIndexOfComparer(array, item, comparer) {
for (var i = 0, len = array.length; i < len; i++) {
if (comparer(array[i], item)) { return i; }
}
return -1;
}
function HashSet(comparer) {
this.comparer = comparer;
this.set = [];
}
HashSet.prototype.push = function(value) {
var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1;
retValue && this.set.push(value);
return retValue;
};
/**
* Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
* Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
*
* @example
* var res = obs = xs.distinct();
* 2 - obs = xs.distinct(function (x) { return x.id; });
* 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; });
* @param {Function} [keySelector] A function to compute the comparison key for each element.
* @param {Function} [comparer] Used to compare items in the collection.
* @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
*/
observableProto.distinct = function (keySelector, comparer) {
var source = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
var hashSet = new HashSet(comparer);
return source.subscribe(function (x) {
var key = x;
if (keySelector) {
try {
key = keySelector(x);
} catch (e) {
observer.onError(e);
return;
}
}
hashSet.push(key) && observer.onNext(x);
},
observer.onError.bind(observer),
observer.onCompleted.bind(observer));
});
};
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.select = observableProto.map = function (selector, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var result;
try {
result = selector.call(thisArg, value, count++, parent);
} catch (exception) {
observer.onError(exception);
return;
}
observer.onNext(result);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Retrieves the value of a specified property from all elements in the Observable sequence.
* @param {String} property The property to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function (property) {
return this.select(function (x) { return x[property]; });
};
observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNext.call(thisArg, x, index++);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
},
function (err) {
var result;
try {
result = onError.call(thisArg, err);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompleted.call(thisArg);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
observer.onCompleted();
});
}).mergeAll();
};
function flatMap(source, selector, thisArg) {
return source.map(function (x, i) {
var result = selector.call(thisArg, x, i);
return isPromise(result) ? observableFromPromise(result) : result;
}).mergeObservable();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) {
if (resultSelector) {
return this.flatMap(function (x, i) {
var selectorResult = selector(x, i),
result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult;
return result.map(function (y) {
return resultSelector(x, y, i);
});
}, thisArg);
}
return typeof selector === 'function' ?
flatMap(this, selector, thisArg) :
flatMap(this, function () { return selector; });
};
/**
* Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
* transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
* and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) {
return this.select(selector, thisArg).switchLatest();
};
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) {
throw new Error(argumentOutOfRange);
}
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining <= 0) {
observer.onNext(x);
} else {
remaining--;
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* var res = source.skipWhile(function (value) { return value < 10; });
* var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !predicate.call(thisArg, x, i++, source);
} catch (e) {
observer.onError(e);
return;
}
}
if (running) {
observer.onNext(x);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* var res = source.take(5);
* var res = source.take(0, Rx.Scheduler.timeout);
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) {
throw new Error(argumentOutOfRange);
}
if (count === 0) {
return observableEmpty(scheduler);
}
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining > 0) {
remaining--;
observer.onNext(x);
if (remaining === 0) {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
*
* @example
* var res = source.takeWhile(function (value) { return value < 10; });
* var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var observable = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = true;
return observable.subscribe(function (x) {
if (running) {
try {
running = predicate.call(thisArg, x, i++, observable);
} catch (e) {
observer.onError(e);
return;
}
if (running) {
observer.onNext(x);
} else {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
*
* @example
* var res = source.where(function (value) { return value < 10; });
* var res = source.where(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.where = observableProto.filter = function (predicate, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var shouldRun;
try {
shouldRun = predicate.call(thisArg, value, count++, parent);
} catch (exception) {
observer.onError(exception);
return;
}
if (shouldRun) {
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/*
* Performs a exclusive waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @returns {Observable} A exclusive observable with only the results that happen when subscribed.
*/
observableProto.exclusive = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasCurrent = false,
isStopped = false,
m = new SingleAssignmentDisposable(),
g = new CompositeDisposable();
g.add(m);
m.setDisposable(sources.subscribe(
function (innerSource) {
if (!hasCurrent) {
hasCurrent = true;
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
var innerSubscription = new SingleAssignmentDisposable();
g.add(innerSubscription);
innerSubscription.setDisposable(innerSource.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () {
g.remove(innerSubscription);
hasCurrent = false;
if (isStopped && g.length === 1) {
observer.onCompleted();
}
}));
}
},
observer.onError.bind(observer),
function () {
isStopped = true;
if (!hasCurrent && g.length === 1) {
observer.onCompleted();
}
}));
return g;
});
};
/*
* Performs a exclusive map waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @param {Function} selector Selector to invoke for every item in the current subscription.
* @param {Any} [thisArg] An optional context to invoke with the selector parameter.
* @returns {Observable} An exclusive observable with only the results that happen when subscribed.
*/
observableProto.exclusiveMap = function (selector, thisArg) {
var sources = this;
return new AnonymousObservable(function (observer) {
var index = 0,
hasCurrent = false,
isStopped = true,
m = new SingleAssignmentDisposable(),
g = new CompositeDisposable();
g.add(m);
m.setDisposable(sources.subscribe(
function (innerSource) {
if (!hasCurrent) {
hasCurrent = true;
innerSubscription = new SingleAssignmentDisposable();
g.add(innerSubscription);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(
function (x) {
var result;
try {
result = selector.call(thisArg, x, index++, innerSource);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
},
observer.onError.bind(observer),
function () {
g.remove(innerSubscription);
hasCurrent = false;
if (isStopped && g.length === 1) {
observer.onCompleted();
}
}));
}
},
observer.onError.bind(observer),
function () {
isStopped = true;
if (g.length === 1 && !hasCurrent) {
observer.onCompleted();
}
}));
return g;
});
};
var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
inherits(AnonymousObservable, __super__);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; }
return typeof subscriber === 'function' ?
disposableCreate(subscriber) :
disposableEmpty;
}
function AnonymousObservable(subscribe) {
if (!(this instanceof AnonymousObservable)) {
return new AnonymousObservable(subscribe);
}
function s(observer) {
var setDisposable = function () {
try {
autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
};
var autoDetachObserver = new AutoDetachObserver(observer);
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.schedule(setDisposable);
} else {
setDisposable();
}
return autoDetachObserver;
}
__super__.call(this, s);
}
return AnonymousObservable;
}(Observable));
/** @private */
var AutoDetachObserver = (function (_super) {
inherits(AutoDetachObserver, _super);
function AutoDetachObserver(observer) {
_super.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var noError = false;
try {
this.observer.onNext(value);
noError = true;
} catch (e) {
throw e;
} finally {
if (!noError) {
this.dispose();
}
}
};
AutoDetachObserverPrototype.error = function (exn) {
try {
this.observer.onError(exn);
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.completed = function () {
try {
this.observer.onCompleted();
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); };
/* @private */
AutoDetachObserverPrototype.disposable = function (value) {
return arguments.length ? this.getDisposable() : setDisposable(value);
};
AutoDetachObserverPrototype.dispose = function () {
_super.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
/** @private */
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
/**
* @private
* @memberOf InnerSubscription
*/
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.exception) {
observer.onError(this.exception);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, _super);
/**
* Creates a subject.
* @constructor
*/
function Subject() {
_super.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
}
addProperties(Subject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
for (var i = 0, len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
var ex = this.exception,
hv = this.hasValue,
v = this.value;
if (ex) {
observer.onError(ex);
} else if (hv) {
observer.onNext(v);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, _super);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
* @constructor
*/
function AsyncSubject() {
_super.call(this, subscribe);
this.isDisposed = false;
this.isStopped = false;
this.value = null;
this.hasValue = false;
this.observers = [];
this.exception = null;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
checkDisposed.call(this);
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*/
onCompleted: function () {
var o, i, len;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
var os = this.observers.slice(0),
v = this.value,
hv = this.hasValue;
if (hv) {
for (i = 0, len = os.length; i < len; i++) {
o = os[i];
o.onNext(v);
o.onCompleted();
}
} else {
for (i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
this.value = value;
this.hasValue = true;
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.exception = null;
this.value = null;
}
});
return AsyncSubject;
}(Observable));
var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) {
inherits(AnonymousSubject, __super__);
function AnonymousSubject(observer, observable) {
this.observer = observer;
this.observable = observable;
__super__.call(this, this.observable.subscribe.bind(this.observable));
}
addProperties(AnonymousSubject.prototype, Observer, {
onCompleted: function () {
this.observer.onCompleted();
},
onError: function (exception) {
this.observer.onError(exception);
},
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
root.Rx = Rx;
define(function() {
return Rx;
});
} else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = Rx).Rx = Rx;
} else {
freeExports.Rx = Rx;
}
} else {
// in a browser or Rhino
root.Rx = Rx;
}
}.call(this));
|
src/common/SpellIcon.js
|
mwwscott0/WoWAnalyzer
|
import React from 'react';
import PropTypes from 'prop-types';
import SPELLS from './SPELLS';
import SpellLink from './SpellLink';
import Icon from './Icon';
const SpellIcon = ({ id, noLink, ...others }) => {
if (process.env.NODE_ENV === 'development' && !SPELLS[id]) {
throw new Error(`Unknown spell: ${id}`);
}
const icon = (
<Icon
icon={SPELLS[id].icon}
alt={SPELLS[id].name}
{...others}
/>
);
if (noLink) {
return icon;
}
return (
<SpellLink id={id}>
{icon}
</SpellLink>
);
};
SpellIcon.propTypes = {
id: PropTypes.number.isRequired,
noLink: PropTypes.bool,
};
export default SpellIcon;
|
src/config/client.js
|
nightwolfz/mobx-starter
|
// This is the entry point for our client-side logic
import '../assets/css/index.scss'
import 'isomorphic-fetch'
import 'core/polyfills'
import 'core/logger'
import React from 'react'
import { render } from 'react-dom'
import { AppContainer } from 'react-hot-loader'
import { BrowserRouter } from 'react-router-dom'
import state from '../stores/State'
import autorun from './autorun'
import createContext from './context'
import routes from './routes'
import Index from '../pages/Index'
// We render our react app into this element
const container = document.getElementById('container')
const context = createContext(state)
// React to changes
autorun(context)
// Render HTML on the browser
render(<AppContainer>
<BrowserRouter>
<Index {...context}>
{routes}
</Index>
</BrowserRouter>
</AppContainer>, container)
if (process.env.NODE_ENV !== 'production') {
require('mobx-logger').enableLogging({
action: true,
reaction: false,
transaction: true,
compute: false
})
}
// Hot-reloading
if (module.hot) {
module.hot.accept()
}
|
packages/playground/stories/AreaUnits.story.js
|
appearhere/bloom
|
import React from 'react';
import { storiesOf } from '@storybook/react';
import { AreaUnits } from '@appearhere/bloom';
storiesOf('AreaUnits', module)
.add('Square foot', () => <AreaUnits value="300" unit="sqft" />)
.add('Meters squared', () => <AreaUnits value="300" unit="m2" />);
|
ajax/libs/redux-form/5.2.1/redux-form.min.js
|
jdh8/cdnjs
|
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("react")):"function"==typeof define&&define.amd?define(["react"],e):"object"==typeof exports?exports.ReduxForm=e(require("react")):t.ReduxForm=e(t.React)}(this,function(t){return function(t){function e(n){if(r[n])return r[n].exports;var i=r[n]={exports:{},id:n,loaded:!1};return t[n].call(i.exports,i,i.exports,e),i.loaded=!0,i.exports}var r={};return e.m=t,e.c=r,e.p="",e(0)}([function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0,e.untouchWithKey=e.untouch=e.touchWithKey=e.touch=e.swapArrayValues=e.stopSubmit=e.stopAsyncValidation=e.startSubmit=e.startAsyncValidation=e.reset=e.propTypes=e.initializeWithKey=e.initialize=e.getValues=e.removeArrayValue=e.reduxForm=e.reducer=e.focus=e.destroy=e.changeWithKey=e.change=e.blur=e.autofillWithKey=e.autofill=e.addArrayValue=e.actionTypes=void 0;var i=r(3),o=n(i),u=r(58),a=r(28),s=n(a),f="undefined"!=typeof window&&window.navigator&&window.navigator.product&&"ReactNative"===window.navigator.product,c=(0,s.default)(f,o.default,u.connect),l=c.actionTypes,d=c.addArrayValue,p=c.autofill,h=c.autofillWithKey,y=c.blur,v=c.change,b=c.changeWithKey,m=c.destroy,g=c.focus,_=c.reducer,O=c.reduxForm,A=c.removeArrayValue,w=c.getValues,P=c.initialize,S=c.initializeWithKey,j=c.propTypes,V=c.reset,T=c.startAsyncValidation,E=c.startSubmit,R=c.stopAsyncValidation,x=c.stopSubmit,M=c.swapArrayValues,F=c.touch,C=c.touchWithKey,k=c.untouch,I=c.untouchWithKey;e.actionTypes=l,e.addArrayValue=d,e.autofill=p,e.autofillWithKey=h,e.blur=y,e.change=v,e.changeWithKey=b,e.destroy=m,e.focus=g,e.reducer=_,e.reduxForm=O,e.removeArrayValue=A,e.getValues=w,e.initialize=P,e.initializeWithKey=S,e.propTypes=j,e.reset=V,e.startAsyncValidation=T,e.startSubmit=E,e.stopAsyncValidation=R,e.stopSubmit=x,e.swapArrayValues=M,e.touch=F,e.touchWithKey=C,e.untouch=k,e.untouchWithKey=I},function(t,e){"use strict";function r(t){return t&&o(t)&&Object.defineProperty(t,i,{value:!0}),t}function n(t){return!!(t&&o(t)&&t[i])}e.__esModule=!0,e.makeFieldValue=r,e.isFieldValue=n;var i="_isFieldValue",o=function(t){return"object"==typeof t}},function(t,e){"use strict";function r(t){return Array.isArray(t)?t.reduce(function(t,e){return t&&r(e)},!0):t&&"object"==typeof t?Object.keys(t).reduce(function(e,n){return e&&r(t[n])},!0):!t}e.__esModule=!0,e.default=r},function(e,r){e.exports=t},function(t,e){"use strict";e.__esModule=!0;e.ADD_ARRAY_VALUE="redux-form/ADD_ARRAY_VALUE",e.AUTOFILL="redux-form/AUTOFILL",e.BLUR="redux-form/BLUR",e.CHANGE="redux-form/CHANGE",e.DESTROY="redux-form/DESTROY",e.FOCUS="redux-form/FOCUS",e.INITIALIZE="redux-form/INITIALIZE",e.REMOVE_ARRAY_VALUE="redux-form/REMOVE_ARRAY_VALUE",e.RESET="redux-form/RESET",e.START_ASYNC_VALIDATION="redux-form/START_ASYNC_VALIDATION",e.START_SUBMIT="redux-form/START_SUBMIT",e.STOP_ASYNC_VALIDATION="redux-form/STOP_ASYNC_VALIDATION",e.STOP_SUBMIT="redux-form/STOP_SUBMIT",e.SUBMIT_FAILED="redux-form/SUBMIT_FAILED",e.SWAP_ARRAY_VALUES="redux-form/SWAP_ARRAY_VALUES",e.TOUCH="redux-form/TOUCH",e.UNTOUCH="redux-form/UNTOUCH"},function(t,e){"use strict";function r(t,e){return t?Object.keys(t).reduce(function(r,i){var o;return n({},r,(o={},o[i]=e(t[i],i),o))},{}):t}e.__esModule=!0;var n=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t};e.default=r},function(t,e){function r(t){return!!t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof t.then}t.exports=r},function(t,e,r){"use strict";e.__esModule=!0,e.untouch=e.touch=e.swapArrayValues=e.submitFailed=e.stopSubmit=e.stopAsyncValidation=e.startSubmit=e.startAsyncValidation=e.reset=e.removeArrayValue=e.initialize=e.focus=e.destroy=e.change=e.blur=e.autofill=e.addArrayValue=void 0;var n=r(4);e.addArrayValue=function(t,e,r,i){return{type:n.ADD_ARRAY_VALUE,path:t,value:e,index:r,fields:i}},e.autofill=function(t,e){return{type:n.AUTOFILL,field:t,value:e}},e.blur=function(t,e){return{type:n.BLUR,field:t,value:e}},e.change=function(t,e){return{type:n.CHANGE,field:t,value:e}},e.destroy=function(){return{type:n.DESTROY}},e.focus=function(t){return{type:n.FOCUS,field:t}},e.initialize=function(t,e){var r=arguments.length<=2||void 0===arguments[2]?!0:arguments[2];if(!Array.isArray(e))throw new Error("must provide fields array to initialize() action creator");return{type:n.INITIALIZE,data:t,fields:e,overwriteValues:r}},e.removeArrayValue=function(t,e){return{type:n.REMOVE_ARRAY_VALUE,path:t,index:e}},e.reset=function(){return{type:n.RESET}},e.startAsyncValidation=function(t){return{type:n.START_ASYNC_VALIDATION,field:t}},e.startSubmit=function(){return{type:n.START_SUBMIT}},e.stopAsyncValidation=function(t){return{type:n.STOP_ASYNC_VALIDATION,errors:t}},e.stopSubmit=function(t){return{type:n.STOP_SUBMIT,errors:t}},e.submitFailed=function(){return{type:n.SUBMIT_FAILED}},e.swapArrayValues=function(t,e,r){return{type:n.SWAP_ARRAY_VALUES,path:t,indexA:e,indexB:r}},e.touch=function(){for(var t=arguments.length,e=Array(t),r=0;t>r;r++)e[r]=arguments[r];return{type:n.TOUCH,fields:e}},e.untouch=function(){for(var t=arguments.length,e=Array(t),r=0;t>r;r++)e[r]=arguments[r];return{type:n.UNTOUCH,fields:e}}},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function i(t,e){return"function"==typeof t?function(){return o({},t.apply(void 0,arguments),e)}:"object"==typeof t?(0,a.default)(t,function(t){return i(t,e)}):t}e.__esModule=!0;var o=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t};e.default=i;var u=r(5),a=n(u)},function(t,e){"use strict";e.__esModule=!0;var r=e.dataKey="value",n=function(t,e){return function(t){t.dataTransfer.setData(r,e())}};e.default=n},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var i=r(11),o=n(i),u=function(t){var e=[];if(t)for(var r=0;r<t.length;r++){var n=t[r];n.selected&&e.push(n.value)}return e},a=function(t,e){if((0,o.default)(t)){if(!e&&t.nativeEvent&&void 0!==t.nativeEvent.text)return t.nativeEvent.text;if(e&&void 0!==t.nativeEvent)return t.nativeEvent.text;var r=t.target,n=r.type,i=r.value,a=r.checked,s=r.files,f=t.dataTransfer;return"checkbox"===n?a:"file"===n?s||f&&f.files:"select-multiple"===n?u(t.target.options):i}return t&&"object"==typeof t&&void 0!==t.value?t.value:t};e.default=a},function(t,e){"use strict";e.__esModule=!0;var r=function(t){return!!(t&&t.stopPropagation&&t.preventDefault)};e.default=r},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var i=r(11),o=n(i),u=function(t){var e=(0,o.default)(t);return e&&t.preventDefault(),e};e.default=u},function(t,e){"use strict";function r(t){return t.displayName||t.name||"Component"}e.__esModule=!0,e.default=r},function(t,e){"use strict";e.__esModule=!0;var r=function(t){var e=t.value,r=t.initialValue;return"undefined"!=typeof e?e:r},n=function o(t,e,n){var i=t.indexOf("."),u=t.indexOf("["),a=t.indexOf("]");if(u>0&&a!==u+1)throw new Error("found [ not followed by ]");if(u>0&&(0>i||i>u))!function(){var i=t.substring(0,u),s=t.substring(a+1);"."===s[0]&&(s=s.substring(1));var f=e&&e[i]||[];s?(n[i]||(n[i]=[]),f.forEach(function(t,e){n[i][e]||(n[i][e]={}),o(s,t,n[i][e])})):n[i]=f.map(r)}();else if(i>0){var s=t.substring(0,i),f=t.substring(i+1);n[s]||(n[s]={}),o(f,e&&e[s]||{},n[s])}else n[t]=e[t]&&r(e[t])},i=function(t,e){return t.reduce(function(t,r){return n(r,e,t),t},{})};e.default=i},function(t,e,r){"use strict";e.__esModule=!0;var n=r(1),i=function o(t){if(!t)return t;var e=Object.keys(t);if(e.length)return e.reduce(function(e,r){var i=t[r];if(i)if(i.hasOwnProperty&&i.hasOwnProperty("value"))void 0!==i.value&&(e[r]=i.value);else if(Array.isArray(i))e[r]=i.map(function(t){return(0,n.isFieldValue)(t)?t.value:o(t)});else if("object"==typeof i){var u=o(i);u&&Object.keys(u).length>0&&(e[r]=u)}return e},{})};e.default=i},function(t,e){"use strict";e.__esModule=!0;var r=function n(t,e){if(!t||!e)return e;var r=t.indexOf(".");if(0===r)return n(t.substring(1),e);var i=t.indexOf("["),o=t.indexOf("]");if(r>=0&&(0>i||i>r))return n(t.substring(r+1),e[t.substring(0,r)]);if(i>=0&&(0>r||r>i)){if(0>o)throw new Error("found [ but no ]");var u=t.substring(0,i),a=t.substring(i+1,o);if(!a.length)return e[u];if(0===i)return n(t.substring(o+1),e[a]);if(!e[u])return;return n(t.substring(o+1),e[u][a])}return e[t]};e.default=r},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function i(t,e){var r={};for(var n in t)e.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n]);return r}function o(){var t,e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],r=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],n=r.form,o=r.key,u=i(r,["form","key"]);if(!n)return e;if(o){var a,s;if(r.type===c.DESTROY){var l;return f({},e,(l={},l[n]=e[n]&&Object.keys(e[n]).reduce(function(t,r){var i;return r===o?t:f({},t,(i={},i[r]=e[n][r],i))},{}),l))}return f({},e,(s={},s[n]=f({},e[n],(a={},a[o]=x((e[n]||{})[o],u),a)),s))}return r.type===c.DESTROY?Object.keys(e).reduce(function(t,r){var i;return r===n?t:f({},t,(i={},i[r]=e[r],i))},{}):f({},e,(t={},t[n]=x(e[n],u),t))}function u(t){return t.plugin=function(t){var e=this;return u(function(){var r=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],n=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],i=e(r,n);return f({},i,(0,d.default)(t,function(t,e){return t(i[e]||E,n)}))})},t.normalize=function(t){var e=this;return u(function(){var r=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],n=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],i=e(r,n);return f({},i,(0,d.default)(t,function(t,e){var o=function(e,r){var n=(0,m.default)(f({},E,e)),i=f({},E,r),o=(0,m.default)(i);return(0,V.default)(t,i,e,o,n)};if(n.key){var u;return f({},i[e],(u={},u[n.key]=o(r[e][n.key],i[e][n.key]),u))}return o(r[e],i[e])}))})},t}e.__esModule=!0,e.initialState=e.globalErrorKey=void 0;var a,s,f=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},c=r(4),l=r(5),d=n(l),p=r(16),h=n(p),y=r(18),v=n(y),b=r(15),m=n(b),g=r(39),_=n(g),O=r(45),A=n(O),w=r(46),P=n(w),S=r(1),j=r(41),V=n(j),T=e.globalErrorKey="_error",E=e.initialState=(a={_active:void 0,_asyncValidating:!1},a[T]=void 0,a._initialized=!1,a._submitting=!1,a._submitFailed=!1,a),R=(s={},s[c.ADD_ARRAY_VALUE]=function(t,e){var r=e.path,n=e.index,i=e.value,o=e.fields,u=(0,h.default)(r,t),a=f({},t),s=u?[].concat(u):[],c=null!==i&&"object"==typeof i?(0,_.default)(i,o||Object.keys(i)):(0,S.makeFieldValue)({value:i});return void 0===n?s.push(c):s.splice(n,0,c),(0,v.default)(r,s,a)},s[c.AUTOFILL]=function(t,e){var r=e.field,n=e.value;return(0,v.default)(r,function(t){var e=f({},t,{value:n,autofilled:!0}),r=(e.asyncError,e.submitError,i(e,["asyncError","submitError"]));return(0,S.makeFieldValue)(r)},t)},s[c.BLUR]=function(t,e){var r=e.field,n=e.value,o=e.touch,u=(t._active,i(t,["_active"]));return(0,v.default)(r,function(t){var e=f({},t);return void 0!==n&&(e.value=n),o&&(e.touched=!0),(0,S.makeFieldValue)(e)},u)},s[c.CHANGE]=function(t,e){var r=e.field,n=e.value,o=e.touch;return(0,v.default)(r,function(t){var e=f({},t,{value:n}),r=(e.asyncError,e.submitError,e.autofilled,i(e,["asyncError","submitError","autofilled"]));return o&&(r.touched=!0),(0,S.makeFieldValue)(r)},t)},s[c.DESTROY]=function(){},s[c.FOCUS]=function(t,e){var r=e.field,n=(0,v.default)(r,function(t){return(0,S.makeFieldValue)(f({},t,{visited:!0}))},t);return n._active=r,n},s[c.INITIALIZE]=function(t,e){var r,n=e.data,i=e.fields,o=e.overwriteValues;return f({},(0,_.default)(n,i,t,o),(r={_asyncValidating:!1,_active:void 0},r[T]=void 0,r._initialized=!0,r._submitting=!1,r._submitFailed=!1,r))},s[c.REMOVE_ARRAY_VALUE]=function(t,e){var r=e.path,n=e.index,i=(0,h.default)(r,t),o=f({},t),u=i?[].concat(i):[];return void 0===n?u.pop():isNaN(n)?delete u[n]:u.splice(n,1),(0,v.default)(r,u,o)},s[c.RESET]=function(t){var e;return f({},(0,A.default)(t),(e={_active:void 0,_asyncValidating:!1},e[T]=void 0,e._initialized=t._initialized,e._submitting=!1,e._submitFailed=!1,e))},s[c.START_ASYNC_VALIDATION]=function(t,e){var r=e.field;return f({},t,{_asyncValidating:r||!0})},s[c.START_SUBMIT]=function(t){return f({},t,{_submitting:!0})},s[c.STOP_ASYNC_VALIDATION]=function(t,e){var r,n=e.errors;return f({},(0,P.default)(t,n,"asyncError"),(r={_asyncValidating:!1},r[T]=n&&n[T],r))},s[c.STOP_SUBMIT]=function(t,e){var r,n=e.errors;return f({},(0,P.default)(t,n,"submitError"),(r={},r[T]=n&&n[T],r._submitting=!1,r._submitFailed=!(!n||!Object.keys(n).length),r))},s[c.SUBMIT_FAILED]=function(t){return f({},t,{_submitFailed:!0})},s[c.SWAP_ARRAY_VALUES]=function(t,e){var r=e.path,n=e.indexA,i=e.indexB,o=(0,h.default)(r,t),u=o.length;if(n===i||isNaN(n)||isNaN(i)||n>=u||i>=u)return t;var a=f({},t),s=[].concat(o);return s[n]=o[i],s[i]=o[n],(0,v.default)(r,s,a)},s[c.TOUCH]=function(t,e){var r=e.fields;return f({},t,r.reduce(function(t,e){return(0,v.default)(e,function(t){return(0,S.makeFieldValue)(f({},t,{touched:!0}))},t)},t))},s[c.UNTOUCH]=function(t,e){var r=e.fields;return f({},t,r.reduce(function(t,e){return(0,v.default)(e,function(t){if(t){var e=(t.touched,i(t,["touched"]));return(0,S.makeFieldValue)(e)}return(0,S.makeFieldValue)(t)},t)},t))},s),x=function(){var t=arguments.length<=0||void 0===arguments[0]?E:arguments[0],e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],r=R[e.type];return r?r(t,e):t};e.default=u(o)},function(t,e){"use strict";e.__esModule=!0;var r=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},n=function i(t,e,n){var o,u=t.indexOf(".");if(0===u)return i(t.substring(1),e,n);var a=t.indexOf("["),s=t.indexOf("]");if(u>=0&&(0>a||a>u)){var f,c=t.substring(0,u);return r({},n,(f={},f[c]=i(t.substring(u+1),e,n[c]||{}),f))}if(a>=0&&(0>u||u>a)){var l=function(){var o;if(0>s)throw new Error("found [ but no ]");var u=t.substring(0,a),f=t.substring(a+1,s),c=n[u]||[],l=t.substring(s+1);if(f){var d;if(l.length){var p,h=c[f]||{},y=[].concat(c);return y[f]=i(l,e,h),{v:r({},n||{},(p={},p[u]=y,p))}}var v=[].concat(c);return v[f]="function"==typeof e?e(v[f]):e,{v:r({},n||{},(d={},d[u]=v,d))}}if(l.length){var b;if(!(c&&c.length||"function"!=typeof e))return{v:n};var m=c.map(function(t){return i(l,e,t)});return{v:r({},n||{},(b={},b[u]=m,b))}}var g=void 0;if(Array.isArray(e))g=e;else if(n[u])g=c.map(function(t){return"function"==typeof e?e(t):e});else{if("function"==typeof e)return{v:n};g=e}return{v:r({},n||{},(o={},o[u]=g,o))}}();if("object"==typeof l)return l.v}return r({},n,(o={},o[t]="function"==typeof e?e(n[t]):e,o))};e.default=n},function(t,e,r){function n(t){return null===t||void 0===t}function i(t){return t&&"object"==typeof t&&"number"==typeof t.length?"function"!=typeof t.copy||"function"!=typeof t.slice?!1:!(t.length>0&&"number"!=typeof t[0]):!1}function o(t,e,r){var o,c;if(n(t)||n(e))return!1;if(t.prototype!==e.prototype)return!1;if(s(t))return s(e)?(t=u.call(t),e=u.call(e),f(t,e,r)):!1;if(i(t)){if(!i(e))return!1;if(t.length!==e.length)return!1;for(o=0;o<t.length;o++)if(t[o]!==e[o])return!1;return!0}try{var l=a(t),d=a(e)}catch(p){return!1}if(l.length!=d.length)return!1;for(l.sort(),d.sort(),o=l.length-1;o>=0;o--)if(l[o]!=d[o])return!1;for(o=l.length-1;o>=0;o--)if(c=l[o],!f(t[c],e[c],r))return!1;return typeof t==typeof e}var u=Array.prototype.slice,a=r(52),s=r(51),f=t.exports=function(t,e,r){return r||(r={}),t===e?!0:t instanceof Date&&e instanceof Date?t.getTime()===e.getTime():!t||!e||"object"!=typeof t&&"object"!=typeof e?r.strict?t===e:t==e:o(t,e,r)}},function(t,e){"use strict";var r={childContextTypes:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,mixins:!0,propTypes:!0,type:!0},n={name:!0,length:!0,prototype:!0,caller:!0,arguments:!0,arity:!0};t.exports=function(t,e){for(var i=Object.getOwnPropertyNames(e),o=0;o<i.length;++o)if(!r[i[o]]&&!n[i[o]])try{t[i[o]]=e[i[o]]}catch(u){}return t}},function(t,e,r){"use strict";e.__esModule=!0;var n=r(3);e.default=n.PropTypes.shape({subscribe:n.PropTypes.func.isRequired,dispatch:n.PropTypes.func.isRequired,getState:n.PropTypes.func.isRequired})},function(t,e){"use strict";function r(){for(var t=arguments.length,e=Array(t),r=0;t>r;r++)e[r]=arguments[r];return function(){if(0===e.length)return arguments.length<=0?void 0:arguments[0];var t=e[e.length-1],r=e.slice(0,-1);return r.reduceRight(function(t,e){return e(t)},t.apply(void 0,arguments))}}e.__esModule=!0,e.default=r},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function i(t,e,r){function n(){h===p&&(h=p.slice())}function o(){return d}function s(t){if("function"!=typeof t)throw new Error("Expected listener to be a function.");var e=!0;return n(),h.push(t),function(){if(e){e=!1,n();var r=h.indexOf(t);h.splice(r,1)}}}function f(t){if(!(0,u.default)(t))throw new Error("Actions must be plain objects. Use custom middleware for async actions.");if("undefined"==typeof t.type)throw new Error('Actions may not have an undefined "type" property. Have you misspelled a constant?');if(y)throw new Error("Reducers may not dispatch actions.");try{y=!0,d=l(d,t)}finally{y=!1}for(var e=p=h,r=0;r<e.length;r++)e[r]();return t}function c(t){if("function"!=typeof t)throw new Error("Expected the nextReducer to be a function.");l=t,f({type:a.INIT})}if("function"==typeof e&&"undefined"==typeof r&&(r=e,e=void 0),"undefined"!=typeof r){if("function"!=typeof r)throw new Error("Expected the enhancer to be a function.");return r(i)(t,e)}if("function"!=typeof t)throw new Error("Expected the reducer to be a function.");var l=t,d=e,p=[],h=p,y=!1;return f({type:a.INIT}),{dispatch:f,subscribe:s,getState:o,replaceReducer:c}}e.__esModule=!0,e.ActionTypes=void 0,e.default=i;var o=r(26),u=n(o),a=e.ActionTypes={INIT:"@@redux/INIT"}},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0,e.compose=e.applyMiddleware=e.bindActionCreators=e.combineReducers=e.createStore=void 0;var i=r(23),o=n(i),u=r(67),a=n(u),s=r(66),f=n(s),c=r(65),l=n(c),d=r(22),p=n(d),h=r(25);n(h);e.createStore=o.default,e.combineReducers=a.default,e.bindActionCreators=f.default,e.applyMiddleware=l.default,e.compose=p.default},function(t,e){"use strict";function r(t){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(t);try{throw new Error(t)}catch(e){}}e.__esModule=!0,e.default=r},function(t,e,r){function n(t){if(!u(t)||d.call(t)!=a||o(t))return!1;var e=i(t);if(null===e)return!0;var r=c.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&f.call(r)==l}var i=r(68),o=r(69),u=r(70),a="[object Object]",s=Object.prototype,f=Function.prototype.toString,c=s.hasOwnProperty,l=f.call(Object),d=s.toString;t.exports=n},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var i=r(6),o=n(i),u=r(2),a=n(u),s=function(t,e,r,n){e(n);var i=t();if(!(0,o.default)(i))throw new Error("asyncValidate function passed to reduxForm must return a promise");var u=function(t){return function(e){if(!(0,a.default)(e))return r(e),Promise.reject();if(t)throw r(),new Error("Asynchronous validation promise was rejected without errors.");return r(),Promise.resolve()}};return i.then(u(!1),u(!0))};e.default=s},function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{"default":t}}function o(t,e,r){return{actionTypes:m,addArrayValue:P,autofill:S,autofillWithKey:j,blur:V,change:T,changeWithKey:E,destroy:R,focus:x,getValues:A.default,initialize:M,initializeWithKey:F,propTypes:(0,_.default)(e),reduxForm:(0,c.default)(t,e,r),reducer:s.default,removeArrayValue:C,reset:k,startAsyncValidation:I,startSubmit:D,stopAsyncValidation:N,stopSubmit:U,submitFailed:q,swapArrayValues:W,touch:L,touchWithKey:K,untouch:z,untouchWithKey:B}}e.__esModule=!0;var u=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t};e.default=o;var a=r(17),s=i(a),f=r(31),c=i(f),l=r(5),d=i(l),p=r(8),h=i(p),y=r(7),v=n(y),b=r(4),m=n(b),g=r(30),_=i(g),O=r(15),A=i(O),w=u({},(0,d.default)(u({},v,{autofillWithKey:function(t){for(var e=arguments.length,r=Array(e>1?e-1:0),n=1;e>n;n++)r[n-1]=arguments[n];return(0,h.default)(v.autofill,{key:t}).apply(void 0,r)},changeWithKey:function(t){for(var e=arguments.length,r=Array(e>1?e-1:0),n=1;e>n;n++)r[n-1]=arguments[n];return(0,h.default)(v.change,{key:t}).apply(void 0,r)},initializeWithKey:function(t){for(var e=arguments.length,r=Array(e>1?e-1:0),n=1;e>n;n++)r[n-1]=arguments[n];return(0,h.default)(v.initialize,{key:t}).apply(void 0,r)},reset:function(t){return(0,h.default)(v.reset,{key:t})()},touchWithKey:function(t){for(var e=arguments.length,r=Array(e>1?e-1:0),n=1;e>n;n++)r[n-1]=arguments[n];return(0,h.default)(v.touch,{key:t}).apply(void 0,r)},untouchWithKey:function(t){for(var e=arguments.length,r=Array(e>1?e-1:0),n=1;e>n;n++)r[n-1]=arguments[n];return(0,h.default)(v.untouch,{key:t}).apply(void 0,r)},destroy:function(t){return(0,h.default)(v.destroy,{key:t})()}}),function(t){return function(e){for(var r=arguments.length,n=Array(r>1?r-1:0),i=1;r>i;i++)n[i-1]=arguments[i];return(0,h.default)(t,{form:e}).apply(void 0,n)}})),P=w.addArrayValue,S=w.autofill,j=w.autofillWithKey,V=w.blur,T=w.change,E=w.changeWithKey,R=w.destroy,x=w.focus,M=w.initialize,F=w.initializeWithKey,C=w.removeArrayValue,k=w.reset,I=w.startAsyncValidation,D=w.startSubmit,N=w.stopAsyncValidation,U=w.stopSubmit,q=w.submitFailed,W=w.swapArrayValues,L=w.touch,K=w.touchWithKey,z=w.untouch,B=w.untouchWithKey},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(t,e){var r={};for(var n in t)e.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n]);return r}function u(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function a(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}e.__esModule=!0;var f=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},c=r(7),l=i(c),d=r(13),p=n(d),h=r(17),y=r(19),v=n(y),b=r(8),m=n(b),g=r(14),_=n(g),O=r(2),A=n(O),w=r(43),P=n(w),S=r(38),j=n(S),V=r(27),T=n(V),E=r(37),R=n(E),x=r(12),M=n(x),F=r(49),C=n(F),k=r(50),I=n(k),D=function(t,e,r,n,i,c,d,y,b){var g=r.Component,O=r.PropTypes;return function(w,S,V,E){var x=function(n){function c(t){u(this,c);var r=a(this,n.call(this,t));r.asyncValidate=r.asyncValidate.bind(r),r.handleSubmit=r.handleSubmit.bind(r),r.fields=(0,P.default)(t,{},{},r.asyncValidate,e);var i=r.props.submitPassback;return i(function(){return r.handleSubmit()}),r}return s(c,n),c.prototype.componentWillMount=function(){var t=this.props,e=t.fields,r=t.form,n=t.initialize,i=t.initialValues;i&&!r._initialized&&n(i,e)},c.prototype.componentWillReceiveProps=function(t){(0,v.default)(this.props.fields,t.fields)&&(0,v.default)(this.props.form,t.form,{strict:!0})||(this.fields=(0,P.default)(t,this.props,this.fields,this.asyncValidate,e)),(0,v.default)(this.props.initialValues,t.initialValues)||this.props.initialize(t.initialValues,t.fields,this.props.overwriteOnInitialValuesChange||!this.props.form._initialized)},c.prototype.componentWillUnmount=function(){t.destroyOnUnmount&&this.props.destroy()},c.prototype.asyncValidate=function l(t,e){var r=this,n=this.props,l=n.asyncValidate,i=n.dispatch,o=n.fields,u=n.form,a=n.startAsyncValidation,s=n.stopAsyncValidation,f=n.validate,c=!t;if(l){var d=function(){var n=(0,_.default)(o,u);t&&(n[t]=e);var d=f(n,r.props),p=r.fields._meta.allPristine,h=u._initialized,y=c||(0,A.default)(d[t]);return!y||!c&&p&&h?void 0:{v:(0,T.default)(function(){return l(n,i,r.props)},a,s,t)}}();if("object"==typeof d)return d.v}},c.prototype.handleSubmit=function(t){var e=this,r=this.props,n=r.onSubmit,i=r.fields,o=r.form,u=function(t){if(!t||"function"!=typeof t)throw new Error("You must either pass handleSubmit() an onSubmit function or pass onSubmit as a prop");return t};return!t||(0,M.default)(t)?(0,j.default)(u(n),(0,_.default)(i,o),this.props,this.asyncValidate):(0,R.default)(function(){return(0,j.default)(u(t),(0,_.default)(i,o),e.props,e.asyncValidate)})},c.prototype.render=function(){var t,e=this,n=this.fields,u=this.props,a=(u.addArrayValue,u.asyncBlurFields,u.autofill,u.blur,u.change,u.destroy),s=(u.focus,u.fields),c=u.form,l=(u.initialValues,u.initialize),d=(u.onSubmit,u.propNamespace),p=u.reset,h=(u.removeArrayValue,u.returnRejectedSubmitPromise,u.startAsyncValidation,u.startSubmit,u.stopAsyncValidation,u.stopSubmit,u.submitFailed,u.swapArrayValues,u.touch),y=u.untouch,v=(u.validate,o(u,["addArrayValue","asyncBlurFields","autofill","blur","change","destroy","focus","fields","form","initialValues","initialize","onSubmit","propNamespace","reset","removeArrayValue","returnRejectedSubmitPromise","startAsyncValidation","startSubmit","stopAsyncValidation","stopSubmit","submitFailed","swapArrayValues","touch","untouch","validate"])),b=n._meta,m=b.allPristine,g=b.allValid,_=b.errors,O=b.formError,A=b.values,w={active:c._active,asyncValidating:c._asyncValidating,dirty:!m,error:O,errors:_,fields:n,formKey:V,invalid:!g,pristine:m,submitting:c._submitting,submitFailed:c._submitFailed,valid:g,values:A,asyncValidate:(0,R.default)(function(){return e.asyncValidate()}),destroyForm:(0,R.default)(a),handleSubmit:this.handleSubmit,initializeForm:(0,R.default)(function(t){return l(t,s)}),resetForm:(0,R.default)(p),touch:(0,R.default)(function(){return h.apply(void 0,arguments)}),touchAll:(0,R.default)(function(){return h.apply(void 0,s)}),untouch:(0,R.default)(function(){return y.apply(void 0,arguments)}),untouchAll:(0,R.default)(function(){return y.apply(void 0,s)})},P=d?(t={},t[d]=w,t):w;return r.createElement(i,f({},v,P))},c}(g);x.displayName="ReduxForm("+(0,p.default)(i)+")",x.WrappedComponent=i,x.propTypes={asyncBlurFields:O.arrayOf(O.string),asyncValidate:O.func,dispatch:O.func.isRequired,fields:O.arrayOf(O.string).isRequired,form:O.object,initialValues:O.any,onSubmit:O.func,onSubmitSuccess:O.func,onSubmitFail:O.func,overwriteOnInitialValuesChange:O.bool.isRequired,propNamespace:O.string,readonly:O.bool,returnRejectedSubmitPromise:O.bool,submitPassback:O.func.isRequired,validate:O.func,addArrayValue:O.func.isRequired,autofill:O.func.isRequired,blur:O.func.isRequired,change:O.func.isRequired,destroy:O.func.isRequired,focus:O.func.isRequired,initialize:O.func.isRequired,removeArrayValue:O.func.isRequired,reset:O.func.isRequired,startAsyncValidation:O.func.isRequired,startSubmit:O.func.isRequired,stopAsyncValidation:O.func.isRequired,stopSubmit:O.func.isRequired,submitFailed:O.func.isRequired,swapArrayValues:O.func.isRequired,touch:O.func.isRequired,untouch:O.func.isRequired},x.defaultProps={asyncBlurFields:[],form:h.initialState,readonly:!1,returnRejectedSubmitPromise:!1,validate:function(){return{}}};var F=f({},l,{blur:(0,m.default)(l.blur,{touch:!!t.touchOnBlur}),change:(0,m.default)(l.change,{touch:!!t.touchOnChange})}),k=void 0!==V&&null!==V?n((0,I.default)(c,function(t){var e=E(t,w);if(!e)throw new Error('You need to mount the redux-form reducer at "'+w+'"');return e&&e[S]&&e[S][V]}),(0,C.default)(d,(0,m.default)(F,{form:S,key:V})),y,b):n((0,I.default)(c,function(t){var e=E(t,w);if(!e)throw new Error('You need to mount the redux-form reducer at "'+w+'"');return e&&e[S]}),(0,C.default)(d,(0,m.default)(F,{form:S})),y,b);return k(x)}};e.default=D},function(t,e){"use strict";e.__esModule=!0;var r=function(t){var e=t.PropTypes,r=e.any,n=e.bool,i=e.string,o=e.func,u=e.object;return{active:i,asyncValidating:n.isRequired,autofilled:n,dirty:n.isRequired,error:r,errors:u,fields:u.isRequired,formKey:r,invalid:n.isRequired,pristine:n.isRequired,submitting:n.isRequired,submitFailed:n.isRequired,valid:n.isRequired,values:u.isRequired,asyncValidate:o.isRequired,destroyForm:o.isRequired,handleSubmit:o.isRequired,initializeForm:o.isRequired,resetForm:o.isRequired,touch:o.isRequired,touchAll:o.isRequired,untouch:o.isRequired,untouchAll:o.isRequired}};e.default=r},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function u(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}e.__esModule=!0;var a=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},s=r(32),f=n(s),c=r(20),l=n(c),d=function(t,e,r){var n=e.Component,s=(0,f.default)(t,e,r);return function(t,r,f,c,d){return function(p){var h=s(p,r,f,c,d),y=a({overwriteOnInitialValuesChange:!0,touchOnBlur:!0,touchOnChange:!1,destroyOnUnmount:!0},t),v=function(t){function r(e){i(this,r);var n=o(this,t.call(this,e));return n.handleSubmitPassback=n.handleSubmitPassback.bind(n),n}return u(r,t),r.prototype.handleSubmitPassback=function(t){this.submit=t},r.prototype.render=function(){return e.createElement(h,a({},y,this.props,{submitPassback:this.handleSubmitPassback}))},r}(n);return(0,l.default)(v,p)}}};e.default=d},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function i(t,e){var r={};for(var n in t)e.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n]);return r}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function u(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}e.__esModule=!0;var s=r(55),f=n(s),c=r(13),l=n(c),d=r(29),p=n(d),h=function(t,e,r){return function(n,s,c,d,h){var y=e.Component,v=e.PropTypes,b=function(l){function y(i){o(this,y);var a=u(this,l.call(this,i));return a.cache=new f.default(a,{ReduxForm:{params:["reduxMountPoint","form","formKey","getFormState"],fn:(0,p.default)(i,t,e,r,n,s,c,d,h)}}),a}return a(y,l),y.prototype.componentWillReceiveProps=function(t){this.cache.componentWillReceiveProps(t)},y.prototype.render=function(){var t=this.cache.get("ReduxForm"),r=this.props,n=(r.reduxMountPoint,
r.destroyOnUnmount,r.form,r.getFormState,r.touchOnBlur,r.touchOnChange,i(r,["reduxMountPoint","destroyOnUnmount","form","getFormState","touchOnBlur","touchOnChange"]));return e.createElement(t,n)},y}(y);return b.displayName="ReduxFormConnector("+(0,l.default)(n)+")",b.WrappedComponent=n,b.propTypes={destroyOnUnmount:v.bool,reduxMountPoint:v.string,form:v.string.isRequired,formKey:v.string,getFormState:v.func,touchOnBlur:v.bool,touchOnChange:v.bool},b.defaultProps={reduxMountPoint:"form",getFormState:function(t,e){return t[e]}},b}};e.default=h},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var i=r(10),o=n(i),u=function(t,e,r,n){return function(i){var u=(0,o.default)(i,r);e(t,u),n&&n(t,u)}};e.default=u},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var i=r(10),o=n(i),u=function(t,e,r){return function(n){return e(t,(0,o.default)(n,r))}};e.default=u},function(t,e,r){"use strict";e.__esModule=!0;var n=r(9),i=function(t,e){return function(r){e(t,r.dataTransfer.getData(n.dataKey))}};e.default=i},function(t,e){"use strict";e.__esModule=!0;var r=function(t,e){return function(){return e(t)}};e.default=r},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var i=r(12),o=n(i),u=function(t){return function(e){for(var r=arguments.length,n=Array(r>1?r-1:0),i=1;r>i;i++)n[i-1]=arguments[i];return(0,o.default)(e)?t.apply(void 0,n):t.apply(void 0,[e].concat(n))}};e.default=u},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var i=r(6),o=n(i),u=r(2),a=n(u),s=function(t,e,r,n){var i=r.dispatch,u=r.fields,s=r.onSubmitSuccess,f=r.onSubmitFail,c=r.startSubmit,l=r.stopSubmit,d=r.submitFailed,p=r.returnRejectedSubmitPromise,h=r.touch,y=r.validate,v=y(e,r);if(h.apply(void 0,u),(0,a.default)(v)){var b=function(){var r=t(e,i);return(0,o.default)(r)?(c(),r.then(function(t){return l(),s&&s(t),t},function(t){return l(t),f&&f(t),p?Promise.reject(t):void 0})):(s&&s(r),r)},m=n();return(0,o.default)(m)?m.then(b,function(){return d(),f&&f(),p?Promise.reject():Promise.resolve()}):b()}return d(),f&&f(v),p?Promise.reject(v):void 0};e.default=s},function(t,e,r){"use strict";e.__esModule=!0;var n=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},i=r(1),o=function(t,e,r){return(0,i.makeFieldValue)(void 0===t?{}:{initial:t,value:r?t:e})},u=function(t,e){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2],i=arguments.length<=3||void 0===arguments[3]?!0:arguments[3];if(!e)throw new Error("fields must be passed when initializing state");if(!t||!e.length)return r;var u=function a(t,e,r){var u=t.indexOf(".");if(0===u)return a(t.substring(1),e,r);var s=t.indexOf("["),f=t.indexOf("]"),c=n({},r)||{};if(u>=0&&(0>s||s>u)){var l=t.substring(0,u);c[l]=e[l]&&a(t.substring(u+1),e[l],c[l]||{})}else s>=0&&(0>u||u>s)?!function(){if(0>f)throw new Error("found '[' but no ']': '"+t+"'");var r=t.substring(0,s),n=e[r],u=c[r],l=t.substring(f+1);Array.isArray(n)?l.length?c[r]=n.map(function(t,e){return a(l,t,u&&u[e])}):c[r]=n.map(function(t,e){return o(t,u&&u[e]&&u[e].value,i)}):c[r]=[]}():c[t]=o(e&&e[t],r&&r[t]&&r[t].value,i);return c};return e.reduce(function(e,r){return u(r,t,e)},n({},r))};e.default=u},function(t,e){"use strict";function r(t,e){if(t===e)return!0;if("boolean"==typeof t||"boolean"==typeof e)return t===e;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(t&&"object"==typeof t){if(!e||"object"!=typeof e)return!1;var n=Object.keys(t),i=Object.keys(e);if(n.length!==i.length)return!1;for(var o=0;o<i.length;o++){var u=i[o];if(!r(t[u],e[u]))return!1}}else if(t||e)return t===e;return!0}e.__esModule=!0,e.default=r},function(t,e,r){"use strict";function n(t){var e=t.indexOf("."),r=t.indexOf("["),n=t.indexOf("]");if(r>0&&n!==r+1)throw new Error("found [ not followed by ]");var i=r>0&&(0>e||e>r),o=void 0,u=void 0;return i?(o=t.substring(0,r),u=t.substring(n+1),"."===u[0]&&(u=u.substring(1))):e>0?(o=t.substring(0,e),u=t.substring(e+1)):o=t,{isArray:i,key:o,nestedPath:u}}function i(t,e,r,o,u,s,f){if(t.isArray){if(t.nestedPath){var c=function(){var a=r&&r[t.key]||[],c=o&&o[t.key]||[],l=n(t.nestedPath);return{v:a.map(function(t,r){return t[l.key]=i(l,e,t,c[r],u,s,f),t})}}();if("object"==typeof c)return c.v}var l=f[e],d=l(r&&r[t.key],o&&o[t.key],u,s);return t.isArray?d&&d.map(a.makeFieldValue):d}if(t.nestedPath){var p=r&&r[t.key]||{},h=n(t.nestedPath);return p[h.key]=i(h,e,p,o&&o[t.key],u,s,f),p}var y=r&&r[t.key]||{},v=f[e];return y.value=v(y.value,o&&o[t.key]&&o[t.key].value,u,s),(0,a.makeFieldValue)(y)}function o(t,e,r,o,a){var s=Object.keys(t).reduce(function(u,s){var f=n(s);return u[f.key]=i(f,s,e,r,o,a,t),u},{});return u({},e,s)}e.__esModule=!0;var u=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t};e.default=o;var a=r(1)},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function i(t,e){var r=t.substring(e+1);return"."===r[0]&&(r=r.substring(1)),r}e.__esModule=!0;var o=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},u=r(33),a=n(u),s=r(34),f=n(s),c=r(9),l=n(c),d=r(35),p=n(d),h=r(36),y=n(h),v=r(47),b=n(v),m=r(16),g=n(m),_=r(48),O=n(_),A=function(t){var e=t.indexOf("."),r=t.indexOf("[");return r>0&&(0>e||e>r)?t.substring(0,r):e>0?t.substring(0,e):t},w=function P(t,e){var r=arguments.length<=2||void 0===arguments[2]?"":arguments[2],n=arguments[3],u=arguments[4],s=arguments[5],c=arguments[6],d=arguments[7],h=arguments.length<=8||void 0===arguments[8]?function(){return null}:arguments[8],v=arguments.length<=9||void 0===arguments[9]?"":arguments[9],m=d.asyncBlurFields,_=d.autofill,w=d.blur,S=d.change,j=d.focus,V=d.form,T=d.initialValues,E=d.readonly,R=d.addArrayValue,x=d.removeArrayValue,M=d.swapArrayValues,F=e.indexOf("."),C=e.indexOf("["),k=e.indexOf("]");if(C>0&&k!==C+1)throw new Error("found [ not followed by ]");if(C>0&&(0>F||F>C)){var I=function(){var o=e.substring(0,C),a=i(e,k),f=t&&t[o]||[],l=v+e.substring(0,k+1),p=d.fields.reduce(function(t,e){return 0===e.indexOf(l)&&t.push(e),t},[]).map(function(t){return i(t,v.length+k)}),y=function(t){return Object.defineProperty(t,"addField",{value:function(t,e){return R(r+o,t,e,p)}}),Object.defineProperty(t,"removeField",{value:function(t){return x(r+o,t)}}),Object.defineProperty(t,"swapFields",{value:function(t,e){return M(r+o,t,e)}}),t};n[o]&&n[o].length===f.length||(n[o]=n[o]?[].concat(n[o]):[],y(n[o]));var b=n[o],m=!1;return f.forEach(function(t,e){a&&!b[e]&&(b[e]={},m=!0);var n=a?b[e]:{},i=""+r+o+"["+e+"]"+(a?".":""),f=""+v+o+"[]"+(a?".":""),l=P(t,a,i,n,u,s,c,d,h,f);a||b[e]===l||(b[e]=l,m=!0)}),b.length>f.length&&b.splice(f.length,b.length-f.length),{v:m?y([].concat(b)):b}}();if("object"==typeof I)return I.v}if(F>0){var D=e.substring(0,F),N=e.substring(F+1),U=n[D]||{},q=r+D+".",W=A(N),L=U[W],K=P(t[D]||{},N,q,U,u,s,c,d,h,q);if(K!==L){var z;U=o({},U,(z={},z[W]=K,z))}return n[D]=U,U}var B=r+e,Y=n[e]||{};if(Y.name!==B){var H=(0,f.default)(B,S,c),G=(0,g.default)(B+".initial",V),Z=G||(0,g.default)(B,T);Y.name=B,Y.checked=Z===!0||void 0,Y.value=Z,Y.initialValue=Z,E||(Y.autofill=function(t){return _(B,t)},Y.onBlur=(0,a.default)(B,w,c,~m.indexOf(B)&&function(t,e){return(0,b.default)(s(t,e))}),Y.onChange=H,Y.onDragStart=(0,l.default)(B,function(){return Y.value}),Y.onDrop=(0,p.default)(B,S),Y.onFocus=(0,y.default)(B,j),Y.onUpdate=H),Y.valid=!0,Y.invalid=!1,Object.defineProperty(Y,"_isField",{value:!0})}var J=(e?t[e]:t)||{},Q=(0,g.default)(B,u),X=(0,O.default)(Y,J,B===V._active,Q);return(e||n[e]!==X)&&(n[e]=X),h(X),X};e.default=w},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var i=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},o=r(42),u=n(o),a=r(18),s=n(a),f=r(14),c=n(f),l=r(44),d=n(l),p=function(t,e,r,n,o){var a=t.fields,f=t.form,l=t.validate,p=e.fields,h=(0,c.default)(a,f),y=l(h,t)||{},v={},b=y._error||f._error,m=!b,g=!0,_=function(t){t.error&&(v=(0,s.default)(t.name,t.error,v),m=!1),t.dirty&&(g=!1)},O=p?p.reduce(function(t,e){return~a.indexOf(e)?t:(0,d.default)(t,e)},i({},r)):i({},r);return a.forEach(function(e){(0,u.default)(f,e,void 0,O,y,n,o,t,_)}),Object.defineProperty(O,"_meta",{value:{allPristine:g,allValid:m,values:h,errors:v,formError:b}}),O};e.default=p},function(t,e){"use strict";e.__esModule=!0;var r=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},n=function(t,e){var n=r({},t);return delete n[e],n},i=function o(t,e){var i=e.indexOf("."),u=e.indexOf("["),a=e.indexOf("]");if(u>0&&a!==u+1)throw new Error("found [ not followed by ]");if(u>0&&(0>i||i>u)){var s=function(){var i=e.substring(0,u);if(!Array.isArray(t[i]))return{v:n(t,i)};var s=e.substring(a+1);if("."===s[0]&&(s=s.substring(1)),s){var f=function(){var e,u=[];return t[i].forEach(function(t,e){var r=o(t,s);Object.keys(r).length&&(u[e]=r)}),{v:{v:u.length?r({},t,(e={},e[i]=u,e)):n(t,i)}}}();if("object"==typeof f)return f.v}return{v:n(t,i)}}();if("object"==typeof s)return s.v}if(i>0){var f,c=e.substring(0,i),l=e.substring(i+1);if(!t[c])return t;var d=o(t[c],l);return Object.keys(d).length?r({},t,(f={},f[c]=o(t[c],l),f)):n(t,c)}return n(t,e)};e.default=i},function(t,e,r){"use strict";e.__esModule=!0;var n=r(1),i=function(t){return(0,n.makeFieldValue)(void 0===t||t&&void 0===t.initial?{}:{initial:t.initial,value:t.initial})},o=function u(t){return t?Object.keys(t).reduce(function(e,r){var o=t[r];return Array.isArray(o)?e[r]=o.map(function(t){return(0,n.isFieldValue)(t)?i(t):u(t)}):o&&((0,n.isFieldValue)(o)?e[r]=i(o):"object"==typeof o&&null!==o?e[r]=u(o):e[r]=o),e},{}):t};e.default=o},function(t,e,r){"use strict";e.__esModule=!0;var n=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},i=r(1),o=function(t){return"_"===t[0]},u=function a(t,e,r){var u=function(){if(Array.isArray(t))return t.map(function(t,n){return a(t,e&&e[n],r)});if(t&&"object"==typeof t){var u=Object.keys(t).reduce(function(i,u){var s;return o(u)?i:n({},i,(s={},s[u]=a(t[u],e&&e[u],r),s))},t);return(0,i.isFieldValue)(t)&&(0,i.makeFieldValue)(u),u}return(0,i.makeFieldValue)(t)};if(!e){if(!t)return t;if(t[r]){var s=n({},t);return delete s[r],(0,i.makeFieldValue)(s)}return u()}if("string"==typeof e){var f;return(0,i.makeFieldValue)(n({},t,(f={},f[r]=e,f)))}if(Array.isArray(e)){if(!t||Array.isArray(t)){var c=function(){var n=(t||[]).map(function(t,n){return a(t,e[n],r)});return e.forEach(function(t,e){return n[e]=a(n[e],t,r)}),{v:n}}();if("object"==typeof c)return c.v}return a(t,e[0],r)}if((0,i.isFieldValue)(t)){var l;return(0,i.makeFieldValue)(n({},t,(l={},l[r]=e,l)))}var d=Object.keys(e);return d.length||t?d.reduce(function(i,u){var s;return o(u)?i:n({},i,(s={},s[u]=a(t&&t[u],e[u],r),s))},u()||{}):t};e.default=u},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var i=r(6),o=n(i),u=function(){},a=function(t){return(0,o.default)(t)?t.then(u,u):t};e.default=a},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var i=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},o=r(40),u=n(o),a=r(2),s=n(a),f=function(t,e,r,n){var o={},a=void 0===e.value?"":e.value;t.value!==a&&(o.value=a,o.checked="boolean"==typeof a?a:void 0);var f=(0,u.default)(a,e.initial);t.pristine!==f&&(o.dirty=!f,o.pristine=f);var c=n||e.submitError||e.asyncError;c!==t.error&&(o.error=c);var l=(0,s.default)(c);t.valid!==l&&(o.invalid=!l,o.valid=l),r!==t.active&&(o.active=r);var d=!!e.touched;d!==t.touched&&(o.touched=d);var p=!!e.visited;p!==t.visited&&(o.visited=p);var h=!!e.autofilled;return h!==t.autofilled&&(o.autofilled=h),"initial"in e&&e.initial!==t.initialValue&&(t.initialValue=e.initial),Object.keys(o).length?i({},t,o):t};e.default=f},function(t,e,r){"use strict";e.__esModule=!0;var n=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},i=r(24),o=function(t,e){return t?"function"==typeof t?t.length>1?function(r,o){return n({dispatch:r},t(r,o),(0,i.bindActionCreators)(e,r))}:function(r){return n({dispatch:r},t(r),(0,i.bindActionCreators)(e,r))}:function(r){return n({dispatch:r},(0,i.bindActionCreators)(t,r),(0,i.bindActionCreators)(e,r))}:function(t){return n({dispatch:t},(0,i.bindActionCreators)(e,t))}};e.default=o},function(t,e){"use strict";e.__esModule=!0;var r=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},n=function(t,e){if(t){if("function"!=typeof t)throw new Error("mapStateToProps must be a function");return t.length>1?function(n,i){return r({},t(n,i),{form:e(n)})}:function(n){return r({},t(n),{form:e(n)})}}return function(t){return{form:e(t)}}};e.default=n},function(t,e){function r(t){return"[object Arguments]"==Object.prototype.toString.call(t)}function n(t){return t&&"object"==typeof t&&"number"==typeof t.length&&Object.prototype.hasOwnProperty.call(t,"callee")&&!Object.prototype.propertyIsEnumerable.call(t,"callee")||!1}var i="[object Arguments]"==function(){return Object.prototype.toString.call(arguments)}();e=t.exports=i?r:n,e.supported=r,e.unsupported=n},function(t,e){function r(t){var e=[];for(var r in t)e.push(r);return e}e=t.exports="function"==typeof Object.keys?Object.keys:r,e.shim=r},function(t,e,r){"use strict";var n=function(t,e,r,n,i,o,u,a){if(!t){var s;if(void 0===e)s=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var f=[r,n,i,o,u,a],c=0;s=new Error(e.replace(/%s/g,function(){return f[c++]})),s.name="Invariant Violation"}throw s.framesToPop=1,s}};t.exports=n},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){return!!(t&&e&&t.some(function(t){return~e.indexOf(t)}))}e.__esModule=!0;var u=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},a=r(19),s=n(a),f=function(){function t(e,r){var n=this;i(this,t),this.component=e,this.allProps=[],this.cache=Object.keys(r).reduce(function(t,e){var i,o=r[e],a=o.fn,s=o.params;return s.forEach(function(t){~n.allProps.indexOf(t)||n.allProps.push(t)}),u({},t,(i={},i[e]={value:void 0,props:s,fn:a},i))},{})}return t.prototype.get=function(t){var e=this.component,r=this.cache[t],n=r.value,i=r.fn,o=r.props;if(void 0!==n)return n;var u=o.map(function(t){return e.props[t]}),a=i.apply(void 0,u);return this.cache[t].value=a,a},t.prototype.componentWillReceiveProps=function(t){var e=this,r=this.component,n=[];this.allProps.forEach(function(e){s.default(r.props[e],t[e])||n.push(e)}),n.length&&Object.keys(this.cache).forEach(function(t){o(n,e.cache[t].props)&&delete e.cache[t].value})},t}();e.default=f,t.exports=e.default},function(t,e,r){t.exports=r(54)},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function u(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}e.__esModule=!0,e.default=void 0;var a=r(3),s=r(21),f=n(s),c=function(t){function e(r,n){i(this,e);var u=o(this,t.call(this,r,n));return u.store=r.store,u}return u(e,t),e.prototype.getChildContext=function(){return{store:this.store}},e.prototype.render=function(){var t=this.props.children;return a.Children.only(t)},e}(a.Component);e.default=c,c.propTypes={store:f.default.isRequired,children:a.PropTypes.element.isRequired},c.childContextTypes={store:f.default.isRequired}},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function u(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(t){return t.displayName||t.name||"Component"}function s(t,e){return(0,w.default)((0,g.default)(t),"`%sToProps` must return an object. Instead received %s.",e?"mapDispatch":"mapState",t),t}function f(t,e,r){function n(t,e,r){var n=m(t,e,r);return(0,w.default)((0,g.default)(n),"`mergeProps` must return an object. Instead received %s.",n),n}var f=arguments.length<=3||void 0===arguments[3]?{}:arguments[3],d=Boolean(t),h=t||P,v=(0,g.default)(e)?(0,b.default)(e):e||S,m=r||j,_=m!==j,A=f.pure,T=void 0===A?!0:A,E=f.withRef,R=void 0===E?!1:E,x=V++;return function(t){var e=function(e){function r(t,n){i(this,r);var u=o(this,e.call(this,t,n));u.version=x,u.store=t.store||n.store,(0,w.default)(u.store,'Could not find "store" in either the context or '+('props of "'+u.constructor.displayName+'". ')+"Either wrap the root component in a <Provider>, "+('or explicitly pass "store" as a prop to "'+u.constructor.displayName+'".'));var a=u.store.getState();return u.state={storeState:a},u.clearCache(),u}return u(r,e),r.prototype.shouldComponentUpdate=function(){return!T||this.haveOwnPropsChanged||this.hasStoreStateChanged},r.prototype.computeStateProps=function(t,e){if(!this.finalMapStateToProps)return this.configureFinalMapState(t,e);var r=t.getState(),n=this.doStatePropsDependOnOwnProps?this.finalMapStateToProps(r,e):this.finalMapStateToProps(r);return s(n)},r.prototype.configureFinalMapState=function(t,e){var r=h(t.getState(),e),n="function"==typeof r;return this.finalMapStateToProps=n?r:h,this.doStatePropsDependOnOwnProps=1!==this.finalMapStateToProps.length,n?this.computeStateProps(t,e):s(r)},r.prototype.computeDispatchProps=function(t,e){if(!this.finalMapDispatchToProps)return this.configureFinalMapDispatch(t,e);var r=t.dispatch,n=this.doDispatchPropsDependOnOwnProps?this.finalMapDispatchToProps(r,e):this.finalMapDispatchToProps(r);return s(n,!0)},r.prototype.configureFinalMapDispatch=function(t,e){var r=v(t.dispatch,e),n="function"==typeof r;return this.finalMapDispatchToProps=n?r:v,this.doDispatchPropsDependOnOwnProps=1!==this.finalMapDispatchToProps.length,n?this.computeDispatchProps(t,e):s(r,!0)},r.prototype.updateStatePropsIfNeeded=function(){var t=this.computeStateProps(this.store,this.props);return this.stateProps&&(0,y.default)(t,this.stateProps)?!1:(this.stateProps=t,!0)},r.prototype.updateDispatchPropsIfNeeded=function(){var t=this.computeDispatchProps(this.store,this.props);return this.dispatchProps&&(0,y.default)(t,this.dispatchProps)?!1:(this.dispatchProps=t,!0)},r.prototype.updateMergedPropsIfNeeded=function(){var t=n(this.stateProps,this.dispatchProps,this.props);return this.mergedProps&&_&&(0,y.default)(t,this.mergedProps)?!1:(this.mergedProps=t,!0)},r.prototype.isSubscribed=function(){return"function"==typeof this.unsubscribe},r.prototype.trySubscribe=function(){d&&!this.unsubscribe&&(this.unsubscribe=this.store.subscribe(this.handleChange.bind(this)),this.handleChange())},r.prototype.tryUnsubscribe=function(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null)},r.prototype.componentDidMount=function(){this.trySubscribe()},r.prototype.componentWillReceiveProps=function(t){T&&(0,y.default)(t,this.props)||(this.haveOwnPropsChanged=!0)},r.prototype.componentWillUnmount=function(){this.tryUnsubscribe(),this.clearCache()},r.prototype.clearCache=function(){this.dispatchProps=null,this.stateProps=null,this.mergedProps=null,this.haveOwnPropsChanged=!0,this.hasStoreStateChanged=!0,this.renderedElement=null,this.finalMapDispatchToProps=null,this.finalMapStateToProps=null},r.prototype.handleChange=function(){if(this.unsubscribe){var t=this.state.storeState,e=this.store.getState();T&&t===e||(this.hasStoreStateChanged=!0,this.setState({storeState:e}))}},r.prototype.getWrappedInstance=function(){return(0,w.default)(R,"To access the wrapped instance, you need to specify { withRef: true } as the fourth argument of the connect() call."),this.refs.wrappedInstance},r.prototype.render=function(){var e=this.haveOwnPropsChanged,r=this.hasStoreStateChanged,n=this.renderedElement;this.haveOwnPropsChanged=!1,this.hasStoreStateChanged=!1;var i=!0,o=!0;T&&n&&(i=r||e&&this.doStatePropsDependOnOwnProps,o=e&&this.doDispatchPropsDependOnOwnProps);var u=!1,a=!1;i&&(u=this.updateStatePropsIfNeeded()),o&&(a=this.updateDispatchPropsIfNeeded());var s=!0;return s=u||a||e?this.updateMergedPropsIfNeeded():!1,!s&&n?n:(R?this.renderedElement=(0,l.createElement)(t,c({},this.mergedProps,{ref:"wrappedInstance"})):this.renderedElement=(0,l.createElement)(t,this.mergedProps),this.renderedElement)},r}(l.Component);return e.displayName="Connect("+a(t)+")",e.WrappedComponent=t,e.contextTypes={store:p.default},e.propTypes={store:p.default},(0,O.default)(e,t)}}var c=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t};e.__esModule=!0,e.default=f;var l=r(3),d=r(21),p=n(d),h=r(59),y=n(h),v=r(60),b=n(v),m=r(64),g=n(m),_=r(20),O=n(_),A=r(53),w=n(A),P=function(t){return{}},S=function(t){return{dispatch:t}},j=function(t,e,r){return c({},r,t,e)},V=0},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0,e.connect=e.Provider=void 0;var i=r(56),o=n(i),u=r(57),a=n(u);e.Provider=o.default,e.connect=a.default},function(t,e){"use strict";function r(t,e){if(t===e)return!0;var r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(var i=Object.prototype.hasOwnProperty,o=0;o<r.length;o++)if(!i.call(e,r[o])||t[r[o]]!==e[r[o]])return!1;return!0}e.__esModule=!0,e.default=r},function(t,e,r){"use strict";function n(t){return function(e){return(0,i.bindActionCreators)(t,e)}}e.__esModule=!0,e.default=n;var i=r(24)},function(t,e){function r(t){return n(Object(t))}var n=Object.getPrototypeOf;t.exports=r},function(t,e){function r(t){var e=!1;if(null!=t&&"function"!=typeof t.toString)try{e=!!(t+"")}catch(r){}return e}t.exports=r},function(t,e){function r(t){return!!t&&"object"==typeof t}t.exports=r},function(t,e,r){function n(t){if(!u(t)||d.call(t)!=a||o(t))return!1;var e=i(t);if(null===e)return!0;var r=c.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&f.call(r)==l}var i=r(61),o=r(62),u=r(63),a="[object Object]",s=Object.prototype,f=Function.prototype.toString,c=s.hasOwnProperty,l=f.call(Object),d=s.toString;t.exports=n},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function i(){for(var t=arguments.length,e=Array(t),r=0;t>r;r++)e[r]=arguments[r];return function(t){return function(r,n,i){var u=t(r,n,i),s=u.dispatch,f=[],c={getState:u.getState,dispatch:function(t){return s(t)}};return f=e.map(function(t){return t(c)}),s=a.default.apply(void 0,f)(u.dispatch),o({},u,{dispatch:s})}}}var o=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t};e.__esModule=!0,e.default=i;var u=r(22),a=n(u)},function(t,e){"use strict";function r(t,e){return function(){return e(t.apply(void 0,arguments))}}function n(t,e){if("function"==typeof t)return r(t,e);if("object"!=typeof t||null===t)throw new Error("bindActionCreators expected an object or a function, instead received "+(null===t?"null":typeof t)+'. Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');for(var n=Object.keys(t),i={},o=0;o<n.length;o++){var u=n[o],a=t[u];"function"==typeof a&&(i[u]=r(a,e))}return i}e.__esModule=!0,e.default=n},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function i(t,e){var r=e&&e.type,n=r&&'"'+r.toString()+'"'||"an action";return'Reducer "'+t+'" returned undefined handling '+n+". To ignore an action, you must explicitly return the previous state."}function o(t){Object.keys(t).forEach(function(e){var r=t[e],n=r(void 0,{type:a.ActionTypes.INIT});if("undefined"==typeof n)throw new Error('Reducer "'+e+'" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined.');var i="@@redux/PROBE_UNKNOWN_ACTION_"+Math.random().toString(36).substring(7).split("").join(".");if("undefined"==typeof r(void 0,{type:i}))throw new Error('Reducer "'+e+'" returned undefined when probed with a random type. '+("Don't try to handle "+a.ActionTypes.INIT+' or other actions in "redux/*" ')+"namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined.")})}function u(t){for(var e=Object.keys(t),r={},n=0;n<e.length;n++){var u=e[n];"function"==typeof t[u]&&(r[u]=t[u])}var a,s=Object.keys(r);try{o(r)}catch(f){a=f}return function(){var t=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],e=arguments[1];if(a)throw a;for(var n=!1,o={},u=0;u<s.length;u++){var f=s[u],c=r[f],l=t[f],d=c(l,e);if("undefined"==typeof d){var p=i(f,e);throw new Error(p)}o[f]=d,n=n||d!==l}return n?o:t}}e.__esModule=!0,e.default=u;var a=r(23),s=r(26),f=(n(s),r(25));n(f)},function(t,e){function r(t){return n(Object(t))}var n=Object.getPrototypeOf;t.exports=r},function(t,e){function r(t){var e=!1;if(null!=t&&"function"!=typeof t.toString)try{e=!!(t+"")}catch(r){}return e}t.exports=r},function(t,e){function r(t){return!!t&&"object"==typeof t}t.exports=r}])});
|
public/javascripts/jquery.min.js
|
Jmacek/CIS526-TeamProject
|
/*! jQuery v1.11.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.1",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="<select msallowclip=''><option selected=''></option></select>",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=lb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=mb(b);function pb(){}pb.prototype=d.filters=d.pseudos,d.setFilters=new pb,g=fb.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fb.error(a):z(a,i).slice(0)};function qb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h;
if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},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(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==cb()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===cb()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ab:bb):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:bb,isPropagationStopped:bb,isImmediatePropagationStopped:bb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ab,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ab,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ab,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=bb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=bb),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function db(a){var b=eb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var eb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fb=/ jQuery\d+="(?:null|\d+)"/g,gb=new RegExp("<(?:"+eb+")[\\s/>]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/<tbody/i,lb=/<|&#?\w+;/,mb=/<(?:script|style|link)/i,nb=/checked\s*(?:[^=]|=\s*.checked.)/i,ob=/^$|\/(?:java|ecma)script/i,pb=/^true\/(.*)/,qb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,rb={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:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?"<table>"!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Cb[0].contentWindow||Cb[0].contentDocument).document,b.write(),b.close(),c=Eb(a,b),Cb.detach()),Db[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.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",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Gb=/^margin/,Hb=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ib,Jb,Kb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ib=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Hb.test(g)&&Gb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ib=function(a){return a.currentStyle},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Hb.test(g)&&!Kb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Lb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.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",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Mb=/alpha\([^)]*\)/i,Nb=/opacity\s*=\s*([^)]*)/,Ob=/^(none|table(?!-c[ea]).+)/,Pb=new RegExp("^("+S+")(.*)$","i"),Qb=new RegExp("^([+-])=("+S+")","i"),Rb={position:"absolute",visibility:"hidden",display:"block"},Sb={letterSpacing:"0",fontWeight:"400"},Tb=["Webkit","O","Moz","ms"];function Ub(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Tb.length;while(e--)if(b=Tb[e]+c,b in a)return b;return d}function Vb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fb(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wb(a,b,c){var d=Pb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Yb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ib(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Jb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Hb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xb(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Jb(a,"opacity");return""===c?"1":c}}}},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":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ub(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ub(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Jb(a,b,d)),"normal"===f&&b in Sb&&(f=Sb[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Ob.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Rb,function(){return Yb(a,b,d)}):Yb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ib(a);return Wb(a,c,d?Xb(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Nb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Mb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Mb.test(f)?f.replace(Mb,e):f+" "+e)}}),m.cssHooks.marginRight=Lb(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Jb,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Gb.test(a)||(m.cssHooks[a+b].set=Wb)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ib(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Vb(this,!0)},hide:function(){return Vb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Zb(a,b,c,d,e){return new Zb.prototype.init(a,b,c,d,e)}m.Tween=Zb,Zb.prototype={constructor:Zb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px")
},cur:function(){var a=Zb.propHooks[this.prop];return a&&a.get?a.get(this):Zb.propHooks._default.get(this)},run:function(a){var b,c=Zb.propHooks[this.prop];return this.pos=b=this.options.duration?m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Zb.propHooks._default.set(this),this}},Zb.prototype.init.prototype=Zb.prototype,Zb.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Zb.propHooks.scrollTop=Zb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Zb.prototype.init,m.fx.step={};var $b,_b,ac=/^(?:toggle|show|hide)$/,bc=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cc=/queueHooks$/,dc=[ic],ec={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bc.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bc.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fc(){return setTimeout(function(){$b=void 0}),$b=m.now()}function gc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hc(a,b,c){for(var d,e=(ec[b]||[]).concat(ec["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ic(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fb(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fb(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ac.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fb(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hc(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jc(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kc(a,b,c){var d,e,f=0,g=dc.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$b||fc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$b||fc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jc(k,j.opts.specialEasing);g>f;f++)if(d=dc[f].call(j,a,k,j.opts))return d;return m.map(k,hc,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kc,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],ec[c]=ec[c]||[],ec[c].unshift(b)},prefilter:function(a,b){b?dc.unshift(a):dc.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kc(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gc(b,!0),a,d,e)}}),m.each({slideDown:gc("show"),slideUp:gc("hide"),slideToggle:gc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($b=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$b=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_b||(_b=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_b),_b=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lc=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lc,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mc,nc,oc=m.expr.attrHandle,pc=/^(?:checked|selected)$/i,qc=k.getSetAttribute,rc=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nc:mc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rc&&qc||!pc.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qc?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nc={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rc&&qc||!pc.test(c)?a.setAttribute(!qc&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=oc[b]||m.find.attr;oc[b]=rc&&qc||!pc.test(b)?function(a,b,d){var e,f;return d||(f=oc[b],oc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,oc[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rc&&qc||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mc&&mc.set(a,b,c)}}),qc||(mc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},oc.id=oc.name=oc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mc.set},m.attrHooks.contenteditable={set:function(a,b,c){mc.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sc=/^(?:input|select|textarea|button|object)$/i,tc=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sc.test(a.nodeName)||tc.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var uc=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(uc," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vc=m.now(),wc=/\?/,xc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yc,zc,Ac=/#.*$/,Bc=/([?&])_=[^&]*/,Cc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Dc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Ec=/^(?:GET|HEAD)$/,Fc=/^\/\//,Gc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hc={},Ic={},Jc="*/".concat("*");try{zc=location.href}catch(Kc){zc=y.createElement("a"),zc.href="",zc=zc.href}yc=Gc.exec(zc.toLowerCase())||[];function Lc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mc(a,b,c,d){var e={},f=a===Ic;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nc(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Oc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zc,type:"GET",isLocal:Dc.test(yc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jc,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":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nc(Nc(a,m.ajaxSettings),b):Nc(m.ajaxSettings,a)},ajaxPrefilter:Lc(Hc),ajaxTransport:Lc(Ic),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zc)+"").replace(Ac,"").replace(Fc,yc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yc[1]&&c[2]===yc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yc[3]||("http:"===yc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mc(Hc,k,b,v),2===t)return v;h=k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Ec.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bc.test(e)?e.replace(Bc,"$1_="+vc++):e+(wc.test(e)?"&":"?")+"_="+vc++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mc(Ic,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Oc(k,v,c)),u=Pc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qc=/%20/g,Rc=/\[\]$/,Sc=/\r?\n/g,Tc=/^(?:submit|button|image|reset|file)$/i,Uc=/^(?:input|select|textarea|keygen)/i;function Vc(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rc.test(a)?d(a,e):Vc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vc(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vc(c,a[c],b,e);return d.join("&").replace(Qc,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Uc.test(this.nodeName)&&!Tc.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sc,"\r\n")}}):{name:b.name,value:c.replace(Sc,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zc()||$c()}:Zc;var Wc=0,Xc={},Yc=m.ajaxSettings.xhr();a.ActiveXObject&&m(a).on("unload",function(){for(var a in Xc)Xc[a](void 0,!0)}),k.cors=!!Yc&&"withCredentials"in Yc,Yc=k.ajax=!!Yc,Yc&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xc[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zc(){try{return new a.XMLHttpRequest}catch(b){}}function $c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _c=[],ad=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_c.pop()||m.expando+"_"+vc++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ad.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ad.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ad,"$1"+e):b.jsonp!==!1&&(b.url+=(wc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_c.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bd=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bd)return bd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cd=a.document.documentElement;function dd(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dd(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cd;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cd})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dd(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=Lb(k.pixelPosition,function(a,c){return c?(c=Jb(a,b),Hb.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ed=a.jQuery,fd=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fd),b&&a.jQuery===m&&(a.jQuery=ed),m},typeof b===K&&(a.jQuery=a.$=m),m});
|
app/components/LoadingIndicator/Circle.js
|
ninjaref/ninjaref
|
import React from 'react';
import PropTypes from 'prop-types';
import styled, { keyframes } from 'styled-components';
const circleFadeDelay = keyframes`
0%,
39%,
100% {
opacity: 0;
}
40% {
opacity: 1;
}
`;
const Circle = (props) => {
const CirclePrimitive = styled.div`
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
${props.rotate && `
-webkit-transform: rotate(${props.rotate}deg);
-ms-transform: rotate(${props.rotate}deg);
transform: rotate(${props.rotate}deg);
`}
&:before {
content: '';
display: block;
margin: 0 auto;
width: 15%;
height: 15%;
background-color: #999;
border-radius: 100%;
animation: ${circleFadeDelay} 1.2s infinite ease-in-out both;
${props.delay && `
-webkit-animation-delay: ${props.delay}s;
animation-delay: ${props.delay}s;
`}
}
`;
return <CirclePrimitive />;
};
Circle.propTypes = {
delay: PropTypes.number,
rotate: PropTypes.number,
};
export default Circle;
|
src/containers/Widgets/widget-column.js
|
EncontrAR/backoffice
|
import React, { Component } from 'react';
export default class IsoWidgetsColumn extends Component {
render() {
const {
width,
gutterTop,
gutterRight,
gutterBottom,
gutterLeft,
padding,
children,
align,
} = this.props;
const alignContent = this.props.align === 'start'
? 'flex-start'
: this.props.align === 'end'
? 'flex-end'
: this.props.align === 'center'
? 'center'
: this.props.align === 'stretch' ? 'stretch' : '';
const columnStyle = {
display: 'flex',
flexWrap: 'wrap',
flexDirection: 'row',
marginTop: gutterTop,
marginRight: gutterRight,
marginBottom: gutterBottom,
marginLeft: gutterLeft,
padding: padding,
width: this.props.width,
alignContent: alignContent,
};
return (
<div className="isoWidgetsColumn" style={columnStyle}>
{this.props.children}
</div>
);
}
}
|
src-client/scripts/auth-view.js
|
jordanledford/Expresso
|
import React from 'react'
import ReactDOM from 'react-dom'
import Backbone from 'backbone'
import $ from 'jquery'
import ACTIONS from './user-actions.js'
const AuthView = React.createClass({
_submitAuth: function(evt){
evt.preventDefault()
let newUser = {
name: evt.target.name.value,
password: evt.target.password.value
}
console.log(newUser)
ACTIONS.registerUser(newUser)
},
render: function(){
return(
<div className = "row text-center">
<form className = "col-sm-offset-3 col-sm-6 " id="auth-form" onSubmit = {this._submitAuth}>
<a href = "#"><i className="fa fa-home fa-2x " aria-hidden="true"></i></a>
<h2 className = "">Login or Sign Up</h2>
<div className = "form-group">
<label htmlFor = "name"> </label>
<input type = "text" className="form-control" id="name" placeholder="Enter Name" />
</div>
<div className="form-group">
<label htmlFor = "password"></label>
<input type = "password" className="form-control" id="password" placeholder="Enter Password"/>
</div>
<input type = "submit" className="btn btn-default" />
</form>
</div>
)
}
})
module.exports = AuthView
|
client/src/routes.js
|
larrystone/BC-26-More-Recipes
|
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import Home from './components/Home';
import AllRecipes from './components/allrecipes';
import RecipeDetails from './components/recipedetails';
import MyRecipes from './components/myrecipes';
import Favorites from './components/favorites';
import Profile from './components/profile';
import PageNotFound from './components/commons/PageNotFound';
import requireAuth from './utils/requireAuth';
/**
* @description Routes component
*
* @returns {object} routes
*
*/
const routes = () => (
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/recipes" component={requireAuth(AllRecipes)} />
<Route exact path="/myrecipes" component={requireAuth(MyRecipes)} />
<Route path="/recipe/:id" component={requireAuth(RecipeDetails)} />
<Route path="/favorites" component={requireAuth(Favorites)} />
<Route path="/profile/:userId" component={requireAuth(Profile)} />
<Route path="/*" component={PageNotFound} />
</Switch>
);
export default (
routes
);
|
ajax/libs/react-router/0.9.3/react-router.min.js
|
mzdani/cdnjs
|
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.ReactRouter=e()}}(function(){var define;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(_dereq_,module){var LocationActions={PUSH:"push",REPLACE:"replace",POP:"pop"};module.exports=LocationActions},{}],2:[function(_dereq_,module){var LocationActions=_dereq_("../actions/LocationActions"),ImitateBrowserBehavior={updateScrollPosition:function(position,actionType){switch(actionType){case LocationActions.PUSH:case LocationActions.REPLACE:window.scrollTo(0,0);break;case LocationActions.POP:window.scrollTo(position.x,position.y)}}};module.exports=ImitateBrowserBehavior},{"../actions/LocationActions":1}],3:[function(_dereq_,module){var ScrollToTopBehavior={updateScrollPosition:function(){window.scrollTo(0,0)}};module.exports=ScrollToTopBehavior},{}],4:[function(_dereq_,module){function DefaultRoute(props){return Route(merge(props,{path:null,isDefault:!0}))}var merge=_dereq_("react/lib/merge"),Route=_dereq_("./Route");module.exports=DefaultRoute},{"./Route":8,"react/lib/merge":41}],5:[function(_dereq_,module){function isLeftClickEvent(event){return 0===event.button}function isModifiedEvent(event){return!!(event.metaKey||event.altKey||event.ctrlKey||event.shiftKey)}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,merge=_dereq_("react/lib/merge"),ActiveState=_dereq_("../mixins/ActiveState"),Navigation=_dereq_("../mixins/Navigation"),Link=React.createClass({displayName:"Link",mixins:[ActiveState,Navigation],propTypes:{activeClassName:React.PropTypes.string.isRequired,to:React.PropTypes.string.isRequired,params:React.PropTypes.object,query:React.PropTypes.object,onClick:React.PropTypes.func},getDefaultProps:function(){return{activeClassName:"active"}},handleClick:function(event){var clickResult,allowTransition=!0;this.props.onClick&&(clickResult=this.props.onClick(event)),!isModifiedEvent(event)&&isLeftClickEvent(event)&&((clickResult===!1||event.defaultPrevented===!0)&&(allowTransition=!1),event.preventDefault(),allowTransition&&this.transitionTo(this.props.to,this.props.params,this.props.query))},getHref:function(){return this.makeHref(this.props.to,this.props.params,this.props.query)},getClassName:function(){var className=this.props.className||"";return this.isActive(this.props.to,this.props.params,this.props.query)&&(className+=" "+this.props.activeClassName),className},render:function(){var props=merge(this.props,{href:this.getHref(),className:this.getClassName(),onClick:this.handleClick});return React.DOM.a(props,this.props.children)}});module.exports=Link},{"../mixins/ActiveState":15,"../mixins/Navigation":18,"react/lib/merge":41}],6:[function(_dereq_,module){function NotFoundRoute(props){return Route(merge(props,{path:null,catchAll:!0}))}var merge=_dereq_("react/lib/merge"),Route=_dereq_("./Route");module.exports=NotFoundRoute},{"./Route":8,"react/lib/merge":41}],7:[function(_dereq_,module){function createRedirectHandler(to,_params,_query){return React.createClass({statics:{willTransitionTo:function(transition,params,query){transition.redirect(to,_params||params,_query||query)}},render:function(){return null}})}function Redirect(props){return Route({name:props.name,path:props.from||props.path||"*",handler:createRedirectHandler(props.to,props.params,props.query)})}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,Route=_dereq_("./Route");module.exports=Redirect},{"./Route":8}],8:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,withoutProperties=_dereq_("../utils/withoutProperties"),RESERVED_PROPS={handler:!0,path:!0,defaultRoute:!0,notFoundRoute:!0,paramNames:!0,children:!0},Route=React.createClass({displayName:"Route",statics:{getUnreservedProps:function(props){return withoutProperties(props,RESERVED_PROPS)}},propTypes:{handler:React.PropTypes.any.isRequired,path:React.PropTypes.string,name:React.PropTypes.string},render:function(){throw new Error("The <Route> component should not be rendered directly. You may be missing a <Routes> wrapper around your list of routes.")}});module.exports=Route},{"../utils/withoutProperties":29}],9:[function(_dereq_,module){function makeMatch(route,params){return{route:route,params:params}}function getRootMatch(matches){return matches[matches.length-1]}function findMatches(path,routes,defaultRoute,notFoundRoute){for(var route,params,matches=null,i=0,len=routes.length;len>i;++i){if(route=routes[i],matches=findMatches(path,route.props.children,route.props.defaultRoute,route.props.notFoundRoute),null!=matches){var rootParams=getRootMatch(matches).params;return params=route.props.paramNames.reduce(function(params,paramName){return params[paramName]=rootParams[paramName],params},{}),matches.unshift(makeMatch(route,params)),matches}if(params=Path.extractParams(route.props.path,path))return[makeMatch(route,params)]}return defaultRoute&&(params=Path.extractParams(defaultRoute.props.path,path))?[makeMatch(defaultRoute,params)]:notFoundRoute&&(params=Path.extractParams(notFoundRoute.props.path,path))?[makeMatch(notFoundRoute,params)]:matches}function hasMatch(matches,match){return matches.some(function(m){if(m.route!==match.route)return!1;for(var property in m.params)if(m.params[property]!==match.params[property])return!1;return!0})}function updateMatchComponents(matches,refs){for(var component,i=0;component=refs.__activeRoute__;)matches[i++].component=component,refs=component.refs}function computeNextState(component,transition,callback){if(component.state.path===transition.path)return callback();var currentMatches=component.state.matches,nextMatches=component.match(transition.path);warning(nextMatches,'No route matches path "'+transition.path+'". Make sure you have <Route path="'+transition.path+'"> somewhere in your routes'),nextMatches||(nextMatches=[]);var fromMatches,toMatches;currentMatches.length?(updateMatchComponents(currentMatches,component.refs),fromMatches=currentMatches.filter(function(match){return!hasMatch(nextMatches,match)}),toMatches=nextMatches.filter(function(match){return!hasMatch(currentMatches,match)})):(fromMatches=[],toMatches=nextMatches);var query=Path.extractQuery(transition.path)||{};runTransitionFromHooks(fromMatches,transition,function(error){return error||transition.isAborted?callback(error):void runTransitionToHooks(toMatches,transition,query,function(error){if(error||transition.isAborted)return callback(error);var matches=currentMatches.slice(0,currentMatches.length-fromMatches.length).concat(toMatches),rootMatch=getRootMatch(matches),params=rootMatch&&rootMatch.params||{},routes=matches.map(function(match){return match.route});callback(null,{path:transition.path,matches:matches,activeRoutes:routes,activeParams:params,activeQuery:query})})})}function runTransitionFromHooks(matches,transition,callback){var hooks=reversedArray(matches).map(function(match){return function(){var handler=match.route.props.handler;if(!transition.isAborted&&handler.willTransitionFrom)return handler.willTransitionFrom(transition,match.component);var promise=transition.promise;return delete transition.promise,promise}});runHooks(hooks,callback)}function runTransitionToHooks(matches,transition,query,callback){var hooks=matches.map(function(match){return function(){var handler=match.route.props.handler;!transition.isAborted&&handler.willTransitionTo&&handler.willTransitionTo(transition,match.params,query);var promise=transition.promise;return delete transition.promise,promise}});runHooks(hooks,callback)}function runHooks(hooks,callback){try{var promise=hooks.reduce(function(promise,hook){return promise?promise.then(hook):hook()},null)}catch(error){return callback(error)}promise?promise.then(function(){setTimeout(callback)},function(error){setTimeout(function(){callback(error)})}):callback()}function returnNull(){return null}function computeHandlerProps(matches,query){var handler=returnNull,props={ref:null,params:null,query:null,activeRouteHandler:handler,key:null};return reversedArray(matches).forEach(function(match){var route=match.route;props=Route.getUnreservedProps(route.props),props.ref="__activeRoute__",props.params=match.params,props.query=query,props.activeRouteHandler=handler,route.props.addHandlerKey&&(props.key=Path.injectParams(route.props.path,match.params)),handler=function(props,addedProps){if(arguments.length>2&&"undefined"!=typeof arguments[2])throw new Error("Passing children to a route handler is not supported");return route.props.handler(copyProperties(props,addedProps))}.bind(this,props)}),props}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,warning=_dereq_("react/lib/warning"),invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,copyProperties=_dereq_("react/lib/copyProperties"),PathStore=_dereq_("../stores/PathStore"),HashLocation=_dereq_("../locations/HashLocation"),reversedArray=_dereq_("../utils/reversedArray"),Transition=_dereq_("../utils/Transition"),Redirect=_dereq_("../utils/Redirect"),Path=_dereq_("../utils/Path"),Route=_dereq_("./Route"),BrowserTransitionHandling={handleTransitionError:function(component,error){throw error},handleAbortedTransition:function(component,transition){var reason=transition.abortReason;reason instanceof Redirect?component.replaceWith(reason.to,reason.params,reason.query):component.goBack()}},ServerTransitionHandling={handleTransitionError:function(){},handleAbortedTransition:function(){}},TransitionHandling=canUseDOM?BrowserTransitionHandling:ServerTransitionHandling,ActiveContext=_dereq_("../mixins/ActiveContext"),LocationContext=_dereq_("../mixins/LocationContext"),RouteContext=_dereq_("../mixins/RouteContext"),ScrollContext=_dereq_("../mixins/ScrollContext"),Routes=React.createClass({displayName:"Routes",mixins:[ActiveContext,LocationContext,RouteContext,ScrollContext],propTypes:{initialPath:React.PropTypes.string,onChange:React.PropTypes.func},getInitialState:function(){return{matches:[]}},componentWillMount:function(){this.handlePathChange(this.props.initialPath)},componentDidMount:function(){PathStore.addChangeListener(this.handlePathChange)},componentWillUnmount:function(){PathStore.removeChangeListener(this.handlePathChange)},handlePathChange:function(_path){var path=_path||PathStore.getCurrentPath(),actionType=PathStore.getCurrentActionType();if(this.state.path!==path){this.state.path&&this.recordScroll(this.state.path);var self=this;this.dispatch(path,function(error,transition){error?TransitionHandling.handleTransitionError(self,error):transition.isAborted?TransitionHandling.handleAbortedTransition(self,transition):(self.updateScroll(path,actionType),self.props.onChange&&self.props.onChange.call(self))})}},match:function(path){return findMatches(Path.withoutQuery(path),this.getRoutes(),this.props.defaultRoute,this.props.notFoundRoute)},dispatch:function(path,callback){var transition=new Transition(this,path),self=this;computeNextState(this,transition,function(error,nextState){return error||null==nextState?callback(error,transition):void self.setState(nextState,function(){callback(null,transition)})})},getHandlerProps:function(){return computeHandlerProps(this.state.matches,this.state.activeQuery)},getActiveComponent:function(){return this.refs.__activeRoute__},getCurrentPath:function(){return this.state.path},makePath:function(to,params,query){var path;if(Path.isAbsolute(to))path=Path.normalize(to);else{var namedRoutes=this.getNamedRoutes(),route=namedRoutes[to];invariant(route,'Unable to find a route named "'+to+'". Make sure you have a <Route name="'+to+'"> defined somewhere in your <Routes>'),path=route.props.path}return Path.withQuery(Path.injectParams(path,params),query)},makeHref:function(to,params,query){var path=this.makePath(to,params,query);return this.getLocation()===HashLocation?"#"+path:path},transitionTo:function(to,params,query){var location=this.getLocation();invariant(location,"You cannot use transitionTo without a location"),location.push(this.makePath(to,params,query))},replaceWith:function(to,params,query){var location=this.getLocation();invariant(location,"You cannot use replaceWith without a location"),location.replace(this.makePath(to,params,query))},goBack:function(){var location=this.getLocation();invariant(location,"You cannot use goBack without a location"),location.pop()},render:function(){var match=this.state.matches[0];return null==match?null:match.route.props.handler(this.getHandlerProps())},childContextTypes:{currentPath:React.PropTypes.string,makePath:React.PropTypes.func.isRequired,makeHref:React.PropTypes.func.isRequired,transitionTo:React.PropTypes.func.isRequired,replaceWith:React.PropTypes.func.isRequired,goBack:React.PropTypes.func.isRequired},getChildContext:function(){return{currentPath:this.getCurrentPath(),makePath:this.makePath,makeHref:this.makeHref,transitionTo:this.transitionTo,replaceWith:this.replaceWith,goBack:this.goBack}}});module.exports=Routes},{"../locations/HashLocation":11,"../mixins/ActiveContext":14,"../mixins/LocationContext":17,"../mixins/RouteContext":19,"../mixins/ScrollContext":20,"../stores/PathStore":21,"../utils/Path":22,"../utils/Redirect":24,"../utils/Transition":25,"../utils/reversedArray":27,"./Route":8,"react/lib/ExecutionEnvironment":36,"react/lib/copyProperties":37,"react/lib/invariant":39,"react/lib/warning":45}],10:[function(_dereq_,module,exports){exports.DefaultRoute=_dereq_("./components/DefaultRoute"),exports.Link=_dereq_("./components/Link"),exports.NotFoundRoute=_dereq_("./components/NotFoundRoute"),exports.Redirect=_dereq_("./components/Redirect"),exports.Route=_dereq_("./components/Route"),exports.Routes=_dereq_("./components/Routes"),exports.ActiveState=_dereq_("./mixins/ActiveState"),exports.CurrentPath=_dereq_("./mixins/CurrentPath"),exports.Navigation=_dereq_("./mixins/Navigation")},{"./components/DefaultRoute":4,"./components/Link":5,"./components/NotFoundRoute":6,"./components/Redirect":7,"./components/Route":8,"./components/Routes":9,"./mixins/ActiveState":15,"./mixins/CurrentPath":16,"./mixins/Navigation":18}],11:[function(_dereq_,module){function getHashPath(){return window.location.hash.substr(1)}function ensureSlash(){var path=getHashPath();return"/"===path.charAt(0)?!0:(HashLocation.replace("/"+path),!1)}function onHashChange(){if(ensureSlash()){{getHashPath()}_onChange({type:_actionType||LocationActions.POP,path:getHashPath()}),_actionType=null}}var _actionType,_onChange,LocationActions=_dereq_("../actions/LocationActions"),getWindowPath=_dereq_("../utils/getWindowPath"),HashLocation={setup:function(onChange){_onChange=onChange,ensureSlash(),window.addEventListener?window.addEventListener("hashchange",onHashChange,!1):window.attachEvent("onhashchange",onHashChange)},teardown:function(){window.removeEventListener?window.removeEventListener("hashchange",onHashChange,!1):window.detachEvent("onhashchange",onHashChange)},push:function(path){_actionType=LocationActions.PUSH,window.location.hash=path},replace:function(path){_actionType=LocationActions.REPLACE,window.location.replace(getWindowPath()+"#"+path)},pop:function(){_actionType=LocationActions.POP,window.history.back()},getCurrentPath:getHashPath,toString:function(){return"<HashLocation>"}};module.exports=HashLocation},{"../actions/LocationActions":1,"../utils/getWindowPath":26}],12:[function(_dereq_,module){function onPopState(){_onChange({type:LocationActions.POP,path:getWindowPath()})}var _onChange,LocationActions=_dereq_("../actions/LocationActions"),getWindowPath=_dereq_("../utils/getWindowPath"),HistoryLocation={setup:function(onChange){_onChange=onChange,window.addEventListener?window.addEventListener("popstate",onPopState,!1):window.attachEvent("popstate",onPopState)},teardown:function(){window.removeEventListener?window.removeEventListener("popstate",onPopState,!1):window.detachEvent("popstate",onPopState)},push:function(path){window.history.pushState({path:path},"",path),_onChange({type:LocationActions.PUSH,path:getWindowPath()})},replace:function(path){window.history.replaceState({path:path},"",path),_onChange({type:LocationActions.REPLACE,path:getWindowPath()})},pop:function(){window.history.back()},getCurrentPath:getWindowPath,toString:function(){return"<HistoryLocation>"}};module.exports=HistoryLocation},{"../actions/LocationActions":1,"../utils/getWindowPath":26}],13:[function(_dereq_,module){var getWindowPath=_dereq_("../utils/getWindowPath"),RefreshLocation={push:function(path){window.location=path},replace:function(path){window.location.replace(path)},pop:function(){window.history.back()},getCurrentPath:getWindowPath,toString:function(){return"<RefreshLocation>"}};module.exports=RefreshLocation},{"../utils/getWindowPath":26}],14:[function(_dereq_,module){function routeIsActive(activeRoutes,routeName){return activeRoutes.some(function(route){return route.props.name===routeName})}function paramsAreActive(activeParams,params){for(var property in params)if(String(activeParams[property])!==String(params[property]))return!1;return!0}function queryIsActive(activeQuery,query){for(var property in query)if(String(activeQuery[property])!==String(query[property]))return!1;return!0}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,copyProperties=_dereq_("react/lib/copyProperties"),ActiveContext={propTypes:{initialActiveState:React.PropTypes.object},getDefaultProps:function(){return{initialActiveState:{}}},getInitialState:function(){var state=this.props.initialActiveState;return{activeRoutes:state.activeRoutes||[],activeParams:state.activeParams||{},activeQuery:state.activeQuery||{}}},getActiveRoutes:function(){return this.state.activeRoutes.slice(0)},getActiveParams:function(){return copyProperties({},this.state.activeParams)},getActiveQuery:function(){return copyProperties({},this.state.activeQuery)},isActive:function(routeName,params,query){var isActive=routeIsActive(this.state.activeRoutes,routeName)&¶msAreActive(this.state.activeParams,params);return query?isActive&&queryIsActive(this.state.activeQuery,query):isActive},childContextTypes:{activeRoutes:React.PropTypes.array.isRequired,activeParams:React.PropTypes.object.isRequired,activeQuery:React.PropTypes.object.isRequired,isActive:React.PropTypes.func.isRequired},getChildContext:function(){return{activeRoutes:this.getActiveRoutes(),activeParams:this.getActiveParams(),activeQuery:this.getActiveQuery(),isActive:this.isActive}}};module.exports=ActiveContext},{"react/lib/copyProperties":37}],15:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,ActiveState={contextTypes:{activeRoutes:React.PropTypes.array.isRequired,activeParams:React.PropTypes.object.isRequired,activeQuery:React.PropTypes.object.isRequired,isActive:React.PropTypes.func.isRequired},getActiveRoutes:function(){return this.context.activeRoutes},getActiveParams:function(){return this.context.activeParams},getActiveQuery:function(){return this.context.activeQuery},isActive:function(to,params,query){return this.context.isActive(to,params,query)}};module.exports=ActiveState},{}],16:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,CurrentPath={contextTypes:{currentPath:React.PropTypes.string.isRequired},getCurrentPath:function(){return this.context.currentPath}};module.exports=CurrentPath},{}],17:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,HashLocation=_dereq_("../locations/HashLocation"),HistoryLocation=_dereq_("../locations/HistoryLocation"),RefreshLocation=_dereq_("../locations/RefreshLocation"),PathStore=_dereq_("../stores/PathStore"),supportsHistory=_dereq_("../utils/supportsHistory"),NAMED_LOCATIONS={none:null,hash:HashLocation,history:HistoryLocation,refresh:RefreshLocation},LocationContext={propTypes:{location:function(props,propName,componentName){var location=props[propName];return"string"!=typeof location||location in NAMED_LOCATIONS?void 0:new Error('Unknown location "'+location+'", see '+componentName)}},getDefaultProps:function(){return{location:canUseDOM?HashLocation:null}},getInitialState:function(){var location=this.props.location;return"string"==typeof location&&(location=NAMED_LOCATIONS[location]),location!==HistoryLocation||supportsHistory()||(location=RefreshLocation),{location:location}},componentWillMount:function(){var location=this.getLocation();invariant(null==location||canUseDOM,"Cannot use location without a DOM"),location&&PathStore.setup(location)},getLocation:function(){return this.state.location},childContextTypes:{location:React.PropTypes.object},getChildContext:function(){return{location:this.getLocation()}}};module.exports=LocationContext},{"../locations/HashLocation":11,"../locations/HistoryLocation":12,"../locations/RefreshLocation":13,"../stores/PathStore":21,"../utils/supportsHistory":28,"react/lib/ExecutionEnvironment":36,"react/lib/invariant":39}],18:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,Navigation={contextTypes:{makePath:React.PropTypes.func.isRequired,makeHref:React.PropTypes.func.isRequired,transitionTo:React.PropTypes.func.isRequired,replaceWith:React.PropTypes.func.isRequired,goBack:React.PropTypes.func.isRequired},makePath:function(to,params,query){return this.context.makePath(to,params,query)},makeHref:function(to,params,query){return this.context.makeHref(to,params,query)},transitionTo:function(to,params,query){this.context.transitionTo(to,params,query)},replaceWith:function(to,params,query){this.context.replaceWith(to,params,query)},goBack:function(){this.context.goBack()}};module.exports=Navigation},{}],19:[function(_dereq_,module){function processRoute(route,container,namedRoutes){var props=route.props;invariant(React.isValidClass(props.handler),'The handler for the "%s" route must be a valid React class',props.name||props.path);var parentPath=container&&container.props.path||"/";if(!props.path&&!props.name||props.isDefault||props.catchAll)props.path=parentPath,props.catchAll&&(props.path+="*");else{var path=props.path||props.name;Path.isAbsolute(path)||(path=Path.join(parentPath,path)),props.path=Path.normalize(path)}if(props.paramNames=Path.extractParamNames(props.path),container&&Array.isArray(container.props.paramNames)&&container.props.paramNames.forEach(function(paramName){invariant(-1!==props.paramNames.indexOf(paramName),'The nested route path "%s" is missing the "%s" parameter of its parent path "%s"',props.path,paramName,container.props.path)}),props.name){var existingRoute=namedRoutes[props.name];invariant(!existingRoute||route===existingRoute,'You cannot use the name "%s" for more than one route',props.name),namedRoutes[props.name]=route}return props.catchAll?(invariant(container,"<NotFoundRoute> must have a parent <Route>"),invariant(null==container.props.notFoundRoute,"You may not have more than one <NotFoundRoute> per <Route>"),container.props.notFoundRoute=route,null):props.isDefault?(invariant(container,"<DefaultRoute> must have a parent <Route>"),invariant(null==container.props.defaultRoute,"You may not have more than one <DefaultRoute> per <Route>"),container.props.defaultRoute=route,null):(props.children=processRoutes(props.children,route,namedRoutes),route)}function processRoutes(children,container,namedRoutes){var routes=[];return React.Children.forEach(children,function(child){(child=processRoute(child,container,namedRoutes))&&routes.push(child)}),routes}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,invariant=_dereq_("react/lib/invariant"),Path=_dereq_("../utils/Path"),RouteContext={getInitialState:function(){var namedRoutes={};return{routes:processRoutes(this.props.children,this,namedRoutes),namedRoutes:namedRoutes}},getRoutes:function(){return this.state.routes},getNamedRoutes:function(){return this.state.namedRoutes},getRouteByName:function(routeName){return this.state.namedRoutes[routeName]||null},childContextTypes:{routes:React.PropTypes.array.isRequired,namedRoutes:React.PropTypes.object.isRequired},getChildContext:function(){return{routes:this.getRoutes(),namedRoutes:this.getNamedRoutes()}}};module.exports=RouteContext},{"../utils/Path":22,"react/lib/invariant":39}],20:[function(_dereq_,module){function getWindowScrollPosition(){return invariant(canUseDOM,"Cannot get current scroll position without a DOM"),{x:window.scrollX,y:window.scrollY}}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,ImitateBrowserBehavior=_dereq_("../behaviors/ImitateBrowserBehavior"),ScrollToTopBehavior=_dereq_("../behaviors/ScrollToTopBehavior"),NAMED_SCROLL_BEHAVIORS={none:null,browser:ImitateBrowserBehavior,imitateBrowser:ImitateBrowserBehavior,scrollToTop:ScrollToTopBehavior},ScrollContext={propTypes:{scrollBehavior:function(props,propName,componentName){var behavior=props[propName];return"string"!=typeof behavior||behavior in NAMED_SCROLL_BEHAVIORS?void 0:new Error('Unknown scroll behavior "'+behavior+'", see '+componentName)}},getDefaultProps:function(){return{scrollBehavior:canUseDOM?ImitateBrowserBehavior:null}},getInitialState:function(){var behavior=this.props.scrollBehavior;return"string"==typeof behavior&&(behavior=NAMED_SCROLL_BEHAVIORS[behavior]),{scrollBehavior:behavior}},componentWillMount:function(){var behavior=this.getScrollBehavior();invariant(null==behavior||canUseDOM,"Cannot use scroll behavior without a DOM"),null!=behavior&&(this._scrollPositions={})},recordScroll:function(path){this._scrollPositions&&(this._scrollPositions[path]=getWindowScrollPosition())},updateScroll:function(path,actionType){var behavior=this.getScrollBehavior();null!=behavior&&this._scrollPositions.hasOwnProperty(path)&&behavior.updateScrollPosition(this._scrollPositions[path],actionType)},getScrollBehavior:function(){return this.state.scrollBehavior},childContextTypes:{scrollBehavior:React.PropTypes.object},getChildContext:function(){return{scrollBehavior:this.getScrollBehavior()}}};module.exports=ScrollContext},{"../behaviors/ImitateBrowserBehavior":2,"../behaviors/ScrollToTopBehavior":3,"react/lib/ExecutionEnvironment":36,"react/lib/invariant":39}],21:[function(_dereq_,module){function notifyChange(){_events.emit(CHANGE_EVENT)}function handleLocationChangeAction(action){_currentPath!==action.path&&(_currentPath=action.path,_currentActionType=action.type,notifyChange())}var _currentLocation,_currentActionType,invariant=_dereq_("react/lib/invariant"),EventEmitter=_dereq_("events").EventEmitter,CHANGE_EVENT=(_dereq_("../actions/LocationActions"),"change"),_events=new EventEmitter,_currentPath="/",PathStore={addChangeListener:function(listener){_events.addListener(CHANGE_EVENT,listener)},removeChangeListener:function(listener){_events.removeListener(CHANGE_EVENT,listener)},removeAllChangeListeners:function(){_events.removeAllListeners(CHANGE_EVENT)},setup:function(location){invariant(null==_currentLocation||_currentLocation===location,"You cannot use %s and %s on the same page",_currentLocation,location),_currentLocation!==location&&(location.setup&&location.setup(handleLocationChangeAction),_currentPath=location.getCurrentPath()),_currentLocation=location},teardown:function(){_currentLocation&&_currentLocation.teardown&&_currentLocation.teardown(),_currentLocation=_currentActionType=null,_currentPath="/",PathStore.removeAllChangeListeners()},getCurrentPath:function(){return _currentPath},getCurrentActionType:function(){return _currentActionType}};module.exports=PathStore},{"../actions/LocationActions":1,events:30,"react/lib/invariant":39}],22:[function(_dereq_,module){function encodeURL(url){return encodeURIComponent(url).replace(/%20/g,"+")}function decodeURL(url){return decodeURIComponent(url.replace(/\+/g," "))}function encodeURLPath(path){return String(path).split("/").map(encodeURL).join("/")}function compilePattern(pattern){if(!(pattern in _compiledPatterns)){var paramNames=[],source=pattern.replace(paramCompileMatcher,function(match,paramName){return paramName?(paramNames.push(paramName),"([^/?#]+)"):"*"===match?(paramNames.push("splat"),"(.*?)"):"\\"+match});_compiledPatterns[pattern]={matcher:new RegExp("^"+source+"$","i"),paramNames:paramNames}}return _compiledPatterns[pattern]}var invariant=_dereq_("react/lib/invariant"),merge=_dereq_("qs/lib/utils").merge,qs=_dereq_("qs"),paramCompileMatcher=/:([a-zA-Z_$][a-zA-Z0-9_$]*)|[*.()\[\]\\+|{}^$]/g,paramInjectMatcher=/:([a-zA-Z_$][a-zA-Z0-9_$]*)|[*]/g,queryMatcher=/\?(.+)/,_compiledPatterns={},Path={extractParamNames:function(pattern){return compilePattern(pattern).paramNames},extractParams:function(pattern,path){var object=compilePattern(pattern),match=decodeURL(path).match(object.matcher);if(!match)return null;var params={};return object.paramNames.forEach(function(paramName,index){params[paramName]=match[index+1]}),params},injectParams:function(pattern,params){params=params||{};var splatIndex=0;return pattern.replace(paramInjectMatcher,function(match,paramName){paramName=paramName||"splat",invariant(null!=params[paramName],'Missing "'+paramName+'" parameter for path "'+pattern+'"');var segment;return"splat"===paramName&&Array.isArray(params[paramName])?(segment=params[paramName][splatIndex++],invariant(null!=segment,"Missing splat # "+splatIndex+' for path "'+pattern+'"')):segment=params[paramName],encodeURLPath(segment)})},extractQuery:function(path){var match=path.match(queryMatcher);return match&&qs.parse(match[1])},withoutQuery:function(path){return path.replace(queryMatcher,"")},withQuery:function(path,query){var existingQuery=Path.extractQuery(path);existingQuery&&(query=query?merge(existingQuery,query):existingQuery);var queryString=query&&qs.stringify(query);return queryString?Path.withoutQuery(path)+"?"+queryString:path},isAbsolute:function(path){return"/"===path.charAt(0)},normalize:function(path){return path.replace(/^\/*/,"/")},join:function(a,b){return a.replace(/\/*$/,"/")+b}};module.exports=Path},{qs:31,"qs/lib/utils":35,"react/lib/invariant":39}],23:[function(_dereq_,module){var Promise=_dereq_("when/lib/Promise");module.exports=Promise},{"when/lib/Promise":46}],24:[function(_dereq_,module){function Redirect(to,params,query){this.to=to,this.params=params,this.query=query}module.exports=Redirect},{}],25:[function(_dereq_,module){function Transition(routesComponent,path){this.routesComponent=routesComponent,this.path=path,this.abortReason=null,this.isAborted=!1}var mixInto=_dereq_("react/lib/mixInto"),Promise=_dereq_("./Promise"),Redirect=_dereq_("./Redirect");mixInto(Transition,{abort:function(reason){this.abortReason=reason,this.isAborted=!0},redirect:function(to,params,query){this.abort(new Redirect(to,params,query))},wait:function(value){this.promise=Promise.resolve(value)},retry:function(){this.routesComponent.replaceWith(this.path)}}),module.exports=Transition},{"./Promise":23,"./Redirect":24,"react/lib/mixInto":44}],26:[function(_dereq_,module){function getWindowPath(){return window.location.pathname+window.location.search
}module.exports=getWindowPath},{}],27:[function(_dereq_,module){function reversedArray(array){return array.slice(0).reverse()}module.exports=reversedArray},{}],28:[function(_dereq_,module){function supportsHistory(){var ua=navigator.userAgent;return-1===ua.indexOf("Android 2.")&&-1===ua.indexOf("Android 4.0")||-1===ua.indexOf("Mobile Safari")||-1!==ua.indexOf("Chrome")?window.history&&"pushState"in window.history:!1}module.exports=supportsHistory},{}],29:[function(_dereq_,module){function withoutProperties(object,properties){var result={};for(var property in object)object.hasOwnProperty(property)&&!properties[property]&&(result[property]=object[property]);return result}module.exports=withoutProperties},{}],30:[function(_dereq_,module){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return"function"==typeof arg}function isNumber(arg){return"number"==typeof arg}function isObject(arg){return"object"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||0>n||isNaN(n))throw TypeError("n must be a positive number");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),"error"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length))throw er=arguments[1],er instanceof Error?er:TypeError('Uncaught, unspecified "error" event.');if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:for(len=arguments.length,args=new Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];handler.apply(this,args)}else if(isObject(handler)){for(len=arguments.length,args=new Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];for(listeners=handler.slice(),len=listeners.length,i=0;len>i;i++)listeners[i].apply(this,args)}return!0},EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener),this._events[type]?isObject(this._events[type])?this._events[type].push(listener):this._events[type]=[this._events[type],listener]:this._events[type]=listener,isObject(this._events[type])&&!this._events[type].warned){var m;m=isUndefined(this._maxListeners)?EventEmitter.defaultMaxListeners:this._maxListeners,m&&m>0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length),"function"==typeof console.trace&&console.trace())}return this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError("listener must be a function");var fired=!1;return g.listener=listener,this.on(type,g),this},EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],this._events.removeListener&&this.emit("removeListener",type,listener);else if(isObject(list)){for(i=length;i-->0;)if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}if(0>position)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit("removeListener",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)"removeListener"!==key&&this.removeAllListeners(key);return this.removeAllListeners("removeListener"),this._events={},this}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.listenerCount=function(emitter,type){var ret;return ret=emitter._events&&emitter._events[type]?isFunction(emitter._events[type])?1:emitter._events[type].length:0}},{}],31:[function(_dereq_,module){module.exports=_dereq_("./lib")},{"./lib":32}],32:[function(_dereq_,module){var Stringify=_dereq_("./stringify"),Parse=_dereq_("./parse");module.exports={stringify:Stringify,parse:Parse}},{"./parse":33,"./stringify":34}],33:[function(_dereq_,module){var Utils=_dereq_("./utils"),internals={delimiter:"&",depth:5,arrayLimit:20,parameterLimit:1e3};internals.parseValues=function(str,options){for(var obj={},parts=str.split(options.delimiter,1/0===options.parameterLimit?void 0:options.parameterLimit),i=0,il=parts.length;il>i;++i){var part=parts[i],pos=-1===part.indexOf("]=")?part.indexOf("="):part.indexOf("]=")+1;if(-1===pos)obj[Utils.decode(part)]="";else{var key=Utils.decode(part.slice(0,pos)),val=Utils.decode(part.slice(pos+1));obj[key]=obj[key]?[].concat(obj[key]).concat(val):val}}return obj},internals.parseObject=function(chain,val,options){if(!chain.length)return val;var root=chain.shift(),obj={};if("[]"===root)obj=[],obj=obj.concat(internals.parseObject(chain,val,options));else{var cleanRoot="["===root[0]&&"]"===root[root.length-1]?root.slice(1,root.length-1):root,index=parseInt(cleanRoot,10);!isNaN(index)&&root!==cleanRoot&&index<=options.arrayLimit?(obj=[],obj[index]=internals.parseObject(chain,val,options)):obj[cleanRoot]=internals.parseObject(chain,val,options)}return obj},internals.parseKeys=function(key,val,options){if(key){var parent=/^([^\[\]]*)/,child=/(\[[^\[\]]*\])/g,segment=parent.exec(key);if(!Object.prototype.hasOwnProperty(segment[1])){var keys=[];segment[1]&&keys.push(segment[1]);for(var i=0;null!==(segment=child.exec(key))&&i<options.depth;)++i,Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g,""))||keys.push(segment[1]);return segment&&keys.push("["+key.slice(segment.index)+"]"),internals.parseObject(keys,val,options)}}},module.exports=function(str,options){if(""===str||null===str||"undefined"==typeof str)return{};options=options||{},options.delimiter="string"==typeof options.delimiter||Utils.isRegExp(options.delimiter)?options.delimiter:internals.delimiter,options.depth="number"==typeof options.depth?options.depth:internals.depth,options.arrayLimit="number"==typeof options.arrayLimit?options.arrayLimit:internals.arrayLimit,options.parameterLimit="number"==typeof options.parameterLimit?options.parameterLimit:internals.parameterLimit;for(var tempObj="string"==typeof str?internals.parseValues(str,options):str,obj={},keys=Object.keys(tempObj),i=0,il=keys.length;il>i;++i){var key=keys[i],newObj=internals.parseKeys(key,tempObj[key],options);obj=Utils.merge(obj,newObj)}return Utils.compact(obj)}},{"./utils":35}],34:[function(_dereq_,module){var Utils=_dereq_("./utils"),internals={delimiter:"&"};internals.stringify=function(obj,prefix){if(Utils.isBuffer(obj)?obj=obj.toString():obj instanceof Date?obj=obj.toISOString():null===obj&&(obj=""),"string"==typeof obj||"number"==typeof obj||"boolean"==typeof obj)return[encodeURIComponent(prefix)+"="+encodeURIComponent(obj)];var values=[];for(var key in obj)obj.hasOwnProperty(key)&&(values=values.concat(internals.stringify(obj[key],prefix+"["+key+"]")));return values},module.exports=function(obj,options){options=options||{};var delimiter="undefined"==typeof options.delimiter?internals.delimiter:options.delimiter,keys=[];for(var key in obj)obj.hasOwnProperty(key)&&(keys=keys.concat(internals.stringify(obj[key],key)));return keys.join(delimiter)}},{"./utils":35}],35:[function(_dereq_,module,exports){exports.arrayToObject=function(source){for(var obj={},i=0,il=source.length;il>i;++i)"undefined"!=typeof source[i]&&(obj[i]=source[i]);return obj},exports.merge=function(target,source){if(!source)return target;if(Array.isArray(source)){for(var i=0,il=source.length;il>i;++i)"undefined"!=typeof source[i]&&(target[i]="object"==typeof target[i]?exports.merge(target[i],source[i]):source[i]);return target}if(Array.isArray(target)){if("object"!=typeof source)return target.push(source),target;target=exports.arrayToObject(target)}for(var keys=Object.keys(source),k=0,kl=keys.length;kl>k;++k){var key=keys[k],value=source[key];target[key]=value&&"object"==typeof value&&target[key]?exports.merge(target[key],value):value}return target},exports.decode=function(str){try{return decodeURIComponent(str.replace(/\+/g," "))}catch(e){return str}},exports.compact=function(obj,refs){if("object"!=typeof obj||null===obj)return obj;refs=refs||[];var lookup=refs.indexOf(obj);if(-1!==lookup)return refs[lookup];if(refs.push(obj),Array.isArray(obj)){for(var compacted=[],i=0,l=obj.length;l>i;++i)"undefined"!=typeof obj[i]&&compacted.push(obj[i]);return compacted}for(var keys=Object.keys(obj),i=0,il=keys.length;il>i;++i){var key=keys[i];obj[key]=exports.compact(obj[key],refs)}return obj},exports.isRegExp=function(obj){return"[object RegExp]"===Object.prototype.toString.call(obj)},exports.isBuffer=function(obj){return"undefined"!=typeof Buffer?Buffer.isBuffer(obj):!1}},{}],36:[function(_dereq_,module){"use strict";var canUseDOM=!("undefined"==typeof window||!window.document||!window.document.createElement),ExecutionEnvironment={canUseDOM:canUseDOM,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:canUseDOM&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:canUseDOM&&!!window.screen,isInWorker:!canUseDOM};module.exports=ExecutionEnvironment},{}],37:[function(_dereq_,module){function copyProperties(obj,a,b,c,d,e,f){obj=obj||{};for(var v,args=[a,b,c,d,e],ii=0;args[ii];){v=args[ii++];for(var k in v)obj[k]=v[k];v.hasOwnProperty&&v.hasOwnProperty("toString")&&"undefined"!=typeof v.toString&&obj.toString!==v.toString&&(obj.toString=v.toString)}return obj}module.exports=copyProperties},{}],38:[function(_dereq_,module){function makeEmptyFunction(arg){return function(){return arg}}function emptyFunction(){}var copyProperties=_dereq_("./copyProperties");copyProperties(emptyFunction,{thatReturns:makeEmptyFunction,thatReturnsFalse:makeEmptyFunction(!1),thatReturnsTrue:makeEmptyFunction(!0),thatReturnsNull:makeEmptyFunction(null),thatReturnsThis:function(){return this},thatReturnsArgument:function(arg){return arg}}),module.exports=emptyFunction},{"./copyProperties":37}],39:[function(_dereq_,module){"use strict";var invariant=function(condition,format,a,b,c,d,e,f){if(!condition){var error;if(void 0===format)error=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var args=[a,b,c,d,e,f],argIndex=0;error=new Error("Invariant Violation: "+format.replace(/%s/g,function(){return args[argIndex++]}))}throw error.framesToPop=1,error}};module.exports=invariant},{}],40:[function(_dereq_,module){"use strict";var invariant=_dereq_("./invariant"),keyMirror=function(obj){var key,ret={};invariant(obj instanceof Object&&!Array.isArray(obj));for(key in obj)obj.hasOwnProperty(key)&&(ret[key]=key);return ret};module.exports=keyMirror},{"./invariant":39}],41:[function(_dereq_,module){"use strict";var mergeInto=_dereq_("./mergeInto"),merge=function(one,two){var result={};return mergeInto(result,one),mergeInto(result,two),result};module.exports=merge},{"./mergeInto":43}],42:[function(_dereq_,module){"use strict";var invariant=_dereq_("./invariant"),keyMirror=_dereq_("./keyMirror"),MAX_MERGE_DEPTH=36,isTerminal=function(o){return"object"!=typeof o||null===o},mergeHelpers={MAX_MERGE_DEPTH:MAX_MERGE_DEPTH,isTerminal:isTerminal,normalizeMergeArg:function(arg){return void 0===arg||null===arg?{}:arg},checkMergeArrayArgs:function(one,two){invariant(Array.isArray(one)&&Array.isArray(two))},checkMergeObjectArgs:function(one,two){mergeHelpers.checkMergeObjectArg(one),mergeHelpers.checkMergeObjectArg(two)},checkMergeObjectArg:function(arg){invariant(!isTerminal(arg)&&!Array.isArray(arg))},checkMergeIntoObjectArg:function(arg){invariant(!(isTerminal(arg)&&"function"!=typeof arg||Array.isArray(arg)))},checkMergeLevel:function(level){invariant(MAX_MERGE_DEPTH>level)},checkArrayStrategy:function(strategy){invariant(void 0===strategy||strategy in mergeHelpers.ArrayStrategies)},ArrayStrategies:keyMirror({Clobber:!0,IndexByIndex:!0})};module.exports=mergeHelpers},{"./invariant":39,"./keyMirror":40}],43:[function(_dereq_,module){"use strict";function mergeInto(one,two){if(checkMergeIntoObjectArg(one),null!=two){checkMergeObjectArg(two);for(var key in two)two.hasOwnProperty(key)&&(one[key]=two[key])}}var mergeHelpers=_dereq_("./mergeHelpers"),checkMergeObjectArg=mergeHelpers.checkMergeObjectArg,checkMergeIntoObjectArg=mergeHelpers.checkMergeIntoObjectArg;module.exports=mergeInto},{"./mergeHelpers":42}],44:[function(_dereq_,module){"use strict";var mixInto=function(constructor,methodBag){var methodName;for(methodName in methodBag)methodBag.hasOwnProperty(methodName)&&(constructor.prototype[methodName]=methodBag[methodName])};module.exports=mixInto},{}],45:[function(_dereq_,module){"use strict";var emptyFunction=_dereq_("./emptyFunction"),warning=emptyFunction;module.exports=warning},{"./emptyFunction":38}],46:[function(_dereq_,module){!function(define){"use strict";define(function(_dereq_){var makePromise=_dereq_("./makePromise"),Scheduler=_dereq_("./Scheduler"),async=_dereq_("./async");return makePromise({scheduler:new Scheduler(async)})})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory(_dereq_)})},{"./Scheduler":48,"./async":49,"./makePromise":50}],47:[function(_dereq_,module){!function(define){"use strict";define(function(){function Queue(capacityPow2){this.head=this.tail=this.length=0,this.buffer=new Array(1<<capacityPow2)}return Queue.prototype.push=function(x){return this.length===this.buffer.length&&this._ensureCapacity(2*this.length),this.buffer[this.tail]=x,this.tail=this.tail+1&this.buffer.length-1,++this.length,this.length},Queue.prototype.shift=function(){var x=this.buffer[this.head];return this.buffer[this.head]=void 0,this.head=this.head+1&this.buffer.length-1,--this.length,x},Queue.prototype._ensureCapacity=function(capacity){var len,head=this.head,buffer=this.buffer,newBuffer=new Array(capacity),i=0;if(0===head)for(len=this.length;len>i;++i)newBuffer[i]=buffer[i];else{for(capacity=buffer.length,len=this.tail;capacity>head;++i,++head)newBuffer[i]=buffer[head];for(head=0;len>head;++i,++head)newBuffer[i]=buffer[head]}this.buffer=newBuffer,this.head=0,this.tail=this.length},Queue})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory()})},{}],48:[function(_dereq_,module){!function(define){"use strict";define(function(_dereq_){function Scheduler(async){this._async=async,this._queue=new Queue(15),this._afterQueue=new Queue(5),this._running=!1;var self=this;this.drain=function(){self._drain()}}function runQueue(queue){for(;queue.length>0;)queue.shift().run()}var Queue=_dereq_("./Queue");return Scheduler.prototype.enqueue=function(task){this._add(this._queue,task)},Scheduler.prototype.afterQueue=function(task){this._add(this._afterQueue,task)},Scheduler.prototype._drain=function(){runQueue(this._queue),this._running=!1,runQueue(this._afterQueue)},Scheduler.prototype._add=function(queue,task){queue.push(task),this._running||(this._running=!0,this._async(this.drain))},Scheduler})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory(_dereq_)})},{"./Queue":47}],49:[function(_dereq_,module){!function(define){"use strict";define(function(_dereq_){var nextTick,MutationObs;return nextTick="undefined"!=typeof process&&null!==process&&"function"==typeof process.nextTick?function(f){process.nextTick(f)}:(MutationObs="function"==typeof MutationObserver&&MutationObserver||"function"==typeof WebKitMutationObserver&&WebKitMutationObserver)?function(document,MutationObserver){function run(){var f=scheduled;scheduled=void 0,f()}var scheduled,el=document.createElement("div"),o=new MutationObserver(run);return o.observe(el,{attributes:!0}),function(f){scheduled=f,el.setAttribute("class","x")}}(document,MutationObs):function(cjsRequire){var vertx;try{vertx=cjsRequire("vertx")}catch(ignore){}if(vertx){if("function"==typeof vertx.runOnLoop)return vertx.runOnLoop;if("function"==typeof vertx.runOnContext)return vertx.runOnContext}var capturedSetTimeout=setTimeout;return function(t){capturedSetTimeout(t,0)}}(_dereq_)})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory(_dereq_)})},{}],50:[function(_dereq_,module){!function(define){"use strict";define(function(){return function(environment){function Promise(resolver,handler){this._handler=resolver===Handler?handler:init(resolver)}function init(resolver){function promiseResolve(x){handler.resolve(x)}function promiseReject(reason){handler.reject(reason)}function promiseNotify(x){handler.notify(x)}var handler=new Pending;try{resolver(promiseResolve,promiseReject,promiseNotify)}catch(e){promiseReject(e)}return handler}function resolve(x){return isPromise(x)?x:new Promise(Handler,new Async(getHandler(x)))}function reject(x){return new Promise(Handler,new Async(new Rejected(x)))}function never(){return foreverPendingPromise}function defer(){return new Promise(Handler,new Pending)}function all(promises){function settleAt(i,x,resolver){this[i]=x,0===--pending&&resolver.become(new Fulfilled(this))}var i,h,x,s,resolver=new Pending,pending=promises.length>>>0,results=new Array(pending);for(i=0;i<promises.length;++i)if(x=promises[i],void 0!==x||i in promises)if(maybeThenable(x))if(h=getHandlerMaybeThenable(x),s=h.state(),0===s)h.fold(settleAt,i,results,resolver);else{if(!(s>0)){unreportRemaining(promises,i+1,h),resolver.become(h);break}results[i]=h.value,--pending}else results[i]=x,--pending;else--pending;return 0===pending&&resolver.become(new Fulfilled(results)),new Promise(Handler,resolver)}function unreportRemaining(promises,start,rejectedHandler){var i,h,x;for(i=start;i<promises.length;++i)x=promises[i],maybeThenable(x)&&(h=getHandlerMaybeThenable(x),h!==rejectedHandler&&h.visit(h,void 0,h._unreport))}function race(promises){if(Object(promises)===promises&&0===promises.length)return never();var i,x,h=new Pending;for(i=0;i<promises.length;++i)x=promises[i],void 0!==x&&i in promises&&getHandler(x).visit(h,h.resolve,h.reject);return new Promise(Handler,h)}function getHandler(x){return isPromise(x)?x._handler.join():maybeThenable(x)?getHandlerUntrusted(x):new Fulfilled(x)}function getHandlerMaybeThenable(x){return isPromise(x)?x._handler.join():getHandlerUntrusted(x)}function getHandlerUntrusted(x){try{var untrustedThen=x.then;return"function"==typeof untrustedThen?new Thenable(untrustedThen,x):new Fulfilled(x)}catch(e){return new Rejected(e)}}function Handler(){}function FailIfRejected(){}function Pending(receiver,inheritedContext){Promise.createContext(this,inheritedContext),this.consumers=void 0,this.receiver=receiver,this.handler=void 0,this.resolved=!1}function Async(handler){this.handler=handler}function Thenable(then,thenable){Pending.call(this),tasks.enqueue(new AssimilateTask(then,thenable,this))}function Fulfilled(x){Promise.createContext(this),this.value=x}function Rejected(x){Promise.createContext(this),this.id=++errorId,this.value=x,this.handled=!1,this.reported=!1,this._report()}function ReportTask(rejection,context){this.rejection=rejection,this.context=context}function UnreportTask(rejection){this.rejection=rejection}function cycle(){return new Rejected(new TypeError("Promise cycle"))}function ContinuationTask(continuation,handler){this.continuation=continuation,this.handler=handler}function ProgressTask(value,handler){this.handler=handler,this.value=value}function AssimilateTask(then,thenable,resolver){this._then=then,this.thenable=thenable,this.resolver=resolver}function tryAssimilate(then,thenable,resolve,reject,notify){try{then.call(thenable,resolve,reject,notify)}catch(e){reject(e)}}function isPromise(x){return x instanceof Promise}function maybeThenable(x){return("object"==typeof x||"function"==typeof x)&&null!==x}function runContinuation1(f,h,receiver,next){return"function"!=typeof f?next.become(h):(Promise.enterContext(h),tryCatchReject(f,h.value,receiver,next),void Promise.exitContext())}function runContinuation3(f,x,h,receiver,next){return"function"!=typeof f?next.become(h):(Promise.enterContext(h),tryCatchReject3(f,x,h.value,receiver,next),void Promise.exitContext())}function runNotify(f,x,h,receiver,next){return"function"!=typeof f?next.notify(x):(Promise.enterContext(h),tryCatchReturn(f,x,receiver,next),void Promise.exitContext())}function tryCatchReject(f,x,thisArg,next){try{next.become(getHandler(f.call(thisArg,x)))}catch(e){next.become(new Rejected(e))}}function tryCatchReject3(f,x,y,thisArg,next){try{f.call(thisArg,x,y,next)}catch(e){next.become(new Rejected(e))}}function tryCatchReturn(f,x,thisArg,next){try{next.notify(f.call(thisArg,x))}catch(e){next.notify(e)}}function inherit(Parent,Child){Child.prototype=objectCreate(Parent.prototype),Child.prototype.constructor=Child}function noop(){}var tasks=environment.scheduler,objectCreate=Object.create||function(proto){function Child(){}return Child.prototype=proto,new Child};Promise.resolve=resolve,Promise.reject=reject,Promise.never=never,Promise._defer=defer,Promise._handler=getHandler,Promise.prototype.then=function(onFulfilled,onRejected){var parent=this._handler,state=parent.join().state();if("function"!=typeof onFulfilled&&state>0||"function"!=typeof onRejected&&0>state)return new this.constructor(Handler,parent);var p=this._beget(),child=p._handler;return parent.chain(child,parent.receiver,onFulfilled,onRejected,arguments.length>2?arguments[2]:void 0),p},Promise.prototype["catch"]=function(onRejected){return this.then(void 0,onRejected)},Promise.prototype._beget=function(){var parent=this._handler,child=new Pending(parent.receiver,parent.join().context);return new this.constructor(Handler,child)},Promise.all=all,Promise.race=race,Handler.prototype.when=Handler.prototype.become=Handler.prototype.notify=Handler.prototype.fail=Handler.prototype._unreport=Handler.prototype._report=noop,Handler.prototype._state=0,Handler.prototype.state=function(){return this._state},Handler.prototype.join=function(){for(var h=this;void 0!==h.handler;)h=h.handler;return h},Handler.prototype.chain=function(to,receiver,fulfilled,rejected,progress){this.when({resolver:to,receiver:receiver,fulfilled:fulfilled,rejected:rejected,progress:progress})},Handler.prototype.visit=function(receiver,fulfilled,rejected,progress){this.chain(failIfRejected,receiver,fulfilled,rejected,progress)},Handler.prototype.fold=function(f,z,c,to){this.visit(to,function(x){f.call(c,z,x,this)},to.reject,to.notify)},inherit(Handler,FailIfRejected),FailIfRejected.prototype.become=function(h){h.fail()};var failIfRejected=new FailIfRejected;inherit(Handler,Pending),Pending.prototype._state=0,Pending.prototype.resolve=function(x){this.become(getHandler(x))},Pending.prototype.reject=function(x){this.resolved||this.become(new Rejected(x))},Pending.prototype.join=function(){if(!this.resolved)return this;for(var h=this;void 0!==h.handler;)if(h=h.handler,h===this)return this.handler=cycle();return h},Pending.prototype.run=function(){var q=this.consumers,handler=this.join();this.consumers=void 0;for(var i=0;i<q.length;++i)handler.when(q[i])},Pending.prototype.become=function(handler){this.resolved||(this.resolved=!0,this.handler=handler,void 0!==this.consumers&&tasks.enqueue(this),void 0!==this.context&&handler._report(this.context))},Pending.prototype.when=function(continuation){this.resolved?tasks.enqueue(new ContinuationTask(continuation,this.handler)):void 0===this.consumers?this.consumers=[continuation]:this.consumers.push(continuation)},Pending.prototype.notify=function(x){this.resolved||tasks.enqueue(new ProgressTask(x,this))},Pending.prototype.fail=function(context){var c="undefined"==typeof context?this.context:context;this.resolved&&this.handler.join().fail(c)},Pending.prototype._report=function(context){this.resolved&&this.handler.join()._report(context)},Pending.prototype._unreport=function(){this.resolved&&this.handler.join()._unreport()},inherit(Handler,Async),Async.prototype.when=function(continuation){tasks.enqueue(new ContinuationTask(continuation,this))},Async.prototype._report=function(context){this.join()._report(context)},Async.prototype._unreport=function(){this.join()._unreport()},inherit(Pending,Thenable),inherit(Handler,Fulfilled),Fulfilled.prototype._state=1,Fulfilled.prototype.fold=function(f,z,c,to){runContinuation3(f,z,this,c,to)},Fulfilled.prototype.when=function(cont){runContinuation1(cont.fulfilled,this,cont.receiver,cont.resolver)};var errorId=0;inherit(Handler,Rejected),Rejected.prototype._state=-1,Rejected.prototype.fold=function(f,z,c,to){to.become(this)},Rejected.prototype.when=function(cont){"function"==typeof cont.rejected&&this._unreport(),runContinuation1(cont.rejected,this,cont.receiver,cont.resolver)},Rejected.prototype._report=function(context){tasks.afterQueue(new ReportTask(this,context))},Rejected.prototype._unreport=function(){this.handled=!0,tasks.afterQueue(new UnreportTask(this))},Rejected.prototype.fail=function(context){Promise.onFatalRejection(this,void 0===context?this.context:context)},ReportTask.prototype.run=function(){this.rejection.handled||(this.rejection.reported=!0,Promise.onPotentiallyUnhandledRejection(this.rejection,this.context))},UnreportTask.prototype.run=function(){this.rejection.reported&&Promise.onPotentiallyUnhandledRejectionHandled(this.rejection)},Promise.createContext=Promise.enterContext=Promise.exitContext=Promise.onPotentiallyUnhandledRejection=Promise.onPotentiallyUnhandledRejectionHandled=Promise.onFatalRejection=noop;var foreverPendingHandler=new Handler,foreverPendingPromise=new Promise(Handler,foreverPendingHandler);return ContinuationTask.prototype.run=function(){this.handler.join().when(this.continuation)},ProgressTask.prototype.run=function(){var q=this.handler.consumers;if(void 0!==q)for(var c,i=0;i<q.length;++i)c=q[i],runNotify(c.progress,this.value,this.handler,c.receiver,c.resolver)},AssimilateTask.prototype.run=function(){function _resolve(x){h.resolve(x)}function _reject(x){h.reject(x)}function _notify(x){h.notify(x)}var h=this.resolver;tryAssimilate(this._then,this.thenable,_resolve,_reject,_notify)},Promise}})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory()})},{}]},{},[10])(10)});
|
ajax/libs/jquery/1.8.2/jquery.js
|
jieter/cdnjs
|
/*!
* jQuery JavaScript Library v1.8.2
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: Thu Sep 20 2012 21:13:05 GMT-0400 (Eastern Daylight Time)
*/
(function( window, undefined ) {
var
// A central reference to the root jQuery(document)
rootjQuery,
// The deferred used on DOM ready
readyList,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
location = window.location,
navigator = window.navigator,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// Save a reference to some core methods
core_push = Array.prototype.push,
core_slice = Array.prototype.slice,
core_indexOf = Array.prototype.indexOf,
core_toString = Object.prototype.toString,
core_hasOwn = Object.prototype.hasOwnProperty,
core_trim = String.prototype.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,
// Used for detecting and trimming whitespace
core_rnotwhite = /\S/,
core_rspace = /\s+/,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return ( letter + "" ).toUpperCase();
},
// The ready event handler and self cleanup method
DOMContentLoaded = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
} else if ( document.readyState === "complete" ) {
// we're here because readyState === "complete" in oldIE
// which is good enough for us to call the dom ready!
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
},
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = ( context && context.nodeType ? context.ownerDocument || context : document );
// scripts is true for back-compat
selector = jQuery.parseHTML( match[1], doc, true );
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
this.attr.call( selector, context, true );
}
return jQuery.merge( this, selector );
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.8.2",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
eq: function( i ) {
i = +i;
return i === -1 ?
this.slice( i ) :
this.slice( i, i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ),
"slice", core_slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ core_toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// scripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, scripts ) {
var parsed;
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
scripts = context;
context = 0;
}
context = context || document;
// Single tag
if ( (parsed = rsingleTag.exec( data )) ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] );
return jQuery.merge( [],
(parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes );
},
parseJSON: function( data ) {
if ( !data || typeof data !== "string") {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && core_rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var name,
i = 0,
length = obj.length,
isObj = length === undefined || jQuery.isFunction( obj );
if ( args ) {
if ( isObj ) {
for ( name in obj ) {
if ( callback.apply( obj[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( obj[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in obj ) {
if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var type,
ret = results || [];
if ( arr != null ) {
// The window, strings (and functions) also have 'length'
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
type = jQuery.type( arr );
if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) {
core_push.call( ret, arr );
} else {
jQuery.merge( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value, key,
ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, pass ) {
var exec,
bulk = key == null,
i = 0,
length = elems.length;
// Sets many values
if ( key && typeof key === "object" ) {
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], 1, emptyGet, value );
}
chainable = 1;
// Sets one value
} else if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = pass === undefined && jQuery.isFunction( value );
if ( bulk ) {
// Bulk operations only iterate when executing function values
if ( exec ) {
exec = fn;
fn = function( elem, key, value ) {
return exec.call( jQuery( elem ), value );
};
// Otherwise they run against the entire set
} else {
fn.call( elems, value );
fn = null;
}
}
if ( fn ) {
for (; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
}
chainable = 1;
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready, 1 );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.split( core_rspace ), function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" && ( !options.unique || !self.has( arg ) ) ) {
list.push( arg );
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Control if a given callback is in the list
has: function( fn ) {
return jQuery.inArray( fn, list ) > -1;
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ]( jQuery.isFunction( fn ) ?
function() {
var returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
}
} :
newDefer[ action ]
);
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ] = list.fire
deferred[ tuple[0] ] = list.fire;
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function() {
var support,
all,
a,
select,
opt,
input,
fragment,
eventName,
i,
isSupported,
clickFn,
div = document.createElement("div");
// Preliminary tests
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
all = div.getElementsByTagName("*");
a = div.getElementsByTagName("a")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
// Can't get basic test support
if ( !all || !all.length ) {
return {};
}
// First batch of supports tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: ( div.firstChild.nodeType === 3 ),
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: ( a.getAttribute("href") === "/a" ),
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.5/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: ( input.value === "on" ),
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// Tests for enctype support on a form(#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
boxModel: ( document.compatMode === "CSS1Compat" ),
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
boxSizingReliable: true,
pixelPosition: false
};
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
div.attachEvent( "onclick", clickFn = function() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
});
div.cloneNode( true ).fireEvent("onclick");
div.detachEvent( "onclick", clickFn );
}
// Check if a radio maintains its value
// after being appended to the DOM
input = document.createElement("input");
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
input.setAttribute( "checked", "checked" );
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "name", "t" );
div.appendChild( input );
fragment = document.createDocumentFragment();
fragment.appendChild( div.lastChild );
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
fragment.removeChild( input );
fragment.appendChild( div );
// Technique from Juriy Zaytsev
// http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
// We only care about the case where non-standard event systems
// are used, namely in IE. Short-circuiting here helps us to
// avoid an eval call (in setAttribute) which can cause CSP
// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
if ( div.attachEvent ) {
for ( i in {
submit: true,
change: true,
focusin: true
}) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) {
div.setAttribute( eventName, "return;" );
isSupported = ( typeof div[ eventName ] === "function" );
}
support[ i + "Bubbles" ] = isSupported;
}
}
// Run tests that need a body at doc ready
jQuery(function() {
var container, div, tds, marginDiv,
divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px";
body.insertBefore( container, body.firstChild );
// Construct the test element
div = document.createElement("div");
container.appendChild( div );
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE <= 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior
div.innerHTML = "";
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
support.boxSizing = ( div.offsetWidth === 4 );
support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );
// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = document.createElement("div");
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
div.appendChild( marginDiv );
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== "undefined" ) {
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
// (IE < 8 does this)
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "block";
div.style.overflow = "visible";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
container.style.zoom = 1;
}
// Null elements to avoid leaks in IE
body.removeChild( container );
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
fragment.removeChild( div );
all = a = select = opt = input = fragment = div = null;
return support;
})();
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
jQuery.extend({
cache: {},
deletedIds: [],
// Remove at next major release (1.9/2.0)
uuid: 0,
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i, l,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
},
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var parts, part, attr, name, l,
elem = this[0],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attr = elem.attributes;
for ( l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( !name.indexOf( "data-" ) ) {
name = jQuery.camelCase( name.substring(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
parts = key.split( ".", 2 );
parts[1] = parts[1] ? "." + parts[1] : "";
part = parts[1] + "!";
return jQuery.access( this, function( value ) {
if ( value === undefined ) {
data = this.triggerHandler( "getData" + part, [ parts[0] ] );
// Try to fetch any internally stored data first
if ( data === undefined && elem ) {
data = jQuery.data( elem, key );
data = dataAttr( elem, key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
}
parts[1] = value;
this.each(function() {
var self = jQuery( this );
self.triggerHandler( "setData" + part, parts );
jQuery.data( this, key, value );
self.triggerHandler( "changeData" + part, parts );
});
}, null, value, arguments.length > 1, null, false );
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery.removeData( elem, type + "queue", true );
jQuery.removeData( elem, key, true );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook, fixSpecified,
rclass = /[\t\r\n]/g,
rreturn = /\r/g,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea|)$/i,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classNames, i, l, elem,
setClass, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call(this, j, this.className) );
});
}
if ( value && typeof value === "string" ) {
classNames = value.split( core_rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
var removes, className, elem, c, cl, i, l;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call(this, j, this.className) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
removes = ( value || "" ).split( core_rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 && elem.className ) {
className = (" " + elem.className + " ").replace( rclass, " " );
// loop over each item in the removal list
for ( c = 0, cl = removes.length; c < cl; c++ ) {
// Remove until there is nothing to remove,
while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) {
className = className.replace( " " + removes[ c ] + " " , " " );
}
}
elem.className = value ? jQuery.trim( className ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( core_rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val,
self = jQuery(this);
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, i, max, option,
index = elem.selectedIndex,
values = [],
options = elem.options,
one = elem.type === "select-one";
// Nothing was selected
if ( index < 0 ) {
return null;
}
// Loop through all the selected options
i = one ? index : 0;
max = one ? index + 1 : options.length;
for ( ; i < max; i++ ) {
option = options[ i ];
// Don't return options that are disabled or in a disabled optgroup
if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
(!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
// Fixes Bug #2551 -- select.val() broken in IE after form.reset()
if ( one && !values.length && options.length ) {
return jQuery( options[ index ] ).val();
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
// Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9
attrFn: {},
attr: function( elem, name, value, pass ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) {
return jQuery( elem )[ name ]( value );
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var propName, attrNames, name, isBool,
i = 0;
if ( value && elem.nodeType === 1 ) {
attrNames = value.split( core_rspace );
for ( ; i < attrNames.length; i++ ) {
name = attrNames[ i ];
if ( name ) {
propName = jQuery.propFix[ name ] || name;
isBool = rboolean.test( name );
// See #9699 for explanation of this approach (setting first, then removal)
// Do not do this for boolean attributes (see #10870)
if ( !isBool ) {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
// Set corresponding property to false for boolean attributes
if ( isBool && propName in elem ) {
elem[ propName ] = false;
}
}
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to it's default in case type is set after value
// This is for element creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
},
// Use the value property for back compat
// Use the nodeHook for button elements in IE6/7 (#1954)
value: {
get: function( elem, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.get( elem, name );
}
return name in elem ?
elem.value :
null;
},
set: function( elem, value, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.set( elem, value, name );
}
// Does not return so that setAttribute is also used
elem.value = value;
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return ( elem[ name ] = value );
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
}
});
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode,
property = jQuery.prop( elem, name );
return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
fixSpecified = {
name: true,
id: true,
coords: true
};
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret;
ret = elem.getAttributeNode( name );
return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ?
ret.value :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
ret = document.createAttribute( name );
elem.setAttributeNode( ret );
}
return ( ret.value = value + "" );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
if ( value === "" ) {
value = "false";
}
nodeHook.set( elem, value, name );
}
};
}
// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret === null ? undefined : ret;
}
});
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Normalize to lowercase since IE uppercases css property names
return elem.style.cssText.toLowerCase() || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
});
});
var rformElems = /^(?:textarea|input|select)$/i,
rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/,
rhoverHack = /(?:^|\s)hover(\.\S+|)\b/,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
hoverHack = function( events ) {
return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
};
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
add: function( elem, types, handler, data, selector ) {
var elemData, eventHandle, events,
t, tns, type, namespaces, handleObj,
handleObjIn, handlers, special;
// Don't attach events to noData or text/comment nodes (allow plain objects tho)
if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
events = elemData.events;
if ( !events ) {
elemData.events = events = {};
}
eventHandle = elemData.handle;
if ( !eventHandle ) {
elemData.handle = eventHandle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = jQuery.trim( hoverHack(types) ).split( " " );
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = tns[1];
namespaces = ( tns[2] || "" ).split( "." ).sort();
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: tns[1],
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
handlers = events[ type ];
if ( !handlers ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var t, tns, type, origType, namespaces, origCount,
j, events, special, eventType, handleObj,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = jQuery.trim( hoverHack( types || "" ) ).split(" ");
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = origType = tns[1];
namespaces = tns[2];
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector? special.delegateType : special.bindType ) || type;
eventType = events[ type ] || [];
origCount = eventType.length;
namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
// Remove matching events
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !namespaces || namespaces.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
eventType.splice( j--, 1 );
if ( handleObj.selector ) {
eventType.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( eventType.length === 0 && origCount !== eventType.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery.removeData( elem, "events", true );
}
},
// Events that are safe to short-circuit if no handlers are attached.
// Native DOM events should not be added, they may have inline handlers.
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function( event, data, elem, onlyHandlers ) {
// Don't do events on text and comment nodes
if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {
return;
}
// Event object or event type
var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType,
type = event.type || event,
namespaces = [];
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "!" ) >= 0 ) {
// Exclusive events trigger only for the exact event (no namespaces)
type = type.slice(0, -1);
exclusive = true;
}
if ( type.indexOf( "." ) >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
// No jQuery handlers for this event type, and it can't have inline handlers
return;
}
// Caller can pass in an Event, Object, or just an event type string
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
new jQuery.Event( type, event ) :
// Just the event type (string)
new jQuery.Event( type );
event.type = type;
event.isTrigger = true;
event.exclusive = exclusive;
event.namespace = namespaces.join( "." );
event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";
// Handle a global trigger
if ( !elem ) {
// TODO: Stop taunting the data cache; remove global events and always attach to document
cache = jQuery.cache;
for ( i in cache ) {
if ( cache[ i ].events && cache[ i ].events[ type ] ) {
jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );
}
}
return;
}
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data != null ? jQuery.makeArray( data ) : [];
data.unshift( event );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
eventPath = [[ elem, special.bindType || type ]];
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;
for ( old = elem; cur; cur = cur.parentNode ) {
eventPath.push([ cur, bubbleType ]);
old = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( old === (elem.ownerDocument || document) ) {
eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
}
}
// Fire handlers on the event path
for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {
cur = eventPath[i][0];
event.type = eventPath[i][1];
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Note that this is a bare JS function and not a jQuery handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
// IE<9 dies on focus/blur to hidden element (#1486)
if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = elem[ ontype ];
if ( old ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( old ) {
elem[ ontype ] = old;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event || window.event );
var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related,
handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
delegateCount = handlers.delegateCount,
args = core_slice.call( arguments ),
run_all = !event.exclusive && !event.namespace,
special = jQuery.event.special[ event.type ] || {},
handlerQueue = [];
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers that should run if there are delegated events
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && !(event.button && event.type === "click") ) {
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
// Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
selMatch = {};
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
sel = handleObj.selector;
if ( selMatch[ sel ] === undefined ) {
selMatch[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( selMatch[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, matches: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( handlers.length > delegateCount ) {
handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
}
// Run delegates first; they may want to stop propagation beneath us
for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
matched = handlerQueue[ i ];
event.currentTarget = matched.elem;
for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
handleObj = matched.matches[ j ];
// Triggered event must either 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {
event.data = handleObj.data;
event.handleObj = handleObj;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
// Includes some event props shared by KeyEvent and MouseEvent
// *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 ***
props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop,
originalEvent = event,
fixHook = jQuery.event.fixHooks[ event.type ] || {},
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = jQuery.Event( originalEvent );
for ( i = copy.length; i; ) {
prop = copy[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary (#1925, IE 6/7/8 & Safari2)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Target should not be a text node (#504, Safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8)
event.metaKey = !!event.metaKey;
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
// Some plugins are using, but it's undocumented/deprecated and will be removed.
// The 1.7 special event interface should provide all the hooks needed now.
jQuery.event.handle = jQuery.event.dispatch;
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8 –
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === "undefined" ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj,
selector = handleObj.selector;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "_submit_attached" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "_submit_attached", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "_change_attached", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) { // && selector != null
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
if ( rkeyEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
}
if ( rmouseEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://sizzlejs.com/
*/
(function( window, undefined ) {
var cachedruns,
assertGetIdNotName,
Expr,
getText,
isXML,
contains,
compile,
sortOrder,
hasDuplicate,
outermostContext,
baseHasDuplicate = true,
strundefined = "undefined",
expando = ( "sizcache" + Math.random() ).replace( ".", "" ),
Token = String,
document = window.document,
docElem = document.documentElement,
dirruns = 0,
done = 0,
pop = [].pop,
push = [].push,
slice = [].slice,
// Use a stripped-down indexOf if a native one is unavailable
indexOf = [].indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
// Augment a function for special use by Sizzle
markFunction = function( fn, value ) {
fn[ expando ] = value == null || value;
return fn;
},
createCache = function() {
var cache = {},
keys = [];
return markFunction(function( key, value ) {
// Only keep the most recent entries
if ( keys.push( key ) > Expr.cacheLength ) {
delete cache[ keys.shift() ];
}
return (cache[ key ] = value);
}, cache );
},
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
// Regex
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors)
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
operators = "([*^$|!~]?=)",
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments not in parens/brackets,
// then attribute selectors and non-pseudos (denoted by :),
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)",
// For matchExpr.POS and matchExpr.needsContext
pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace +
"*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
rpseudo = new RegExp( pseudos ),
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,
rnot = /^:not/,
rsibling = /[\x20\t\r\n\f]*[+~]/,
rendsWithNot = /:not\($/,
rheader = /h\d/i,
rinputs = /input|select|textarea|button/i,
rbackslash = /\\(?!\\)/g,
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"POS": new RegExp( pos, "i" ),
"CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
// For use in libraries implementing .is()
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" )
},
// Support
// Used for testing something on an element
assert = function( fn ) {
var div = document.createElement("div");
try {
return fn( div );
} catch (e) {
return false;
} finally {
// release memory in IE
div = null;
}
},
// Check if getElementsByTagName("*") returns only elements
assertTagNameNoComments = assert(function( div ) {
div.appendChild( document.createComment("") );
return !div.getElementsByTagName("*").length;
}),
// Check if getAttribute returns normalized href attributes
assertHrefNotNormalized = assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
div.firstChild.getAttribute("href") === "#";
}),
// Check if attributes should be retrieved by attribute nodes
assertAttributes = assert(function( div ) {
div.innerHTML = "<select></select>";
var type = typeof div.lastChild.getAttribute("multiple");
// IE8 returns a string for some attributes even when not present
return type !== "boolean" && type !== "string";
}),
// Check if getElementsByClassName can be trusted
assertUsableClassName = assert(function( div ) {
// Opera can't find a second classname (in 9.6)
div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {
return false;
}
// Safari 3.2 caches class attributes and doesn't catch changes
div.lastChild.className = "e";
return div.getElementsByClassName("e").length === 2;
}),
// Check if getElementById returns elements by name
// Check if getElementsByName privileges form controls or returns elements by ID
assertUsableName = assert(function( div ) {
// Inject content
div.id = expando + 0;
div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
docElem.insertBefore( div, docElem.firstChild );
// Test
var pass = document.getElementsByName &&
// buggy browsers will return fewer than the correct 2
document.getElementsByName( expando ).length === 2 +
// buggy browsers will return more than the correct 0
document.getElementsByName( expando + 0 ).length;
assertGetIdNotName = !document.getElementById( expando );
// Cleanup
docElem.removeChild( div );
return pass;
});
// If slice is not available, provide a backup
try {
slice.call( docElem.childNodes, 0 )[0].nodeType;
} catch ( e ) {
slice = function( i ) {
var elem,
results = [];
for ( ; (elem = this[i]); i++ ) {
results.push( elem );
}
return results;
};
}
function Sizzle( selector, context, results, seed ) {
results = results || [];
context = context || document;
var match, elem, xml, m,
nodeType = context.nodeType;
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( nodeType !== 1 && nodeType !== 9 ) {
return [];
}
xml = isXML( context );
if ( !xml && !seed ) {
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) {
push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );
return results;
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed, xml );
}
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
return Sizzle( expr, null, null, [ elem ] ).length > 0;
};
// Returns a function to use in pseudos for input types
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
// Returns a function to use in pseudos for buttons
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
// Returns a function to use in pseudos for positionals
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( nodeType ) {
if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
} else {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
}
return ret;
};
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
// Element contains another
contains = Sizzle.contains = docElem.contains ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) );
} :
docElem.compareDocumentPosition ?
function( a, b ) {
return b && !!( a.compareDocumentPosition( b ) & 16 );
} :
function( a, b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
return false;
};
Sizzle.attr = function( elem, name ) {
var val,
xml = isXML( elem );
if ( !xml ) {
name = name.toLowerCase();
}
if ( (val = Expr.attrHandle[ name ]) ) {
return val( elem );
}
if ( xml || assertAttributes ) {
return elem.getAttribute( name );
}
val = elem.getAttributeNode( name );
return val ?
typeof elem[ name ] === "boolean" ?
elem[ name ] ? name : null :
val.specified ? val.value : null :
null;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
// IE6/7 return a modified href
attrHandle: assertHrefNotNormalized ?
{} :
{
"href": function( elem ) {
return elem.getAttribute( "href", 2 );
},
"type": function( elem ) {
return elem.getAttribute("type");
}
},
find: {
"ID": assertGetIdNotName ?
function( id, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
} :
function( id, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( id );
return m ?
m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
[m] :
undefined :
[];
}
},
"TAG": assertTagNameNoComments ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
var elem,
tmp = [],
i = 0;
for ( ; (elem = results[i]); i++ ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
},
"NAME": assertUsableName && function( tag, context ) {
if ( typeof context.getElementsByName !== strundefined ) {
return context.getElementsByName( name );
}
},
"CLASS": assertUsableClassName && function( className, context, xml ) {
if ( typeof context.getElementsByClassName !== strundefined && !xml ) {
return context.getElementsByClassName( className );
}
}
},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( rbackslash, "" );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
3 xn-component of xn+y argument ([+-]?\d*n|)
4 sign of xn-component
5 x of xn-component
6 sign of y-component
7 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1] === "nth" ) {
// nth-child requires argument
if ( !match[2] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) );
match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" );
// other types prohibit arguments
} else if ( match[2] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var unquoted, excess;
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
if ( match[3] ) {
match[2] = match[3];
} else if ( (unquoted = match[4]) ) {
// Only check arguments that contain a pseudo
if ( rpseudo.test(unquoted) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
unquoted = unquoted.slice( 0, excess );
match[0] = match[0].slice( 0, excess );
}
match[2] = unquoted;
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"ID": assertGetIdNotName ?
function( id ) {
id = id.replace( rbackslash, "" );
return function( elem ) {
return elem.getAttribute("id") === id;
};
} :
function( id ) {
id = id.replace( rbackslash, "" );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === id;
};
},
"TAG": function( nodeName ) {
if ( nodeName === "*" ) {
return function() { return true; };
}
nodeName = nodeName.replace( rbackslash, "" ).toLowerCase();
return function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ expando ][ className ];
if ( !pattern ) {
pattern = classCache( className, new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)") );
}
return function( elem ) {
return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
};
},
"ATTR": function( name, operator, check ) {
return function( elem, context ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.substr( result.length - check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, argument, first, last ) {
if ( type === "nth" ) {
return function( elem ) {
var node, diff,
parent = elem.parentNode;
if ( first === 1 && last === 0 ) {
return true;
}
if ( parent ) {
diff = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
diff++;
if ( elem === node ) {
break;
}
}
}
}
// Incorporate the offset (or cast to NaN), then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
};
}
return function( elem ) {
var node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
/* falls through */
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
var nodeType;
elem = elem.firstChild;
while ( elem ) {
if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) {
return false;
}
elem = elem.nextSibling;
}
return true;
},
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"text": function( elem ) {
var type, attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
(type = elem.type) === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type );
},
// Input types
"radio": createInputPseudo("radio"),
"checkbox": createInputPseudo("checkbox"),
"file": createInputPseudo("file"),
"password": createInputPseudo("password"),
"image": createInputPseudo("image"),
"submit": createButtonPseudo("submit"),
"reset": createButtonPseudo("reset"),
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"focus": function( elem ) {
var doc = elem.ownerDocument;
return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href);
},
"active": function( elem ) {
return elem === elem.ownerDocument.activeElement;
},
// Positional types
"first": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length, argument ) {
for ( var i = 0; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length, argument ) {
for ( var i = 1; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
function siblingCheck( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
}
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
return ( !a.compareDocumentPosition || !b.compareDocumentPosition ?
a.compareDocumentPosition :
a.compareDocumentPosition(b) & 4
) ? -1 : 1;
} :
function( a, b ) {
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return a.sourceIndex - b.sourceIndex;
}
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// If the nodes are siblings (or identical) we can do a quick check
if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
// Always assume the presence of duplicates if sort doesn't
// pass them to our comparison function (as in Google Chrome).
[0, 0].sort( sortOrder );
baseHasDuplicate = !hasDuplicate;
// Document sorting and removing duplicates
Sizzle.uniqueSort = function( results ) {
var elem,
i = 1;
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( ; (elem = results[i]); i++ ) {
if ( elem === results[ i - 1 ] ) {
results.splice( i--, 1 );
}
}
}
return results;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type, soFar, groups, preFilters,
cached = tokenCache[ expando ][ selector ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
soFar = soFar.slice( match[0].length );
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
tokens.push( matched = new Token( match.shift() ) );
soFar = soFar.slice( matched.length );
// Cast descendant combinators to space
matched.type = match[0].replace( rtrim, " " );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
// The last two arguments here are (context, xml) for backCompat
(match = preFilters[ type ]( match, document, true ))) ) {
tokens.push( matched = new Token( match.shift() ) );
soFar = soFar.slice( matched.length );
matched.type = type;
matched.matches = match;
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && combinator.dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( checkNonElements || elem.nodeType === 1 ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( !xml ) {
var cache,
dirkey = dirruns + " " + doneName + " ",
cachedkey = dirkey + cachedruns;
while ( (elem = elem[ dir ]) ) {
if ( checkNonElements || elem.nodeType === 1 ) {
if ( (cache = elem[ expando ]) === cachedkey ) {
return elem.sizset;
} else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) {
if ( elem.sizset ) {
return elem;
}
} else {
elem[ expando ] = cachedkey;
if ( matcher( elem, context, xml ) ) {
elem.sizset = true;
return elem;
}
elem.sizset = false;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( checkNonElements || elem.nodeType === 1 ) {
if ( matcher( elem, context, xml ) ) {
return elem;
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
// Positional selectors apply to seed elements, so it is invalid to follow them with relative ones
if ( seed && postFinder ) {
return;
}
var i, elem, postFilterIn,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [], seed ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
postFilterIn = condense( matcherOut, postMap );
postFilter( postFilterIn, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = postFilterIn.length;
while ( i-- ) {
if ( (elem = postFilterIn[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
// Keep seed and results synchronized
if ( seed ) {
// Ignore postFinder because it can't coexist with seed
i = preFilter && matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
seed[ preMap[i] ] = !(results[ preMap[i] ] = elem);
}
}
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ];
} else {
// The concatenated values are (context, xml) for backCompat
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && tokens.join("")
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Nested matchers should use non-integer dirruns
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = superMatcher.el;
}
// Add elements passing elementMatchers directly to results
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
for ( j = 0; (matcher = elementMatchers[j]); j++ ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++superMatcher.el;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
for ( j = 0; (matcher = setMatchers[j]); j++ ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
superMatcher.el = 0;
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ expando ][ selector ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results, seed ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results, seed );
}
return results;
}
function select( selector, context, results, seed, xml ) {
var i, tokens, token, type, find,
match = tokenize( selector ),
j = match.length;
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
context.nodeType === 9 && !xml &&
Expr.relative[ tokens[1].type ] ) {
context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().length );
}
// Fetch a seed set for right-to-left matching
for ( i = matchExpr["POS"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( rbackslash, "" ),
rsibling.test( tokens[0].type ) && context.parentNode || context,
xml
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && tokens.join("");
if ( !selector ) {
push.apply( results, slice.call( seed, 0 ) );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
xml,
results,
rsibling.test( selector )
);
return results;
}
if ( document.querySelectorAll ) {
(function() {
var disconnectedMatch,
oldSelect = select,
rescape = /'|\\/g,
rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
// qSa(:focus) reports false when true (Chrome 21),
// A support test would require too much code (would include document ready)
rbuggyQSA = [":focus"],
// matchesSelector(:focus) reports false when true (Chrome 21),
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
// A support test would require too much code (would include document ready)
// just skip matchesSelector for :active
rbuggyMatches = [ ":active", ":focus" ],
matches = docElem.matchesSelector ||
docElem.mozMatchesSelector ||
docElem.webkitMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector;
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explictly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// IE8 - Some boolean attributes are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here (do not put tests after this one)
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Opera 10-12/IE9 - ^= $= *= and empty values
// Should not select anything
div.innerHTML = "<p test=''></p>";
if ( div.querySelectorAll("[test^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here (do not put tests after this one)
div.innerHTML = "<input type='hidden'/>";
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push(":enabled", ":disabled");
}
});
// rbuggyQSA always contains :focus, so no need for a length check
rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") );
select = function( selector, context, results, seed, xml ) {
// Only use querySelectorAll when not filtering,
// when this is not xml,
// and when no QSA bugs apply
if ( !seed && !xml && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
var groups, i,
old = true,
nid = expando,
newContext = context,
newSelector = context.nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + groups[i].join("");
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results, slice.call( newContext.querySelectorAll(
newSelector
), 0 ) );
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
return oldSelect( selector, context, results, seed, xml );
};
if ( matches ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
try {
matches.call( div, "[test!='']:sizzle" );
rbuggyMatches.push( "!=", pseudos );
} catch ( e ) {}
});
// rbuggyMatches always contains :active and :focus, so no need for a length check
rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") );
Sizzle.matchesSelector = function( elem, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
// rbuggyMatches always contains :active, so no need for an existence check
if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && (!rbuggyQSA || !rbuggyQSA.test( expr )) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, null, null, [ elem ] ).length > 0;
};
}
})();
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Back-compat
function setFilters() {}
Expr.filters = setFilters.prototype = Expr.pseudos;
Expr.setFilters = new setFilters();
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
var runtil = /Until$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
isSimple = /^.[^:#\[\.,]*$/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i, l, length, n, r, ret,
self = this;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
ret = this.pushStack( "", "find", selector );
for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
rneedsContext.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
cur = this[i];
while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
}
cur = cur.parentNode;
}
}
ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
jQuery.fn.andSelf = jQuery.fn.addBack;
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( this.length > 1 && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, core_slice.call( arguments ).join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return ( elem === qualifier ) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem, i ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
rnocache = /<(?:script|object|embed|option|style)/i,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rcheckableType = /^(?:checkbox|radio)$/,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
area: [ 1, "<map>", "</map>" ],
_default: [ 0, "", "" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "X<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( set, this ), "before", this.selector );
}
},
after: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( this, set ), "after", this.selector );
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName( "*" ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function( value ) {
if ( !isDisconnected( this[0] ) ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
}
return this.length ?
this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
this;
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
// Flatten any nested arrays
args = [].concat.apply( [], args );
var results, first, fragment, iNoClone,
i = 0,
value = args[0],
scripts = [],
l = this.length;
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call( this, i, table ? self.html() : undefined );
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
results = jQuery.buildFragment( args, this, scripts );
fragment = results.fragment;
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
// Fragments from the fragment cache must always be cloned and never used in place.
for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) {
callback.call(
table && jQuery.nodeName( this[i], "table" ) ?
findOrAppend( this[i], "tbody" ) :
this[i],
i === iNoClone ?
fragment :
jQuery.clone( fragment, true, true )
);
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
if ( scripts.length ) {
jQuery.each( scripts, function( i, elem ) {
if ( elem.src ) {
if ( jQuery.ajax ) {
jQuery.ajax({
url: elem.src,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
} else {
jQuery.error("no ajax");
}
} else {
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
});
}
}
return this;
}
});
function findOrAppend( elem, tag ) {
return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) );
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function cloneFixAttributes( src, dest ) {
var nodeName;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
if ( dest.clearAttributes ) {
dest.clearAttributes();
}
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
nodeName = dest.nodeName.toLowerCase();
if ( nodeName === "object" ) {
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
// IE blanks contents when cloning scripts
} else if ( nodeName === "script" && dest.text !== src.text ) {
dest.text = src.text;
}
// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute( jQuery.expando );
}
jQuery.buildFragment = function( args, context, scripts ) {
var fragment, cacheable, cachehit,
first = args[ 0 ];
// Set context from what may come in as undefined or a jQuery collection or a node
// Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 &
// also doubles as fix for #8950 where plain objects caused createDocumentFragment exception
context = context || document;
context = !context.nodeType && context[0] || context;
context = context.ownerDocument || context;
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document &&
first.charAt(0) === "<" && !rnocache.test( first ) &&
(jQuery.support.checkClone || !rchecked.test( first )) &&
(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {
// Mark cacheable and look for a hit
cacheable = true;
fragment = jQuery.fragments[ first ];
cachehit = fragment !== undefined;
}
if ( !fragment ) {
fragment = context.createDocumentFragment();
jQuery.clean( args, context, fragment, scripts );
// Update the cache, but only store false
// unless this is a second parsing of the same content
if ( cacheable ) {
jQuery.fragments[ first ] = cachehit && fragment;
}
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
l = insert.length,
parent = this.length === 1 && this[0].parentNode;
if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( ; i < l; i++ ) {
elems = ( i > 0 ? this.clone(true) : this ).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
function getAll( elem ) {
if ( typeof elem.getElementsByTagName !== "undefined" ) {
return elem.getElementsByTagName( "*" );
} else if ( typeof elem.querySelectorAll !== "undefined" ) {
return elem.querySelectorAll( "*" );
} else {
return [];
}
}
// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var srcElements,
destElements,
i,
clone;
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName instead
srcElements = getAll( elem );
destElements = getAll( clone );
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents ) {
srcElements = getAll( elem );
destElements = getAll( clone );
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
srcElements = destElements = null;
// Return the cloned set
return clone;
},
clean: function( elems, context, fragment, scripts ) {
var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags,
safe = context === document && safeFragment,
ret = [];
// Ensure that context is a document
if ( !context || typeof context.createDocumentFragment === "undefined" ) {
context = document;
}
// Use the already-created safe fragment if context permits
for ( i = 0; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Ensure a safe container in which to render the html
safe = safe || createSafeFragment( context );
div = context.createElement("div");
safe.appendChild( div );
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Go to html and back, then peel off extra wrappers
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
depth = wrap[0];
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
hasBody = rtbody.test(elem);
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
// Take out of fragment container (we need a fresh div each time)
div.parentNode.removeChild( div );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
jQuery.merge( ret, elem );
}
}
// Fix #11356: Clear elements from safeFragment
if ( div ) {
elem = div = safe = null;
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
for ( i = 0; (elem = ret[i]) != null; i++ ) {
if ( jQuery.nodeName( elem, "input" ) ) {
fixDefaultChecked( elem );
} else if ( typeof elem.getElementsByTagName !== "undefined" ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
}
// Append elements to a provided document fragment
if ( fragment ) {
// Special handling of each script element
handleScript = function( elem ) {
// Check if we consider it executable
if ( !elem.type || rscriptType.test( elem.type ) ) {
// Detach the script and store it in the scripts array (if provided) or the fragment
// Return truthy to indicate that it has been handled
return scripts ?
scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) :
fragment.appendChild( elem );
}
};
for ( i = 0; (elem = ret[i]) != null; i++ ) {
// Check if we're done after handling an executable script
if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) {
// Append to fragment and handle embedded scripts
fragment.appendChild( elem );
if ( typeof elem.getElementsByTagName !== "undefined" ) {
// handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration
jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript );
// Splice the scripts into ret after their former ancestor and advance our index beyond them
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
i += jsTags.length;
}
}
}
}
return ret;
},
cleanData: function( elems, /* internal */ acceptData ) {
var data, id, elem, type,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
jQuery.deletedIds.push( id );
}
}
}
}
}
});
// Limit scope pollution from any deprecated API
(function() {
var matched, browser;
// Use of jQuery.browser is frowned upon.
// More details: http://api.jquery.com/jQuery.browser
// jQuery.uaMatch maintained for back-compat
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
matched = jQuery.uaMatch( navigator.userAgent );
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = browser;
jQuery.sub = function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
};
})();
var curCSS, iframe, iframeDoc,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ),
elemdisplay = {},
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ],
eventsToggle = jQuery.fn.toggle;
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function isHidden( elem, el ) {
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
function showHide( elements, show ) {
var elem, display,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && elem.style.display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
display = curCSS( elem, "display" );
if ( !values[ index ] && display !== "none" ) {
jQuery._data( elem, "olddisplay", display );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.fn.extend({
css: function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state, fn2 ) {
var bool = typeof state === "boolean";
if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) {
return eventsToggle.apply( this, arguments );
}
return this.each(function() {
if ( bool ? state : isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, numeric, extra ) {
var val, num, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( numeric || extra !== undefined ) {
num = parseFloat( val );
return numeric || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
curCSS = function( elem, name ) {
var ret, width, minWidth, maxWidth,
computed = window.getComputedStyle( elem, null ),
style = elem.style;
if ( computed ) {
ret = computed[ name ];
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if ( document.documentElement.currentStyle ) {
curCSS = function( elem, name ) {
var left, rsLeft,
ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
// we use jQuery.css instead of curCSS here
// because of the reliableMarginRight CSS hook!
val += jQuery.css( elem, extra + cssExpand[ i ], true );
}
// From this point on we use curCSS for maximum performance (relevant in animations)
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
} else {
// at this point, extra isn't content, so add padding
val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
valueIsBorderBox = true,
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
if ( elemdisplay[ nodeName ] ) {
return elemdisplay[ nodeName ];
}
var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ),
display = elem.css("display");
elem.remove();
// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if ( display === "none" || display === "" ) {
// Use the already-created iframe if possible
iframe = document.body.appendChild(
iframe || jQuery.extend( document.createElement("iframe"), {
frameBorder: 0,
width: 0,
height: 0
})
);
// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
// document to it; WebKit & Firefox won't allow reusing the iframe document.
if ( !iframeDoc || !iframe.createElement ) {
iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
iframeDoc.write("<!doctype html><html><body>");
iframeDoc.close();
}
elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) );
display = curCSS( elem, "display" );
document.body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
return display;
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) {
return jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
});
} else {
return getWidthOrHeight( elem, name, extra );
}
}
},
set: function( elem, value, extra ) {
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"
) : 0
);
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there there is no filter style applied in a css rule, we are done
if ( currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" }, function() {
if ( computed ) {
return curCSS( elem, "marginRight" );
}
});
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
var ret = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i,
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ],
expanded = {};
for ( i = 0; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
rselectTextarea = /^(?:select|textarea)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
var
// Document location
ajaxLocParts,
ajaxLocation,
rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rts = /([?&])_=[^&]*/,
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = ["*/"] + ["*"];
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType, list, placeBefore,
dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ),
i = 0,
length = dataTypes.length;
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
for ( ; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
dataType /* internal */, inspected /* internal */ ) {
dataType = dataType || options.dataTypes[ 0 ];
inspected = inspected || {};
inspected[ dataType ] = true;
var selection,
list = structure[ dataType ],
i = 0,
length = list ? list.length : 0,
executeOnly = ( structure === prefilters );
for ( ; i < length && ( executeOnly || !selection ); i++ ) {
selection = list[ i ]( options, originalOptions, jqXHR );
// If we got redirected to another dataType
// we try there if executing only and not done already
if ( typeof selection === "string" ) {
if ( !executeOnly || inspected[ selection ] ) {
selection = undefined;
} else {
options.dataTypes.unshift( selection );
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, selection, inspected );
}
}
}
// If we're only executing or nothing was selected
// we try the catchall dataType if not done already
if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, "*", inspected );
}
// unnecessary when only executing (prefilters)
// but it'll be ignored by the caller in that case
return selection;
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
}
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
// Don't do a request if no elements are being requested
if ( !this.length ) {
return this;
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// Request the remote document
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params,
complete: function( jqXHR, status ) {
if ( callback ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
}
}
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append( responseText.replace( rscript, "" ) )
// Locate the specified elements
.find( selector ) :
// If not, just inject the full result
responseText );
});
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
jQuery.fn[ o ] = function( f ){
return this.on( o, f );
};
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
});
jQuery.extend({
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
if ( settings ) {
// Building a settings object
ajaxExtend( target, jQuery.ajaxSettings );
} else {
// Extending ajaxSettings
settings = target;
target = jQuery.ajaxSettings;
}
ajaxExtend( target, settings );
return target;
},
ajaxSettings: {
url: ajaxLocation,
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
processData: true,
async: true,
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": allTypes
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// List of data converters
// 1) key format is "source_type destination_type" (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
context: true,
url: true
}
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // ifModified key
ifModifiedKey,
// Response headers
responseHeadersString,
responseHeaders,
// transport
transport,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext = callbackContext !== s &&
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks( "once memory" ),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
var lname = name.toLowerCase();
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Cancel the request
abort: function( statusText ) {
statusText = statusText || strAbort;
if ( transport ) {
transport.abort( statusText );
}
done( 0, statusText );
return this;
}
};
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ ifModifiedKey ] = modified;
}
modified = jqXHR.getResponseHeader("Etag");
if ( modified ) {
jQuery.etag[ ifModifiedKey ] = modified;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
isSuccess = ajaxConvert( s, response );
statusText = isSuccess.state;
success = isSuccess.data;
error = isSuccess.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( !statusText || status ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Attach deferreds
deferred.promise( jqXHR );
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.add;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for ( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.always( tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace );
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() ) || false;
s.crossDomain = parts && ( parts.join(":") + ( parts[ 3 ] ? "" : parts[ 1 ] === "http:" ? 80 : 443 ) ) !==
( ajaxLocParts.join(":") + ( ajaxLocParts[ 3 ] ? "" : ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) );
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey = s.url;
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
}
if ( jQuery.etag[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
}
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout( function(){
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch (e) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
return jqXHR;
},
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var ct, type, finalDataType, firstDataType,
contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields;
// Fill responseXXX fields
for ( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
var conv, conv2, current, tmp,
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice(),
prev = dataTypes[ 0 ],
converters = {},
i = 0;
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
// Convert to each sequential dataType, tolerating list modification
for ( ; (current = dataTypes[++i]); ) {
// There's only work to do if current dataType is non-auto
if ( current !== "*" ) {
// Convert response if prev dataType is non-auto and differs from current
if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split(" ");
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.splice( i--, 0, current );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s["throws"] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
// Update prev for next iteration
prev = current;
}
}
return { state: "success", data: response };
}
var oldCallbacks = [],
rquestion = /\?/,
rjsonp = /(=)\?(?=&|$)|\?\?/,
nonce = jQuery.now();
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
data = s.data,
url = s.url,
hasCallback = s.jsonp !== false,
replaceInUrl = hasCallback && rjsonp.test( url ),
replaceInData = hasCallback && !replaceInUrl && typeof data === "string" &&
!( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") &&
rjsonp.test( data );
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
overwritten = window[ callbackName ];
// Insert callback into url or form data
if ( replaceInUrl ) {
s.url = url.replace( rjsonp, "$1" + callbackName );
} else if ( replaceInData ) {
s.data = data.replace( rjsonp, "$1" + callbackName );
} else if ( hasCallback ) {
s.url += ( rquestion.test( url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = "async";
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( 0, 1 );
}
}
};
}
});
var xhrCallbacks,
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject ? function() {
// Abort all pending requests
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( 0, 1 );
}
} : false,
xhrId = 0;
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
(function( xhr ) {
jQuery.extend( jQuery.support, {
ajax: !!xhr,
cors: !!xhr && ( "withCredentials" in xhr )
});
})( jQuery.ajaxSettings.xhr() );
// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var handle, i,
xhr = s.xhr();
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( _ ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status,
statusText,
responseHeaders,
responses,
xml;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occurred
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {};
xml = xhr.responseXML;
// Construct response list
if ( xml && xml.documentElement /* #4958 */ ) {
responses.xml = xml;
}
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
try {
responses.text = xhr.responseText;
} catch( _ ) {
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
if ( !s.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback, 0 );
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback(0,1);
}
}
};
}
});
}
var fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [function( prop, value ) {
var end, unit,
tween = this.createTween( prop, value ),
parts = rfxnum.exec( value ),
target = tween.cur(),
start = +target || 0,
scale = 1,
maxIterations = 20;
if ( parts ) {
end = +parts[2];
unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" && start ) {
// Iteratively approximate from a nonzero starting point
// Prefer the current property, because this process will be trivial if it uses the same units
// Fallback to end or a simple constant
start = jQuery.css( tween.elem, prop, true ) || end || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
tween.unit = unit;
tween.start = start;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end;
}
return tween;
}]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
}, 0 );
return ( fxNow = jQuery.now() );
}
function createTweens( animation, props ) {
jQuery.each( props, function( prop, value ) {
var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( collection[ index ].call( animation, prop, value ) ) {
// we're done with this property
return;
}
}
});
}
function Animation( elem, properties, options ) {
var result,
index = 0,
tweenerIndex = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
percent = 1 - ( remaining / animation.duration || 0 ),
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end, easing ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
createTweens( animation, props );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
anim: animation,
queue: animation.opts.queue,
elem: elem
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
function defaultPrefilter( elem, props, opts ) {
var index, prop, value, length, dataShow, tween, hooks, oldfire,
anim = this,
style = elem.style,
orig = {},
handled = [],
hidden = elem.nodeType && isHidden( elem );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( elem, "display" ) === "inline" &&
jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !jQuery.support.shrinkWrapBlocks ) {
anim.done(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( index in props ) {
value = props[ index ];
if ( rfxtypes.exec( value ) ) {
delete props[ index ];
if ( value === ( hidden ? "hide" : "show" ) ) {
continue;
}
handled.push( index );
}
}
length = handled.length;
if ( length ) {
dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} );
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery.removeData( elem, "fxshow", true );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( index = 0 ; index < length ; index++ ) {
prop = handled[ index ];
tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 );
orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
}
}
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing any value as a 4th parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, false, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Remove in 2.0 - this supports IE8's panic based approach
// to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ||
// special check for .toggle( handler, handler, ... )
( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations resolve immediately
if ( empty ) {
anim.stop( true );
}
};
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
}
});
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth? 1 : 0;
for( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p*Math.PI ) / 2;
}
};
jQuery.timers = [];
jQuery.fx = Tween.prototype.init;
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
};
jQuery.fx.timer = function( timer ) {
if ( timer() && jQuery.timers.push( timer ) && !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.interval = 13;
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Back Compat <1.8 extension point
jQuery.fx.step = {};
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
var rroot = /^(?:body|html)$/i;
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
if ( (body = doc.body) === elem ) {
return jQuery.offset.bodyOffset( elem );
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== "undefined" ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
clientTop = docElem.clientTop || body.clientTop || 0;
clientLeft = docElem.clientLeft || body.clientLeft || 0;
scrollTop = win.pageYOffset || docElem.scrollTop;
scrollLeft = win.pageXOffset || docElem.scrollLeft;
return {
top: box.top + scrollTop - clientTop,
left: box.left + scrollLeft - clientLeft
};
};
jQuery.offset = {
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[0] ) {
return;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || document.body;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return jQuery.access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, value, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
})( window );
|
jest-preprocessor.js
|
hirokai/MicroManagerViewer
|
var ReactTools = require('react-tools');
module.exports = {
process: function(src) {
return ReactTools.transform(src,{harmony:true});
}
};
|
TicketingSystemMVC/Exam.Mvc/Scripts/jquery-1.8.2.min.js
|
ivovachkov/TicketingSystemMVC
|
/*! jQuery v1.8.2 jquery.com | jquery.org/license */
(function(a,b){function G(a){var b=F[a]={};return p.each(a.split(s),function(a,c){b[c]=!0}),b}function J(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(I,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:+d+""===d?+d:H.test(d)?p.parseJSON(d):d}catch(f){}p.data(a,c,d)}else d=b}return d}function K(a){var b;for(b in a){if(b==="data"&&p.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function ba(){return!1}function bb(){return!0}function bh(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function bi(a,b){do a=a[b];while(a&&a.nodeType!==1);return a}function bj(a,b,c){b=b||0;if(p.isFunction(b))return p.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return p.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=p.grep(a,function(a){return a.nodeType===1});if(be.test(b))return p.filter(b,d,!c);b=p.filter(b,d)}return p.grep(a,function(a,d){return p.inArray(a,b)>=0===c})}function bk(a){var b=bl.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function bC(a,b){return a.getElementsByTagName(b)[0]||a.appendChild(a.ownerDocument.createElement(b))}function bD(a,b){if(b.nodeType!==1||!p.hasData(a))return;var c,d,e,f=p._data(a),g=p._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;d<e;d++)p.event.add(b,c,h[c][d])}g.data&&(g.data=p.extend({},g.data))}function bE(a,b){var c;if(b.nodeType!==1)return;b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?(b.parentNode&&(b.outerHTML=a.outerHTML),p.support.html5Clone&&a.innerHTML&&!p.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):c==="input"&&bv.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text),b.removeAttribute(p.expando)}function bF(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bG(a){bv.test(a.type)&&(a.defaultChecked=a.checked)}function bY(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=bW.length;while(e--){b=bW[e]+c;if(b in a)return b}return d}function bZ(a,b){return a=b||a,p.css(a,"display")==="none"||!p.contains(a.ownerDocument,a)}function b$(a,b){var c,d,e=[],f=0,g=a.length;for(;f<g;f++){c=a[f];if(!c.style)continue;e[f]=p._data(c,"olddisplay"),b?(!e[f]&&c.style.display==="none"&&(c.style.display=""),c.style.display===""&&bZ(c)&&(e[f]=p._data(c,"olddisplay",cc(c.nodeName)))):(d=bH(c,"display"),!e[f]&&d!=="none"&&p._data(c,"olddisplay",d))}for(f=0;f<g;f++){c=a[f];if(!c.style)continue;if(!b||c.style.display==="none"||c.style.display==="")c.style.display=b?e[f]||"":"none"}return a}function b_(a,b,c){var d=bP.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function ca(a,b,c,d){var e=c===(d?"border":"content")?4:b==="width"?1:0,f=0;for(;e<4;e+=2)c==="margin"&&(f+=p.css(a,c+bV[e],!0)),d?(c==="content"&&(f-=parseFloat(bH(a,"padding"+bV[e]))||0),c!=="margin"&&(f-=parseFloat(bH(a,"border"+bV[e]+"Width"))||0)):(f+=parseFloat(bH(a,"padding"+bV[e]))||0,c!=="padding"&&(f+=parseFloat(bH(a,"border"+bV[e]+"Width"))||0));return f}function cb(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=!0,f=p.support.boxSizing&&p.css(a,"boxSizing")==="border-box";if(d<=0||d==null){d=bH(a,b);if(d<0||d==null)d=a.style[b];if(bQ.test(d))return d;e=f&&(p.support.boxSizingReliable||d===a.style[b]),d=parseFloat(d)||0}return d+ca(a,b,c||(f?"border":"content"),e)+"px"}function cc(a){if(bS[a])return bS[a];var b=p("<"+a+">").appendTo(e.body),c=b.css("display");b.remove();if(c==="none"||c===""){bI=e.body.appendChild(bI||p.extend(e.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!bJ||!bI.createElement)bJ=(bI.contentWindow||bI.contentDocument).document,bJ.write("<!doctype html><html><body>"),bJ.close();b=bJ.body.appendChild(bJ.createElement(a)),c=bH(b,"display"),e.body.removeChild(bI)}return bS[a]=c,c}function ci(a,b,c,d){var e;if(p.isArray(b))p.each(b,function(b,e){c||ce.test(a)?d(a,e):ci(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&p.type(b)==="object")for(e in b)ci(a+"["+e+"]",b[e],c,d);else d(a,b)}function cz(a){return function(b,c){typeof b!="string"&&(c=b,b="*");var d,e,f,g=b.toLowerCase().split(s),h=0,i=g.length;if(p.isFunction(c))for(;h<i;h++)d=g[h],f=/^\+/.test(d),f&&(d=d.substr(1)||"*"),e=a[d]=a[d]||[],e[f?"unshift":"push"](c)}}function cA(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h,i=a[f],j=0,k=i?i.length:0,l=a===cv;for(;j<k&&(l||!h);j++)h=i[j](c,d,e),typeof h=="string"&&(!l||g[h]?h=b:(c.dataTypes.unshift(h),h=cA(a,c,d,e,h,g)));return(l||!h)&&!g["*"]&&(h=cA(a,c,d,e,"*",g)),h}function cB(a,c){var d,e,f=p.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((f[d]?a:e||(e={}))[d]=c[d]);e&&p.extend(!0,a,e)}function cC(a,c,d){var e,f,g,h,i=a.contents,j=a.dataTypes,k=a.responseFields;for(f in k)f in d&&(c[k[f]]=d[f]);while(j[0]==="*")j.shift(),e===b&&(e=a.mimeType||c.getResponseHeader("content-type"));if(e)for(f in i)if(i[f]&&i[f].test(e)){j.unshift(f);break}if(j[0]in d)g=j[0];else{for(f in d){if(!j[0]||a.converters[f+" "+j[0]]){g=f;break}h||(h=f)}g=g||h}if(g)return g!==j[0]&&j.unshift(g),d[g]}function cD(a,b){var c,d,e,f,g=a.dataTypes.slice(),h=g[0],i={},j=0;a.dataFilter&&(b=a.dataFilter(b,a.dataType));if(g[1])for(c in a.converters)i[c.toLowerCase()]=a.converters[c];for(;e=g[++j];)if(e!=="*"){if(h!=="*"&&h!==e){c=i[h+" "+e]||i["* "+e];if(!c)for(d in i){f=d.split(" ");if(f[1]===e){c=i[h+" "+f[0]]||i["* "+f[0]];if(c){c===!0?c=i[d]:i[d]!==!0&&(e=f[0],g.splice(j--,0,e));break}}}if(c!==!0)if(c&&a["throws"])b=c(b);else try{b=c(b)}catch(k){return{state:"parsererror",error:c?k:"No conversion from "+h+" to "+e}}}h=e}return{state:"success",data:b}}function cL(){try{return new a.XMLHttpRequest}catch(b){}}function cM(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function cU(){return setTimeout(function(){cN=b},0),cN=p.now()}function cV(a,b){p.each(b,function(b,c){var d=(cT[b]||[]).concat(cT["*"]),e=0,f=d.length;for(;e<f;e++)if(d[e].call(a,b,c))return})}function cW(a,b,c){var d,e=0,f=0,g=cS.length,h=p.Deferred().always(function(){delete i.elem}),i=function(){var b=cN||cU(),c=Math.max(0,j.startTime+j.duration-b),d=1-(c/j.duration||0),e=0,f=j.tweens.length;for(;e<f;e++)j.tweens[e].run(d);return h.notifyWith(a,[j,d,c]),d<1&&f?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:p.extend({},b),opts:p.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:cN||cU(),duration:c.duration,tweens:[],createTween:function(b,c,d){var e=p.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(e),e},stop:function(b){var c=0,d=b?j.tweens.length:0;for(;c<d;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;cX(k,j.opts.specialEasing);for(;e<g;e++){d=cS[e].call(j,a,k,j.opts);if(d)return d}return cV(j,k),p.isFunction(j.opts.start)&&j.opts.start.call(a,j),p.fx.timer(p.extend(i,{anim:j,queue:j.opts.queue,elem:a})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}function cX(a,b){var c,d,e,f,g;for(c in a){d=p.camelCase(c),e=b[d],f=a[c],p.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=p.cssHooks[d];if(g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}}function cY(a,b,c){var d,e,f,g,h,i,j,k,l=this,m=a.style,n={},o=[],q=a.nodeType&&bZ(a);c.queue||(j=p._queueHooks(a,"fx"),j.unqueued==null&&(j.unqueued=0,k=j.empty.fire,j.empty.fire=function(){j.unqueued||k()}),j.unqueued++,l.always(function(){l.always(function(){j.unqueued--,p.queue(a,"fx").length||j.empty.fire()})})),a.nodeType===1&&("height"in b||"width"in b)&&(c.overflow=[m.overflow,m.overflowX,m.overflowY],p.css(a,"display")==="inline"&&p.css(a,"float")==="none"&&(!p.support.inlineBlockNeedsLayout||cc(a.nodeName)==="inline"?m.display="inline-block":m.zoom=1)),c.overflow&&(m.overflow="hidden",p.support.shrinkWrapBlocks||l.done(function(){m.overflow=c.overflow[0],m.overflowX=c.overflow[1],m.overflowY=c.overflow[2]}));for(d in b){f=b[d];if(cP.exec(f)){delete b[d];if(f===(q?"hide":"show"))continue;o.push(d)}}g=o.length;if(g){h=p._data(a,"fxshow")||p._data(a,"fxshow",{}),q?p(a).show():l.done(function(){p(a).hide()}),l.done(function(){var b;p.removeData(a,"fxshow",!0);for(b in n)p.style(a,b,n[b])});for(d=0;d<g;d++)e=o[d],i=l.createTween(e,q?h[e]:0),n[e]=h[e]||p.style(a,e),e in h||(h[e]=i.start,q&&(i.end=i.start,i.start=e==="width"||e==="height"?1:0))}}function cZ(a,b,c,d,e){return new cZ.prototype.init(a,b,c,d,e)}function c$(a,b){var c,d={height:a},e=0;b=b?1:0;for(;e<4;e+=2-b)c=bV[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function da(a){return p.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}var c,d,e=a.document,f=a.location,g=a.navigator,h=a.jQuery,i=a.$,j=Array.prototype.push,k=Array.prototype.slice,l=Array.prototype.indexOf,m=Object.prototype.toString,n=Object.prototype.hasOwnProperty,o=String.prototype.trim,p=function(a,b){return new p.fn.init(a,b,c)},q=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,r=/\S/,s=/\s+/,t=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,u=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,y=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,z=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,A=/^-ms-/,B=/-([\da-z])/gi,C=function(a,b){return(b+"").toUpperCase()},D=function(){e.addEventListener?(e.removeEventListener("DOMContentLoaded",D,!1),p.ready()):e.readyState==="complete"&&(e.detachEvent("onreadystatechange",D),p.ready())},E={};p.fn=p.prototype={constructor:p,init:function(a,c,d){var f,g,h,i;if(!a)return this;if(a.nodeType)return this.context=this[0]=a,this.length=1,this;if(typeof a=="string"){a.charAt(0)==="<"&&a.charAt(a.length-1)===">"&&a.length>=3?f=[null,a,null]:f=u.exec(a);if(f&&(f[1]||!c)){if(f[1])return c=c instanceof p?c[0]:c,i=c&&c.nodeType?c.ownerDocument||c:e,a=p.parseHTML(f[1],i,!0),v.test(f[1])&&p.isPlainObject(c)&&this.attr.call(a,c,!0),p.merge(this,a);g=e.getElementById(f[2]);if(g&&g.parentNode){if(g.id!==f[2])return d.find(a);this.length=1,this[0]=g}return this.context=e,this.selector=a,this}return!c||c.jquery?(c||d).find(a):this.constructor(c).find(a)}return p.isFunction(a)?d.ready(a):(a.selector!==b&&(this.selector=a.selector,this.context=a.context),p.makeArray(a,this))},selector:"",jquery:"1.8.2",length:0,size:function(){return this.length},toArray:function(){return k.call(this)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=p.merge(this.constructor(),a);return d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")"),d},each:function(a,b){return p.each(this,a,b)},ready:function(a){return p.ready.promise().done(a),this},eq:function(a){return a=+a,a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(k.apply(this,arguments),"slice",k.call(arguments).join(","))},map:function(a){return this.pushStack(p.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:j,sort:[].sort,splice:[].splice},p.fn.init.prototype=p.fn,p.extend=p.fn.extend=function(){var a,c,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;typeof h=="boolean"&&(k=h,h=arguments[1]||{},i=2),typeof h!="object"&&!p.isFunction(h)&&(h={}),j===i&&(h=this,--i);for(;i<j;i++)if((a=arguments[i])!=null)for(c in a){d=h[c],e=a[c];if(h===e)continue;k&&e&&(p.isPlainObject(e)||(f=p.isArray(e)))?(f?(f=!1,g=d&&p.isArray(d)?d:[]):g=d&&p.isPlainObject(d)?d:{},h[c]=p.extend(k,g,e)):e!==b&&(h[c]=e)}return h},p.extend({noConflict:function(b){return a.$===p&&(a.$=i),b&&a.jQuery===p&&(a.jQuery=h),p},isReady:!1,readyWait:1,holdReady:function(a){a?p.readyWait++:p.ready(!0)},ready:function(a){if(a===!0?--p.readyWait:p.isReady)return;if(!e.body)return setTimeout(p.ready,1);p.isReady=!0;if(a!==!0&&--p.readyWait>0)return;d.resolveWith(e,[p]),p.fn.trigger&&p(e).trigger("ready").off("ready")},isFunction:function(a){return p.type(a)==="function"},isArray:Array.isArray||function(a){return p.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):E[m.call(a)]||"object"},isPlainObject:function(a){if(!a||p.type(a)!=="object"||a.nodeType||p.isWindow(a))return!1;try{if(a.constructor&&!n.call(a,"constructor")&&!n.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||n.call(a,d)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},error:function(a){throw new Error(a)},parseHTML:function(a,b,c){var d;return!a||typeof a!="string"?null:(typeof b=="boolean"&&(c=b,b=0),b=b||e,(d=v.exec(a))?[b.createElement(d[1])]:(d=p.buildFragment([a],b,c?null:[]),p.merge([],(d.cacheable?p.clone(d.fragment):d.fragment).childNodes)))},parseJSON:function(b){if(!b||typeof b!="string")return null;b=p.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(w.test(b.replace(y,"@").replace(z,"]").replace(x,"")))return(new Function("return "+b))();p.error("Invalid JSON: "+b)},parseXML:function(c){var d,e;if(!c||typeof c!="string")return null;try{a.DOMParser?(e=new DOMParser,d=e.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(f){d=b}return(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&p.error("Invalid XML: "+c),d},noop:function(){},globalEval:function(b){b&&r.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(A,"ms-").replace(B,C)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,c,d){var e,f=0,g=a.length,h=g===b||p.isFunction(a);if(d){if(h){for(e in a)if(c.apply(a[e],d)===!1)break}else for(;f<g;)if(c.apply(a[f++],d)===!1)break}else if(h){for(e in a)if(c.call(a[e],e,a[e])===!1)break}else for(;f<g;)if(c.call(a[f],f,a[f++])===!1)break;return a},trim:o&&!o.call(" ")?function(a){return a==null?"":o.call(a)}:function(a){return a==null?"":(a+"").replace(t,"")},makeArray:function(a,b){var c,d=b||[];return a!=null&&(c=p.type(a),a.length==null||c==="string"||c==="function"||c==="regexp"||p.isWindow(a)?j.call(d,a):p.merge(d,a)),d},inArray:function(a,b,c){var d;if(b){if(l)return l.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=c.length,e=a.length,f=0;if(typeof d=="number")for(;f<d;f++)a[e++]=c[f];else while(c[f]!==b)a[e++]=c[f++];return a.length=e,a},grep:function(a,b,c){var d,e=[],f=0,g=a.length;c=!!c;for(;f<g;f++)d=!!b(a[f],f),c!==d&&e.push(a[f]);return e},map:function(a,c,d){var e,f,g=[],h=0,i=a.length,j=a instanceof p||i!==b&&typeof i=="number"&&(i>0&&a[0]&&a[i-1]||i===0||p.isArray(a));if(j)for(;h<i;h++)e=c(a[h],h,d),e!=null&&(g[g.length]=e);else for(f in a)e=c(a[f],f,d),e!=null&&(g[g.length]=e);return g.concat.apply([],g)},guid:1,proxy:function(a,c){var d,e,f;return typeof c=="string"&&(d=a[c],c=a,a=d),p.isFunction(a)?(e=k.call(arguments,2),f=function(){return a.apply(c,e.concat(k.call(arguments)))},f.guid=a.guid=a.guid||p.guid++,f):b},access:function(a,c,d,e,f,g,h){var i,j=d==null,k=0,l=a.length;if(d&&typeof d=="object"){for(k in d)p.access(a,c,k,d[k],1,g,e);f=1}else if(e!==b){i=h===b&&p.isFunction(e),j&&(i?(i=c,c=function(a,b,c){return i.call(p(a),c)}):(c.call(a,e),c=null));if(c)for(;k<l;k++)c(a[k],d,i?e.call(a[k],k,c(a[k],d)):e,h);f=1}return f?a:j?c.call(a):l?c(a[0],d):g},now:function(){return(new Date).getTime()}}),p.ready.promise=function(b){if(!d){d=p.Deferred();if(e.readyState==="complete")setTimeout(p.ready,1);else if(e.addEventListener)e.addEventListener("DOMContentLoaded",D,!1),a.addEventListener("load",p.ready,!1);else{e.attachEvent("onreadystatechange",D),a.attachEvent("onload",p.ready);var c=!1;try{c=a.frameElement==null&&e.documentElement}catch(f){}c&&c.doScroll&&function g(){if(!p.isReady){try{c.doScroll("left")}catch(a){return setTimeout(g,50)}p.ready()}}()}}return d.promise(b)},p.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){E["[object "+b+"]"]=b.toLowerCase()}),c=p(e);var F={};p.Callbacks=function(a){a=typeof a=="string"?F[a]||G(a):p.extend({},a);var c,d,e,f,g,h,i=[],j=!a.once&&[],k=function(b){c=a.memory&&b,d=!0,h=f||0,f=0,g=i.length,e=!0;for(;i&&h<g;h++)if(i[h].apply(b[0],b[1])===!1&&a.stopOnFalse){c=!1;break}e=!1,i&&(j?j.length&&k(j.shift()):c?i=[]:l.disable())},l={add:function(){if(i){var b=i.length;(function d(b){p.each(b,function(b,c){var e=p.type(c);e==="function"&&(!a.unique||!l.has(c))?i.push(c):c&&c.length&&e!=="string"&&d(c)})})(arguments),e?g=i.length:c&&(f=b,k(c))}return this},remove:function(){return i&&p.each(arguments,function(a,b){var c;while((c=p.inArray(b,i,c))>-1)i.splice(c,1),e&&(c<=g&&g--,c<=h&&h--)}),this},has:function(a){return p.inArray(a,i)>-1},empty:function(){return i=[],this},disable:function(){return i=j=c=b,this},disabled:function(){return!i},lock:function(){return j=b,c||l.disable(),this},locked:function(){return!j},fireWith:function(a,b){return b=b||[],b=[a,b.slice?b.slice():b],i&&(!d||j)&&(e?j.push(b):k(b)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!d}};return l},p.extend({Deferred:function(a){var b=[["resolve","done",p.Callbacks("once memory"),"resolved"],["reject","fail",p.Callbacks("once memory"),"rejected"],["notify","progress",p.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return p.Deferred(function(c){p.each(b,function(b,d){var f=d[0],g=a[b];e[d[1]](p.isFunction(g)?function(){var a=g.apply(this,arguments);a&&p.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f+"With"](this===e?c:this,[a])}:c[f])}),a=null}).promise()},promise:function(a){return a!=null?p.extend(a,d):d}},e={};return d.pipe=d.then,p.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[a^1][2].disable,b[2][2].lock),e[f[0]]=g.fire,e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=k.call(arguments),d=c.length,e=d!==1||a&&p.isFunction(a.promise)?d:0,f=e===1?a:p.Deferred(),g=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?k.call(arguments):d,c===h?f.notifyWith(b,c):--e||f.resolveWith(b,c)}},h,i,j;if(d>1){h=new Array(d),i=new Array(d),j=new Array(d);for(;b<d;b++)c[b]&&p.isFunction(c[b].promise)?c[b].promise().done(g(b,j,c)).fail(f.reject).progress(g(b,i,h)):--e}return e||f.resolveWith(j,c),f.promise()}}),p.support=function(){var b,c,d,f,g,h,i,j,k,l,m,n=e.createElement("div");n.setAttribute("className","t"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",c=n.getElementsByTagName("*"),d=n.getElementsByTagName("a")[0],d.style.cssText="top:1px;float:left;opacity:.5";if(!c||!c.length)return{};f=e.createElement("select"),g=f.appendChild(e.createElement("option")),h=n.getElementsByTagName("input")[0],b={leadingWhitespace:n.firstChild.nodeType===3,tbody:!n.getElementsByTagName("tbody").length,htmlSerialize:!!n.getElementsByTagName("link").length,style:/top/.test(d.getAttribute("style")),hrefNormalized:d.getAttribute("href")==="/a",opacity:/^0.5/.test(d.style.opacity),cssFloat:!!d.style.cssFloat,checkOn:h.value==="on",optSelected:g.selected,getSetAttribute:n.className!=="t",enctype:!!e.createElement("form").enctype,html5Clone:e.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:e.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},h.checked=!0,b.noCloneChecked=h.cloneNode(!0).checked,f.disabled=!0,b.optDisabled=!g.disabled;try{delete n.test}catch(o){b.deleteExpando=!1}!n.addEventListener&&n.attachEvent&&n.fireEvent&&(n.attachEvent("onclick",m=function(){b.noCloneEvent=!1}),n.cloneNode(!0).fireEvent("onclick"),n.detachEvent("onclick",m)),h=e.createElement("input"),h.value="t",h.setAttribute("type","radio"),b.radioValue=h.value==="t",h.setAttribute("checked","checked"),h.setAttribute("name","t"),n.appendChild(h),i=e.createDocumentFragment(),i.appendChild(n.lastChild),b.checkClone=i.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=h.checked,i.removeChild(h),i.appendChild(n);if(n.attachEvent)for(k in{submit:!0,change:!0,focusin:!0})j="on"+k,l=j in n,l||(n.setAttribute(j,"return;"),l=typeof n[j]=="function"),b[k+"Bubbles"]=l;return p(function(){var c,d,f,g,h="padding:0;margin:0;border:0;display:block;overflow:hidden;",i=e.getElementsByTagName("body")[0];if(!i)return;c=e.createElement("div"),c.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",i.insertBefore(c,i.firstChild),d=e.createElement("div"),c.appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",f=d.getElementsByTagName("td"),f[0].style.cssText="padding:0;margin:0;border:0;display:none",l=f[0].offsetHeight===0,f[0].style.display="",f[1].style.display="none",b.reliableHiddenOffsets=l&&f[0].offsetHeight===0,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",b.boxSizing=d.offsetWidth===4,b.doesNotIncludeMarginInBodyOffset=i.offsetTop!==1,a.getComputedStyle&&(b.pixelPosition=(a.getComputedStyle(d,null)||{}).top!=="1%",b.boxSizingReliable=(a.getComputedStyle(d,null)||{width:"4px"}).width==="4px",g=e.createElement("div"),g.style.cssText=d.style.cssText=h,g.style.marginRight=g.style.width="0",d.style.width="1px",d.appendChild(g),b.reliableMarginRight=!parseFloat((a.getComputedStyle(g,null)||{}).marginRight)),typeof d.style.zoom!="undefined"&&(d.innerHTML="",d.style.cssText=h+"width:1px;padding:1px;display:inline;zoom:1",b.inlineBlockNeedsLayout=d.offsetWidth===3,d.style.display="block",d.style.overflow="visible",d.innerHTML="<div></div>",d.firstChild.style.width="5px",b.shrinkWrapBlocks=d.offsetWidth!==3,c.style.zoom=1),i.removeChild(c),c=d=f=g=null}),i.removeChild(n),c=d=f=g=h=i=n=null,b}();var H=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,I=/([A-Z])/g;p.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(p.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){return a=a.nodeType?p.cache[a[p.expando]]:a[p.expando],!!a&&!K(a)},data:function(a,c,d,e){if(!p.acceptData(a))return;var f,g,h=p.expando,i=typeof c=="string",j=a.nodeType,k=j?p.cache:a,l=j?a[h]:a[h]&&h;if((!l||!k[l]||!e&&!k[l].data)&&i&&d===b)return;l||(j?a[h]=l=p.deletedIds.pop()||p.guid++:l=h),k[l]||(k[l]={},j||(k[l].toJSON=p.noop));if(typeof c=="object"||typeof c=="function")e?k[l]=p.extend(k[l],c):k[l].data=p.extend(k[l].data,c);return f=k[l],e||(f.data||(f.data={}),f=f.data),d!==b&&(f[p.camelCase(c)]=d),i?(g=f[c],g==null&&(g=f[p.camelCase(c)])):g=f,g},removeData:function(a,b,c){if(!p.acceptData(a))return;var d,e,f,g=a.nodeType,h=g?p.cache:a,i=g?a[p.expando]:p.expando;if(!h[i])return;if(b){d=c?h[i]:h[i].data;if(d){p.isArray(b)||(b in d?b=[b]:(b=p.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,f=b.length;e<f;e++)delete d[b[e]];if(!(c?K:p.isEmptyObject)(d))return}}if(!c){delete h[i].data;if(!K(h[i]))return}g?p.cleanData([a],!0):p.support.deleteExpando||h!=h.window?delete h[i]:h[i]=null},_data:function(a,b,c){return p.data(a,b,c,!0)},acceptData:function(a){var b=a.nodeName&&p.noData[a.nodeName.toLowerCase()];return!b||b!==!0&&a.getAttribute("classid")===b}}),p.fn.extend({data:function(a,c){var d,e,f,g,h,i=this[0],j=0,k=null;if(a===b){if(this.length){k=p.data(i);if(i.nodeType===1&&!p._data(i,"parsedAttrs")){f=i.attributes;for(h=f.length;j<h;j++)g=f[j].name,g.indexOf("data-")||(g=p.camelCase(g.substring(5)),J(i,g,k[g]));p._data(i,"parsedAttrs",!0)}}return k}return typeof a=="object"?this.each(function(){p.data(this,a)}):(d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!",p.access(this,function(c){if(c===b)return k=this.triggerHandler("getData"+e,[d[0]]),k===b&&i&&(k=p.data(i,a),k=J(i,a,k)),k===b&&d[1]?this.data(d[0]):k;d[1]=c,this.each(function(){var b=p(this);b.triggerHandler("setData"+e,d),p.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1))},removeData:function(a){return this.each(function(){p.removeData(this,a)})}}),p.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=p._data(a,b),c&&(!d||p.isArray(c)?d=p._data(a,b,p.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=p.queue(a,b),d=c.length,e=c.shift(),f=p._queueHooks(a,b),g=function(){p.dequeue(a,b)};e==="inprogress"&&(e=c.shift(),d--),e&&(b==="fx"&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return p._data(a,c)||p._data(a,c,{empty:p.Callbacks("once memory").add(function(){p.removeData(a,b+"queue",!0),p.removeData(a,c,!0)})})}}),p.fn.extend({queue:function(a,c){var d=2;return typeof a!="string"&&(c=a,a="fx",d--),arguments.length<d?p.queue(this[0],a):c===b?this:this.each(function(){var b=p.queue(this,a,c);p._queueHooks(this,a),a==="fx"&&b[0]!=="inprogress"&&p.dequeue(this,a)})},dequeue:function(a){return this.each(function(){p.dequeue(this,a)})},delay:function(a,b){return a=p.fx?p.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){var d,e=1,f=p.Deferred(),g=this,h=this.length,i=function(){--e||f.resolveWith(g,[g])};typeof a!="string"&&(c=a,a=b),a=a||"fx";while(h--)d=p._data(g[h],a+"queueHooks"),d&&d.empty&&(e++,d.empty.add(i));return i(),f.promise(c)}});var L,M,N,O=/[\t\r\n]/g,P=/\r/g,Q=/^(?:button|input)$/i,R=/^(?:button|input|object|select|textarea)$/i,S=/^a(?:rea|)$/i,T=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,U=p.support.getSetAttribute;p.fn.extend({attr:function(a,b){return p.access(this,p.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){p.removeAttr(this,a)})},prop:function(a,b){return p.access(this,p.prop,a,b,arguments.length>1)},removeProp:function(a){return a=p.propFix[a]||a,this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,f,g,h;if(p.isFunction(a))return this.each(function(b){p(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(s);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{f=" "+e.className+" ";for(g=0,h=b.length;g<h;g++)f.indexOf(" "+b[g]+" ")<0&&(f+=b[g]+" ");e.className=p.trim(f)}}}return this},removeClass:function(a){var c,d,e,f,g,h,i;if(p.isFunction(a))return this.each(function(b){p(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(s);for(h=0,i=this.length;h<i;h++){e=this[h];if(e.nodeType===1&&e.className){d=(" "+e.className+" ").replace(O," ");for(f=0,g=c.length;f<g;f++)while(d.indexOf(" "+c[f]+" ")>=0)d=d.replace(" "+c[f]+" "," ");e.className=a?p.trim(d):""}}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";return p.isFunction(a)?this.each(function(c){p(this).toggleClass(a.call(this,c,this.className,b),b)}):this.each(function(){if(c==="string"){var e,f=0,g=p(this),h=b,i=a.split(s);while(e=i[f++])h=d?h:!g.hasClass(e),g[h?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&p._data(this,"__className__",this.className),this.className=this.className||a===!1?"":p._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(O," ").indexOf(b)>=0)return!0;return!1},val:function(a){var c,d,e,f=this[0];if(!arguments.length){if(f)return c=p.valHooks[f.type]||p.valHooks[f.nodeName.toLowerCase()],c&&"get"in c&&(d=c.get(f,"value"))!==b?d:(d=f.value,typeof d=="string"?d.replace(P,""):d==null?"":d);return}return e=p.isFunction(a),this.each(function(d){var f,g=p(this);if(this.nodeType!==1)return;e?f=a.call(this,d,g.val()):f=a,f==null?f="":typeof f=="number"?f+="":p.isArray(f)&&(f=p.map(f,function(a){return a==null?"":a+""})),c=p.valHooks[this.type]||p.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,f,"value")===b)this.value=f})}}),p.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,f=a.selectedIndex,g=[],h=a.options,i=a.type==="select-one";if(f<0)return null;c=i?f:0,d=i?f+1:h.length;for(;c<d;c++){e=h[c];if(e.selected&&(p.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!p.nodeName(e.parentNode,"optgroup"))){b=p(e).val();if(i)return b;g.push(b)}}return i&&!g.length&&h.length?p(h[f]).val():g},set:function(a,b){var c=p.makeArray(b);return p(a).find("option").each(function(){this.selected=p.inArray(p(this).val(),c)>=0}),c.length||(a.selectedIndex=-1),c}}},attrFn:{},attr:function(a,c,d,e){var f,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return;if(e&&p.isFunction(p.fn[c]))return p(a)[c](d);if(typeof a.getAttribute=="undefined")return p.prop(a,c,d);h=i!==1||!p.isXMLDoc(a),h&&(c=c.toLowerCase(),g=p.attrHooks[c]||(T.test(c)?M:L));if(d!==b){if(d===null){p.removeAttr(a,c);return}return g&&"set"in g&&h&&(f=g.set(a,d,c))!==b?f:(a.setAttribute(c,d+""),d)}return g&&"get"in g&&h&&(f=g.get(a,c))!==null?f:(f=a.getAttribute(c),f===null?b:f)},removeAttr:function(a,b){var c,d,e,f,g=0;if(b&&a.nodeType===1){d=b.split(s);for(;g<d.length;g++)e=d[g],e&&(c=p.propFix[e]||e,f=T.test(e),f||p.attr(a,e,""),a.removeAttribute(U?e:c),f&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(Q.test(a.nodeName)&&a.parentNode)p.error("type property can't be changed");else if(!p.support.radioValue&&b==="radio"&&p.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}},value:{get:function(a,b){return L&&p.nodeName(a,"button")?L.get(a,b):b in a?a.value:null},set:function(a,b,c){if(L&&p.nodeName(a,"button"))return L.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,f,g,h=a.nodeType;if(!a||h===3||h===8||h===2)return;return g=h!==1||!p.isXMLDoc(a),g&&(c=p.propFix[c]||c,f=p.propHooks[c]),d!==b?f&&"set"in f&&(e=f.set(a,d,c))!==b?e:a[c]=d:f&&"get"in f&&(e=f.get(a,c))!==null?e:a[c]},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):R.test(a.nodeName)||S.test(a.nodeName)&&a.href?0:b}}}}),M={get:function(a,c){var d,e=p.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;return b===!1?p.removeAttr(a,c):(d=p.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase())),c}},U||(N={name:!0,id:!0,coords:!0},L=p.valHooks.button={get:function(a,c){var d;return d=a.getAttributeNode(c),d&&(N[c]?d.value!=="":d.specified)?d.value:b},set:function(a,b,c){var d=a.getAttributeNode(c);return d||(d=e.createAttribute(c),a.setAttributeNode(d)),d.value=b+""}},p.each(["width","height"],function(a,b){p.attrHooks[b]=p.extend(p.attrHooks[b],{set:function(a,c){if(c==="")return a.setAttribute(b,"auto"),c}})}),p.attrHooks.contenteditable={get:L.get,set:function(a,b,c){b===""&&(b="false"),L.set(a,b,c)}}),p.support.hrefNormalized||p.each(["href","src","width","height"],function(a,c){p.attrHooks[c]=p.extend(p.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),p.support.style||(p.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=b+""}}),p.support.optSelected||(p.propHooks.selected=p.extend(p.propHooks.selected,{get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}})),p.support.enctype||(p.propFix.enctype="encoding"),p.support.checkOn||p.each(["radio","checkbox"],function(){p.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),p.each(["radio","checkbox"],function(){p.valHooks[this]=p.extend(p.valHooks[this],{set:function(a,b){if(p.isArray(b))return a.checked=p.inArray(p(a).val(),b)>=0}})});var V=/^(?:textarea|input|select)$/i,W=/^([^\.]*|)(?:\.(.+)|)$/,X=/(?:^|\s)hover(\.\S+|)\b/,Y=/^key/,Z=/^(?:mouse|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=function(a){return p.event.special.hover?a:a.replace(X,"mouseenter$1 mouseleave$1")};p.event={add:function(a,c,d,e,f){var g,h,i,j,k,l,m,n,o,q,r;if(a.nodeType===3||a.nodeType===8||!c||!d||!(g=p._data(a)))return;d.handler&&(o=d,d=o.handler,f=o.selector),d.guid||(d.guid=p.guid++),i=g.events,i||(g.events=i={}),h=g.handle,h||(g.handle=h=function(a){return typeof p!="undefined"&&(!a||p.event.triggered!==a.type)?p.event.dispatch.apply(h.elem,arguments):b},h.elem=a),c=p.trim(_(c)).split(" ");for(j=0;j<c.length;j++){k=W.exec(c[j])||[],l=k[1],m=(k[2]||"").split(".").sort(),r=p.event.special[l]||{},l=(f?r.delegateType:r.bindType)||l,r=p.event.special[l]||{},n=p.extend({type:l,origType:k[1],data:e,handler:d,guid:d.guid,selector:f,needsContext:f&&p.expr.match.needsContext.test(f),namespace:m.join(".")},o),q=i[l];if(!q){q=i[l]=[],q.delegateCount=0;if(!r.setup||r.setup.call(a,e,m,h)===!1)a.addEventListener?a.addEventListener(l,h,!1):a.attachEvent&&a.attachEvent("on"+l,h)}r.add&&(r.add.call(a,n),n.handler.guid||(n.handler.guid=d.guid)),f?q.splice(q.delegateCount++,0,n):q.push(n),p.event.global[l]=!0}a=null},global:{},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,q,r=p.hasData(a)&&p._data(a);if(!r||!(m=r.events))return;b=p.trim(_(b||"")).split(" ");for(f=0;f<b.length;f++){g=W.exec(b[f])||[],h=i=g[1],j=g[2];if(!h){for(h in m)p.event.remove(a,h+b[f],c,d,!0);continue}n=p.event.special[h]||{},h=(d?n.delegateType:n.bindType)||h,o=m[h]||[],k=o.length,j=j?new RegExp("(^|\\.)"+j.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(l=0;l<o.length;l++)q=o[l],(e||i===q.origType)&&(!c||c.guid===q.guid)&&(!j||j.test(q.namespace))&&(!d||d===q.selector||d==="**"&&q.selector)&&(o.splice(l--,1),q.selector&&o.delegateCount--,n.remove&&n.remove.call(a,q));o.length===0&&k!==o.length&&((!n.teardown||n.teardown.call(a,j,r.handle)===!1)&&p.removeEvent(a,h,r.handle),delete m[h])}p.isEmptyObject(m)&&(delete r.handle,p.removeData(a,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,f,g){if(!f||f.nodeType!==3&&f.nodeType!==8){var h,i,j,k,l,m,n,o,q,r,s=c.type||c,t=[];if($.test(s+p.event.triggered))return;s.indexOf("!")>=0&&(s=s.slice(0,-1),i=!0),s.indexOf(".")>=0&&(t=s.split("."),s=t.shift(),t.sort());if((!f||p.event.customEvent[s])&&!p.event.global[s])return;c=typeof c=="object"?c[p.expando]?c:new p.Event(s,c):new p.Event(s),c.type=s,c.isTrigger=!0,c.exclusive=i,c.namespace=t.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+t.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,m=s.indexOf(":")<0?"on"+s:"";if(!f){h=p.cache;for(j in h)h[j].events&&h[j].events[s]&&p.event.trigger(c,d,h[j].handle.elem,!0);return}c.result=b,c.target||(c.target=f),d=d!=null?p.makeArray(d):[],d.unshift(c),n=p.event.special[s]||{};if(n.trigger&&n.trigger.apply(f,d)===!1)return;q=[[f,n.bindType||s]];if(!g&&!n.noBubble&&!p.isWindow(f)){r=n.delegateType||s,k=$.test(r+s)?f:f.parentNode;for(l=f;k;k=k.parentNode)q.push([k,r]),l=k;l===(f.ownerDocument||e)&&q.push([l.defaultView||l.parentWindow||a,r])}for(j=0;j<q.length&&!c.isPropagationStopped();j++)k=q[j][0],c.type=q[j][1],o=(p._data(k,"events")||{})[c.type]&&p._data(k,"handle"),o&&o.apply(k,d),o=m&&k[m],o&&p.acceptData(k)&&o.apply&&o.apply(k,d)===!1&&c.preventDefault();return c.type=s,!g&&!c.isDefaultPrevented()&&(!n._default||n._default.apply(f.ownerDocument,d)===!1)&&(s!=="click"||!p.nodeName(f,"a"))&&p.acceptData(f)&&m&&f[s]&&(s!=="focus"&&s!=="blur"||c.target.offsetWidth!==0)&&!p.isWindow(f)&&(l=f[m],l&&(f[m]=null),p.event.triggered=s,f[s](),p.event.triggered=b,l&&(f[m]=l)),c.result}return},dispatch:function(c){c=p.event.fix(c||a.event);var d,e,f,g,h,i,j,l,m,n,o=(p._data(this,"events")||{})[c.type]||[],q=o.delegateCount,r=k.call(arguments),s=!c.exclusive&&!c.namespace,t=p.event.special[c.type]||{},u=[];r[0]=c,c.delegateTarget=this;if(t.preDispatch&&t.preDispatch.call(this,c)===!1)return;if(q&&(!c.button||c.type!=="click"))for(f=c.target;f!=this;f=f.parentNode||this)if(f.disabled!==!0||c.type!=="click"){h={},j=[];for(d=0;d<q;d++)l=o[d],m=l.selector,h[m]===b&&(h[m]=l.needsContext?p(m,this).index(f)>=0:p.find(m,this,null,[f]).length),h[m]&&j.push(l);j.length&&u.push({elem:f,matches:j})}o.length>q&&u.push({elem:this,matches:o.slice(q)});for(d=0;d<u.length&&!c.isPropagationStopped();d++){i=u[d],c.currentTarget=i.elem;for(e=0;e<i.matches.length&&!c.isImmediatePropagationStopped();e++){l=i.matches[e];if(s||!c.namespace&&!l.namespace||c.namespace_re&&c.namespace_re.test(l.namespace))c.data=l.data,c.handleObj=l,g=((p.event.special[l.origType]||{}).handle||l.handler).apply(i.elem,r),g!==b&&(c.result=g,g===!1&&(c.preventDefault(),c.stopPropagation()))}}return t.postDispatch&&t.postDispatch.call(this,c),c.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,c){var d,f,g,h=c.button,i=c.fromElement;return a.pageX==null&&c.clientX!=null&&(d=a.target.ownerDocument||e,f=d.documentElement,g=d.body,a.pageX=c.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=c.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?c.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0),a}},fix:function(a){if(a[p.expando])return a;var b,c,d=a,f=p.event.fixHooks[a.type]||{},g=f.props?this.props.concat(f.props):this.props;a=p.Event(d);for(b=g.length;b;)c=g[--b],a[c]=d[c];return a.target||(a.target=d.srcElement||e),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,f.filter?f.filter(a,d):a},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){p.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=p.extend(new p.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?p.event.trigger(e,null,b):p.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},p.event.handle=p.event.dispatch,p.removeEvent=e.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]=="undefined"&&(a[d]=null),a.detachEvent(d,c))},p.Event=function(a,b){if(this instanceof p.Event)a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?bb:ba):this.type=a,b&&p.extend(this,b),this.timeStamp=a&&a.timeStamp||p.now(),this[p.expando]=!0;else return new p.Event(a,b)},p.Event.prototype={preventDefault:function(){this.isDefaultPrevented=bb;var a=this.originalEvent;if(!a)return;a.preventDefault?a.preventDefault():a.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=bb;var a=this.originalEvent;if(!a)return;a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()},isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba},p.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){p.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj,g=f.selector;if(!e||e!==d&&!p.contains(d,e))a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b;return c}}}),p.support.submitBubbles||(p.event.special.submit={setup:function(){if(p.nodeName(this,"form"))return!1;p.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=p.nodeName(c,"input")||p.nodeName(c,"button")?c.form:b;d&&!p._data(d,"_submit_attached")&&(p.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),p._data(d,"_submit_attached",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&p.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(p.nodeName(this,"form"))return!1;p.event.remove(this,"._submit")}}),p.support.changeBubbles||(p.event.special.change={setup:function(){if(V.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")p.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),p.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),p.event.simulate("change",this,a,!0)});return!1}p.event.add(this,"beforeactivate._change",function(a){var b=a.target;V.test(b.nodeName)&&!p._data(b,"_change_attached")&&(p.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&p.event.simulate("change",this.parentNode,a,!0)}),p._data(b,"_change_attached",!0))})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){return p.event.remove(this,"._change"),!V.test(this.nodeName)}}),p.support.focusinBubbles||p.each({focus:"focusin",blur:"focusout"},function(a,b){var c=0,d=function(a){p.event.simulate(b,a.target,p.event.fix(a),!0)};p.event.special[b]={setup:function(){c++===0&&e.addEventListener(a,d,!0)},teardown:function(){--c===0&&e.removeEventListener(a,d,!0)}}}),p.fn.extend({on:function(a,c,d,e,f){var g,h;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(h in a)this.on(h,c,d,a[h],f);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=ba;else if(!e)return this;return f===1&&(g=e,e=function(a){return p().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=p.guid++)),this.each(function(){p.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){var e,f;if(a&&a.preventDefault&&a.handleObj)return e=a.handleObj,p(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler),this;if(typeof a=="object"){for(f in a)this.off(f,c,a[f]);return this}if(c===!1||typeof c=="function")d=c,c=b;return d===!1&&(d=ba),this.each(function(){p.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){return p(this.context).on(a,this.selector,b,c),this},die:function(a,b){return p(this.context).off(a,this.selector||"**",b),this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length===1?this.off(a,"**"):this.off(b,a||"**",c)},trigger:function(a,b){return this.each(function(){p.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return p.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||p.guid++,d=0,e=function(c){var e=(p._data(this,"lastToggle"+a.guid)||0)%d;return p._data(this,"lastToggle"+a.guid,e+1),c.preventDefault(),b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),p.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){p.fn[b]=function(a,c){return c==null&&(c=a,a=null),arguments.length>0?this.on(b,null,a,c):this.trigger(b)},Y.test(b)&&(p.event.fixHooks[b]=p.event.keyHooks),Z.test(b)&&(p.event.fixHooks[b]=p.event.mouseHooks)}),function(a,b){function bc(a,b,c,d){c=c||[],b=b||r;var e,f,i,j,k=b.nodeType;if(!a||typeof a!="string")return c;if(k!==1&&k!==9)return[];i=g(b);if(!i&&!d)if(e=P.exec(a))if(j=e[1]){if(k===9){f=b.getElementById(j);if(!f||!f.parentNode)return c;if(f.id===j)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(j))&&h(b,f)&&f.id===j)return c.push(f),c}else{if(e[2])return w.apply(c,x.call(b.getElementsByTagName(a),0)),c;if((j=e[3])&&_&&b.getElementsByClassName)return w.apply(c,x.call(b.getElementsByClassName(j),0)),c}return bp(a.replace(L,"$1"),b,c,d,i)}function bd(a){return function(b){var c=b.nodeName.toLowerCase();return c==="input"&&b.type===a}}function be(a){return function(b){var c=b.nodeName.toLowerCase();return(c==="input"||c==="button")&&b.type===a}}function bf(a){return z(function(b){return b=+b,z(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function bg(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}function bh(a,b){var c,d,f,g,h,i,j,k=C[o][a];if(k)return b?0:k.slice(0);h=a,i=[],j=e.preFilter;while(h){if(!c||(d=M.exec(h)))d&&(h=h.slice(d[0].length)),i.push(f=[]);c=!1;if(d=N.exec(h))f.push(c=new q(d.shift())),h=h.slice(c.length),c.type=d[0].replace(L," ");for(g in e.filter)(d=W[g].exec(h))&&(!j[g]||(d=j[g](d,r,!0)))&&(f.push(c=new q(d.shift())),h=h.slice(c.length),c.type=g,c.matches=d);if(!c)break}return b?h.length:h?bc.error(a):C(a,i).slice(0)}function bi(a,b,d){var e=b.dir,f=d&&b.dir==="parentNode",g=u++;return b.first?function(b,c,d){while(b=b[e])if(f||b.nodeType===1)return a(b,c,d)}:function(b,d,h){if(!h){var i,j=t+" "+g+" ",k=j+c;while(b=b[e])if(f||b.nodeType===1){if((i=b[o])===k)return b.sizset;if(typeof i=="string"&&i.indexOf(j)===0){if(b.sizset)return b}else{b[o]=k;if(a(b,d,h))return b.sizset=!0,b;b.sizset=!1}}}else while(b=b[e])if(f||b.nodeType===1)if(a(b,d,h))return b}}function bj(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function bk(a,b,c,d,e){var f,g=[],h=0,i=a.length,j=b!=null;for(;h<i;h++)if(f=a[h])if(!c||c(f,d,e))g.push(f),j&&b.push(h);return g}function bl(a,b,c,d,e,f){return d&&!d[o]&&(d=bl(d)),e&&!e[o]&&(e=bl(e,f)),z(function(f,g,h,i){if(f&&e)return;var j,k,l,m=[],n=[],o=g.length,p=f||bo(b||"*",h.nodeType?[h]:h,[],f),q=a&&(f||!b)?bk(p,m,a,h,i):p,r=c?e||(f?a:o||d)?[]:g:q;c&&c(q,r,h,i);if(d){l=bk(r,n),d(l,[],h,i),j=l.length;while(j--)if(k=l[j])r[n[j]]=!(q[n[j]]=k)}if(f){j=a&&r.length;while(j--)if(k=r[j])f[m[j]]=!(g[m[j]]=k)}else r=bk(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):w.apply(g,r)})}function bm(a){var b,c,d,f=a.length,g=e.relative[a[0].type],h=g||e.relative[" "],i=g?1:0,j=bi(function(a){return a===b},h,!0),k=bi(function(a){return y.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==l)||((b=c).nodeType?j(a,c,d):k(a,c,d))}];for(;i<f;i++)if(c=e.relative[a[i].type])m=[bi(bj(m),c)];else{c=e.filter[a[i].type].apply(null,a[i].matches);if(c[o]){d=++i;for(;d<f;d++)if(e.relative[a[d].type])break;return bl(i>1&&bj(m),i>1&&a.slice(0,i-1).join("").replace(L,"$1"),c,i<d&&bm(a.slice(i,d)),d<f&&bm(a=a.slice(d)),d<f&&a.join(""))}m.push(c)}return bj(m)}function bn(a,b){var d=b.length>0,f=a.length>0,g=function(h,i,j,k,m){var n,o,p,q=[],s=0,u="0",x=h&&[],y=m!=null,z=l,A=h||f&&e.find.TAG("*",m&&i.parentNode||i),B=t+=z==null?1:Math.E;y&&(l=i!==r&&i,c=g.el);for(;(n=A[u])!=null;u++){if(f&&n){for(o=0;p=a[o];o++)if(p(n,i,j)){k.push(n);break}y&&(t=B,c=++g.el)}d&&((n=!p&&n)&&s--,h&&x.push(n))}s+=u;if(d&&u!==s){for(o=0;p=b[o];o++)p(x,q,i,j);if(h){if(s>0)while(u--)!x[u]&&!q[u]&&(q[u]=v.call(k));q=bk(q)}w.apply(k,q),y&&!h&&q.length>0&&s+b.length>1&&bc.uniqueSort(k)}return y&&(t=B,l=z),x};return g.el=0,d?z(g):g}function bo(a,b,c,d){var e=0,f=b.length;for(;e<f;e++)bc(a,b[e],c,d);return c}function bp(a,b,c,d,f){var g,h,j,k,l,m=bh(a),n=m.length;if(!d&&m.length===1){h=m[0]=m[0].slice(0);if(h.length>2&&(j=h[0]).type==="ID"&&b.nodeType===9&&!f&&e.relative[h[1].type]){b=e.find.ID(j.matches[0].replace(V,""),b,f)[0];if(!b)return c;a=a.slice(h.shift().length)}for(g=W.POS.test(a)?-1:h.length-1;g>=0;g--){j=h[g];if(e.relative[k=j.type])break;if(l=e.find[k])if(d=l(j.matches[0].replace(V,""),R.test(h[0].type)&&b.parentNode||b,f)){h.splice(g,1),a=d.length&&h.join("");if(!a)return w.apply(c,x.call(d,0)),c;break}}}return i(a,m)(d,b,f,c,R.test(a)),c}function bq(){}var c,d,e,f,g,h,i,j,k,l,m=!0,n="undefined",o=("sizcache"+Math.random()).replace(".",""),q=String,r=a.document,s=r.documentElement,t=0,u=0,v=[].pop,w=[].push,x=[].slice,y=[].indexOf||function(a){var b=0,c=this.length;for(;b<c;b++)if(this[b]===a)return b;return-1},z=function(a,b){return a[o]=b==null||b,a},A=function(){var a={},b=[];return z(function(c,d){return b.push(c)>e.cacheLength&&delete a[b.shift()],a[c]=d},a)},B=A(),C=A(),D=A(),E="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",G=F.replace("w","w#"),H="([*^$|!~]?=)",I="\\["+E+"*("+F+")"+E+"*(?:"+H+E+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+G+")|)|)"+E+"*\\]",J=":("+F+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+I+")|[^:]|\\\\.)*|.*))\\)|)",K=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+E+"*((?:-\\d)?\\d*)"+E+"*\\)|)(?=[^-]|$)",L=new RegExp("^"+E+"+|((?:^|[^\\\\])(?:\\\\.)*)"+E+"+$","g"),M=new RegExp("^"+E+"*,"+E+"*"),N=new RegExp("^"+E+"*([\\x20\\t\\r\\n\\f>+~])"+E+"*"),O=new RegExp(J),P=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,Q=/^:not/,R=/[\x20\t\r\n\f]*[+~]/,S=/:not\($/,T=/h\d/i,U=/input|select|textarea|button/i,V=/\\(?!\\)/g,W={ID:new RegExp("^#("+F+")"),CLASS:new RegExp("^\\.("+F+")"),NAME:new RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:new RegExp("^("+F.replace("w","w*")+")"),ATTR:new RegExp("^"+I),PSEUDO:new RegExp("^"+J),POS:new RegExp(K,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+E+"*(even|odd|(([+-]|)(\\d*)n|)"+E+"*(?:([+-]|)"+E+"*(\\d+)|))"+E+"*\\)|)","i"),needsContext:new RegExp("^"+E+"*[>+~]|"+K,"i")},X=function(a){var b=r.createElement("div");try{return a(b)}catch(c){return!1}finally{b=null}},Y=X(function(a){return a.appendChild(r.createComment("")),!a.getElementsByTagName("*").length}),Z=X(function(a){return a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!==n&&a.firstChild.getAttribute("href")==="#"}),$=X(function(a){a.innerHTML="<select></select>";var b=typeof a.lastChild.getAttribute("multiple");return b!=="boolean"&&b!=="string"}),_=X(function(a){return a.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!a.getElementsByClassName||!a.getElementsByClassName("e").length?!1:(a.lastChild.className="e",a.getElementsByClassName("e").length===2)}),ba=X(function(a){a.id=o+0,a.innerHTML="<a name='"+o+"'></a><div name='"+o+"'></div>",s.insertBefore(a,s.firstChild);var b=r.getElementsByName&&r.getElementsByName(o).length===2+r.getElementsByName(o+0).length;return d=!r.getElementById(o),s.removeChild(a),b});try{x.call(s.childNodes,0)[0].nodeType}catch(bb){x=function(a){var b,c=[];for(;b=this[a];a++)c.push(b);return c}}bc.matches=function(a,b){return bc(a,null,null,b)},bc.matchesSelector=function(a,b){return bc(b,null,null,[a]).length>0},f=bc.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(e===1||e===9||e===11){if(typeof a.textContent=="string")return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=f(a)}else if(e===3||e===4)return a.nodeValue}else for(;b=a[d];d++)c+=f(b);return c},g=bc.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?b.nodeName!=="HTML":!1},h=bc.contains=s.contains?function(a,b){var c=a.nodeType===9?a.documentElement:a,d=b&&b.parentNode;return a===d||!!(d&&d.nodeType===1&&c.contains&&c.contains(d))}:s.compareDocumentPosition?function(a,b){return b&&!!(a.compareDocumentPosition(b)&16)}:function(a,b){while(b=b.parentNode)if(b===a)return!0;return!1},bc.attr=function(a,b){var c,d=g(a);return d||(b=b.toLowerCase()),(c=e.attrHandle[b])?c(a):d||$?a.getAttribute(b):(c=a.getAttributeNode(b),c?typeof a[b]=="boolean"?a[b]?b:null:c.specified?c.value:null:null)},e=bc.selectors={cacheLength:50,createPseudo:z,match:W,attrHandle:Z?{}:{href:function(a){return a.getAttribute("href",2)},type:function(a){return a.getAttribute("type")}},find:{ID:d?function(a,b,c){if(typeof b.getElementById!==n&&!c){var d=b.getElementById(a);return d&&d.parentNode?[d]:[]}}:function(a,c,d){if(typeof c.getElementById!==n&&!d){var e=c.getElementById(a);return e?e.id===a||typeof e.getAttributeNode!==n&&e.getAttributeNode("id").value===a?[e]:b:[]}},TAG:Y?function(a,b){if(typeof b.getElementsByTagName!==n)return b.getElementsByTagName(a)}:function(a,b){var c=b.getElementsByTagName(a);if(a==="*"){var d,e=[],f=0;for(;d=c[f];f++)d.nodeType===1&&e.push(d);return e}return c},NAME:ba&&function(a,b){if(typeof b.getElementsByName!==n)return b.getElementsByName(name)},CLASS:_&&function(a,b,c){if(typeof b.getElementsByClassName!==n&&!c)return b.getElementsByClassName(a)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(V,""),a[3]=(a[4]||a[5]||"").replace(V,""),a[2]==="~="&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),a[1]==="nth"?(a[2]||bc.error(a[0]),a[3]=+(a[3]?a[4]+(a[5]||1):2*(a[2]==="even"||a[2]==="odd")),a[4]=+(a[6]+a[7]||a[2]==="odd")):a[2]&&bc.error(a[0]),a},PSEUDO:function(a){var b,c;if(W.CHILD.test(a[0]))return null;if(a[3])a[2]=a[3];else if(b=a[4])O.test(b)&&(c=bh(b,!0))&&(c=b.indexOf(")",b.length-c)-b.length)&&(b=b.slice(0,c),a[0]=a[0].slice(0,c)),a[2]=b;return a.slice(0,3)}},filter:{ID:d?function(a){return a=a.replace(V,""),function(b){return b.getAttribute("id")===a}}:function(a){return a=a.replace(V,""),function(b){var c=typeof b.getAttributeNode!==n&&b.getAttributeNode("id");return c&&c.value===a}},TAG:function(a){return a==="*"?function(){return!0}:(a=a.replace(V,"").toLowerCase(),function(b){return b.nodeName&&b.nodeName.toLowerCase()===a})},CLASS:function(a){var b=B[o][a];return b||(b=B(a,new RegExp("(^|"+E+")"+a+"("+E+"|$)"))),function(a){return b.test(a.className||typeof a.getAttribute!==n&&a.getAttribute("class")||"")}},ATTR:function(a,b,c){return function(d,e){var f=bc.attr(d,a);return f==null?b==="!=":b?(f+="",b==="="?f===c:b==="!="?f!==c:b==="^="?c&&f.indexOf(c)===0:b==="*="?c&&f.indexOf(c)>-1:b==="$="?c&&f.substr(f.length-c.length)===c:b==="~="?(" "+f+" ").indexOf(c)>-1:b==="|="?f===c||f.substr(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d){return a==="nth"?function(a){var b,e,f=a.parentNode;if(c===1&&d===0)return!0;if(f){e=0;for(b=f.firstChild;b;b=b.nextSibling)if(b.nodeType===1){e++;if(a===b)break}}return e-=d,e===c||e%c===0&&e/c>=0}:function(b){var c=b;switch(a){case"only":case"first":while(c=c.previousSibling)if(c.nodeType===1)return!1;if(a==="first")return!0;c=b;case"last":while(c=c.nextSibling)if(c.nodeType===1)return!1;return!0}}},PSEUDO:function(a,b){var c,d=e.pseudos[a]||e.setFilters[a.toLowerCase()]||bc.error("unsupported pseudo: "+a);return d[o]?d(b):d.length>1?(c=[a,a,"",b],e.setFilters.hasOwnProperty(a.toLowerCase())?z(function(a,c){var e,f=d(a,b),g=f.length;while(g--)e=y.call(a,f[g]),a[e]=!(c[e]=f[g])}):function(a){return d(a,0,c)}):d}},pseudos:{not:z(function(a){var b=[],c=[],d=i(a.replace(L,"$1"));return d[o]?z(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)if(f=g[h])a[h]=!(b[h]=f)}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:z(function(a){return function(b){return bc(a,b).length>0}}),contains:z(function(a){return function(b){return(b.textContent||b.innerText||f(b)).indexOf(a)>-1}}),enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&!!a.checked||b==="option"&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},parent:function(a){return!e.pseudos.empty(a)},empty:function(a){var b;a=a.firstChild;while(a){if(a.nodeName>"@"||(b=a.nodeType)===3||b===4)return!1;a=a.nextSibling}return!0},header:function(a){return T.test(a.nodeName)},text:function(a){var b,c;return a.nodeName.toLowerCase()==="input"&&(b=a.type)==="text"&&((c=a.getAttribute("type"))==null||c.toLowerCase()===b)},radio:bd("radio"),checkbox:bd("checkbox"),file:bd("file"),password:bd("password"),image:bd("image"),submit:be("submit"),reset:be("reset"),button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&a.type==="button"||b==="button"},input:function(a){return U.test(a.nodeName)},focus:function(a){var b=a.ownerDocument;return a===b.activeElement&&(!b.hasFocus||b.hasFocus())&&(!!a.type||!!a.href)},active:function(a){return a===a.ownerDocument.activeElement},first:bf(function(a,b,c){return[0]}),last:bf(function(a,b,c){return[b-1]}),eq:bf(function(a,b,c){return[c<0?c+b:c]}),even:bf(function(a,b,c){for(var d=0;d<b;d+=2)a.push(d);return a}),odd:bf(function(a,b,c){for(var d=1;d<b;d+=2)a.push(d);return a}),lt:bf(function(a,b,c){for(var d=c<0?c+b:c;--d>=0;)a.push(d);return a}),gt:bf(function(a,b,c){for(var d=c<0?c+b:c;++d<b;)a.push(d);return a})}},j=s.compareDocumentPosition?function(a,b){return a===b?(k=!0,0):(!a.compareDocumentPosition||!b.compareDocumentPosition?a.compareDocumentPosition:a.compareDocumentPosition(b)&4)?-1:1}:function(a,b){if(a===b)return k=!0,0;if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,h=b.parentNode,i=g;if(g===h)return bg(a,b);if(!g)return-1;if(!h)return 1;while(i)e.unshift(i),i=i.parentNode;i=h;while(i)f.unshift(i),i=i.parentNode;c=e.length,d=f.length;for(var j=0;j<c&&j<d;j++)if(e[j]!==f[j])return bg(e[j],f[j]);return j===c?bg(a,f[j],-1):bg(e[j],b,1)},[0,0].sort(j),m=!k,bc.uniqueSort=function(a){var b,c=1;k=m,a.sort(j);if(k)for(;b=a[c];c++)b===a[c-1]&&a.splice(c--,1);return a},bc.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},i=bc.compile=function(a,b){var c,d=[],e=[],f=D[o][a];if(!f){b||(b=bh(a)),c=b.length;while(c--)f=bm(b[c]),f[o]?d.push(f):e.push(f);f=D(a,bn(e,d))}return f},r.querySelectorAll&&function(){var a,b=bp,c=/'|\\/g,d=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,e=[":focus"],f=[":active",":focus"],h=s.matchesSelector||s.mozMatchesSelector||s.webkitMatchesSelector||s.oMatchesSelector||s.msMatchesSelector;X(function(a){a.innerHTML="<select><option selected=''></option></select>",a.querySelectorAll("[selected]").length||e.push("\\["+E+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),a.querySelectorAll(":checked").length||e.push(":checked")}),X(function(a){a.innerHTML="<p test=''></p>",a.querySelectorAll("[test^='']").length&&e.push("[*^$]="+E+"*(?:\"\"|'')"),a.innerHTML="<input type='hidden'/>",a.querySelectorAll(":enabled").length||e.push(":enabled",":disabled")}),e=new RegExp(e.join("|")),bp=function(a,d,f,g,h){if(!g&&!h&&(!e||!e.test(a))){var i,j,k=!0,l=o,m=d,n=d.nodeType===9&&a;if(d.nodeType===1&&d.nodeName.toLowerCase()!=="object"){i=bh(a),(k=d.getAttribute("id"))?l=k.replace(c,"\\$&"):d.setAttribute("id",l),l="[id='"+l+"'] ",j=i.length;while(j--)i[j]=l+i[j].join("");m=R.test(a)&&d.parentNode||d,n=i.join(",")}if(n)try{return w.apply(f,x.call(m.querySelectorAll(n),0)),f}catch(p){}finally{k||d.removeAttribute("id")}}return b(a,d,f,g,h)},h&&(X(function(b){a=h.call(b,"div");try{h.call(b,"[test!='']:sizzle"),f.push("!=",J)}catch(c){}}),f=new RegExp(f.join("|")),bc.matchesSelector=function(b,c){c=c.replace(d,"='$1']");if(!g(b)&&!f.test(c)&&(!e||!e.test(c)))try{var i=h.call(b,c);if(i||a||b.document&&b.document.nodeType!==11)return i}catch(j){}return bc(c,null,null,[b]).length>0})}(),e.pseudos.nth=e.pseudos.eq,e.filters=bq.prototype=e.pseudos,e.setFilters=new bq,bc.attr=p.attr,p.find=bc,p.expr=bc.selectors,p.expr[":"]=p.expr.pseudos,p.unique=bc.uniqueSort,p.text=bc.getText,p.isXMLDoc=bc.isXML,p.contains=bc.contains}(a);var bc=/Until$/,bd=/^(?:parents|prev(?:Until|All))/,be=/^.[^:#\[\.,]*$/,bf=p.expr.match.needsContext,bg={children:!0,contents:!0,next:!0,prev:!0};p.fn.extend({find:function(a){var b,c,d,e,f,g,h=this;if(typeof a!="string")return p(a).filter(function(){for(b=0,c=h.length;b<c;b++)if(p.contains(h[b],this))return!0});g=this.pushStack("","find",a);for(b=0,c=this.length;b<c;b++){d=g.length,p.find(a,this[b],g);if(b>0)for(e=d;e<g.length;e++)for(f=0;f<d;f++)if(g[f]===g[e]){g.splice(e--,1);break}}return g},has:function(a){var b,c=p(a,this),d=c.length;return this.filter(function(){for(b=0;b<d;b++)if(p.contains(this,c[b]))return!0})},not:function(a){return this.pushStack(bj(this,a,!1),"not",a)},filter:function(a){return this.pushStack(bj(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?bf.test(a)?p(a,this.context).index(this[0])>=0:p.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c,d=0,e=this.length,f=[],g=bf.test(a)||typeof a!="string"?p(a,b||this.context):0;for(;d<e;d++){c=this[d];while(c&&c.ownerDocument&&c!==b&&c.nodeType!==11){if(g?g.index(c)>-1:p.find.matchesSelector(c,a)){f.push(c);break}c=c.parentNode}}return f=f.length>1?p.unique(f):f,this.pushStack(f,"closest",a)},index:function(a){return a?typeof a=="string"?p.inArray(this[0],p(a)):p.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(a,b){var c=typeof a=="string"?p(a,b):p.makeArray(a&&a.nodeType?[a]:a),d=p.merge(this.get(),c);return this.pushStack(bh(c[0])||bh(d[0])?d:p.unique(d))},addBack:function(a){return this.add(a==null?this.prevObject:this.prevObject.filter(a))}}),p.fn.andSelf=p.fn.addBack,p.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return p.dir(a,"parentNode")},parentsUntil:function(a,b,c){return p.dir(a,"parentNode",c)},next:function(a){return bi(a,"nextSibling")},prev:function(a){return bi(a,"previousSibling")},nextAll:function(a){return p.dir(a,"nextSibling")},prevAll:function(a){return p.dir(a,"previousSibling")},nextUntil:function(a,b,c){return p.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return p.dir(a,"previousSibling",c)},siblings:function(a){return p.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return p.sibling(a.firstChild)},contents:function(a){return p.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:p.merge([],a.childNodes)}},function(a,b){p.fn[a]=function(c,d){var e=p.map(this,b,c);return bc.test(a)||(d=c),d&&typeof d=="string"&&(e=p.filter(d,e)),e=this.length>1&&!bg[a]?p.unique(e):e,this.length>1&&bd.test(a)&&(e=e.reverse()),this.pushStack(e,a,k.call(arguments).join(","))}}),p.extend({filter:function(a,b,c){return c&&(a=":not("+a+")"),b.length===1?p.find.matchesSelector(b[0],a)?[b[0]]:[]:p.find.matches(a,b)},dir:function(a,c,d){var e=[],f=a[c];while(f&&f.nodeType!==9&&(d===b||f.nodeType!==1||!p(f).is(d)))f.nodeType===1&&e.push(f),f=f[c];return e},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var bl="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",bm=/ jQuery\d+="(?:null|\d+)"/g,bn=/^\s+/,bo=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bp=/<([\w:]+)/,bq=/<tbody/i,br=/<|&#?\w+;/,bs=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,bu=new RegExp("<(?:"+bl+")[\\s/>]","i"),bv=/^(?:checkbox|radio)$/,bw=/checked\s*(?:[^=]|=\s*.checked.)/i,bx=/\/(java|ecma)script/i,by=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,bz={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bA=bk(e),bB=bA.appendChild(e.createElement("div"));bz.optgroup=bz.option,bz.tbody=bz.tfoot=bz.colgroup=bz.caption=bz.thead,bz.th=bz.td,p.support.htmlSerialize||(bz._default=[1,"X<div>","</div>"]),p.fn.extend({text:function(a){return p.access(this,function(a){return a===b?p.text(this):this.empty().append((this[0]&&this[0].ownerDocument||e).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(p.isFunction(a))return this.each(function(b){p(this).wrapAll(a.call(this,b))});if(this[0]){var b=p(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return p.isFunction(a)?this.each(function(b){p(this).wrapInner(a.call(this,b))}):this.each(function(){var b=p(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=p.isFunction(a);return this.each(function(c){p(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){p.nodeName(this,"body")||p(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(a,this.firstChild)})},before:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(a,this),"before",this.selector)}},after:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(this,a),"after",this.selector)}},remove:function(a,b){var c,d=0;for(;(c=this[d])!=null;d++)if(!a||p.filter(a,[c]).length)!b&&c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),p.cleanData([c])),c.parentNode&&c.parentNode.removeChild(c);return this},empty:function(){var a,b=0;for(;(a=this[b])!=null;b++){a.nodeType===1&&p.cleanData(a.getElementsByTagName("*"));while(a.firstChild)a.removeChild(a.firstChild)}return this},clone:function(a,b){return a=a==null?!1:a,b=b==null?a:b,this.map(function(){return p.clone(this,a,b)})},html:function(a){return p.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(bm,""):b;if(typeof a=="string"&&!bs.test(a)&&(p.support.htmlSerialize||!bu.test(a))&&(p.support.leadingWhitespace||!bn.test(a))&&!bz[(bp.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(bo,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(f){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){return bh(this[0])?this.length?this.pushStack(p(p.isFunction(a)?a():a),"replaceWith",a):this:p.isFunction(a)?this.each(function(b){var c=p(this),d=c.html();c.replaceWith(a.call(this,b,d))}):(typeof a!="string"&&(a=p(a).detach()),this.each(function(){var b=this.nextSibling,c=this.parentNode;p(this).remove(),b?p(b).before(a):p(c).append(a)}))},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){a=[].concat.apply([],a);var e,f,g,h,i=0,j=a[0],k=[],l=this.length;if(!p.support.checkClone&&l>1&&typeof j=="string"&&bw.test(j))return this.each(function(){p(this).domManip(a,c,d)});if(p.isFunction(j))return this.each(function(e){var f=p(this);a[0]=j.call(this,e,c?f.html():b),f.domManip(a,c,d)});if(this[0]){e=p.buildFragment(a,this,k),g=e.fragment,f=g.firstChild,g.childNodes.length===1&&(g=f);if(f){c=c&&p.nodeName(f,"tr");for(h=e.cacheable||l-1;i<l;i++)d.call(c&&p.nodeName(this[i],"table")?bC(this[i],"tbody"):this[i],i===h?g:p.clone(g,!0,!0))}g=f=null,k.length&&p.each(k,function(a,b){b.src?p.ajax?p.ajax({url:b.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):p.error("no ajax"):p.globalEval((b.text||b.textContent||b.innerHTML||"").replace(by,"")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),p.buildFragment=function(a,c,d){var f,g,h,i=a[0];return c=c||e,c=!c.nodeType&&c[0]||c,c=c.ownerDocument||c,a.length===1&&typeof i=="string"&&i.length<512&&c===e&&i.charAt(0)==="<"&&!bt.test(i)&&(p.support.checkClone||!bw.test(i))&&(p.support.html5Clone||!bu.test(i))&&(g=!0,f=p.fragments[i],h=f!==b),f||(f=c.createDocumentFragment(),p.clean(a,c,f,d),g&&(p.fragments[i]=h&&f)),{fragment:f,cacheable:g}},p.fragments={},p.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){p.fn[a]=function(c){var d,e=0,f=[],g=p(c),h=g.length,i=this.length===1&&this[0].parentNode;if((i==null||i&&i.nodeType===11&&i.childNodes.length===1)&&h===1)return g[b](this[0]),this;for(;e<h;e++)d=(e>0?this.clone(!0):this).get(),p(g[e])[b](d),f=f.concat(d);return this.pushStack(f,a,g.selector)}}),p.extend({clone:function(a,b,c){var d,e,f,g;p.support.html5Clone||p.isXMLDoc(a)||!bu.test("<"+a.nodeName+">")?g=a.cloneNode(!0):(bB.innerHTML=a.outerHTML,bB.removeChild(g=bB.firstChild));if((!p.support.noCloneEvent||!p.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!p.isXMLDoc(a)){bE(a,g),d=bF(a),e=bF(g);for(f=0;d[f];++f)e[f]&&bE(d[f],e[f])}if(b){bD(a,g);if(c){d=bF(a),e=bF(g);for(f=0;d[f];++f)bD(d[f],e[f])}}return d=e=null,g},clean:function(a,b,c,d){var f,g,h,i,j,k,l,m,n,o,q,r,s=b===e&&bA,t=[];if(!b||typeof b.createDocumentFragment=="undefined")b=e;for(f=0;(h=a[f])!=null;f++){typeof h=="number"&&(h+="");if(!h)continue;if(typeof h=="string")if(!br.test(h))h=b.createTextNode(h);else{s=s||bk(b),l=b.createElement("div"),s.appendChild(l),h=h.replace(bo,"<$1></$2>"),i=(bp.exec(h)||["",""])[1].toLowerCase(),j=bz[i]||bz._default,k=j[0],l.innerHTML=j[1]+h+j[2];while(k--)l=l.lastChild;if(!p.support.tbody){m=bq.test(h),n=i==="table"&&!m?l.firstChild&&l.firstChild.childNodes:j[1]==="<table>"&&!m?l.childNodes:[];for(g=n.length-1;g>=0;--g)p.nodeName(n[g],"tbody")&&!n[g].childNodes.length&&n[g].parentNode.removeChild(n[g])}!p.support.leadingWhitespace&&bn.test(h)&&l.insertBefore(b.createTextNode(bn.exec(h)[0]),l.firstChild),h=l.childNodes,l.parentNode.removeChild(l)}h.nodeType?t.push(h):p.merge(t,h)}l&&(h=l=s=null);if(!p.support.appendChecked)for(f=0;(h=t[f])!=null;f++)p.nodeName(h,"input")?bG(h):typeof h.getElementsByTagName!="undefined"&&p.grep(h.getElementsByTagName("input"),bG);if(c){q=function(a){if(!a.type||bx.test(a.type))return d?d.push(a.parentNode?a.parentNode.removeChild(a):a):c.appendChild(a)};for(f=0;(h=t[f])!=null;f++)if(!p.nodeName(h,"script")||!q(h))c.appendChild(h),typeof h.getElementsByTagName!="undefined"&&(r=p.grep(p.merge([],h.getElementsByTagName("script")),q),t.splice.apply(t,[f+1,0].concat(r)),f+=r.length)}return t},cleanData:function(a,b){var c,d,e,f,g=0,h=p.expando,i=p.cache,j=p.support.deleteExpando,k=p.event.special;for(;(e=a[g])!=null;g++)if(b||p.acceptData(e)){d=e[h],c=d&&i[d];if(c){if(c.events)for(f in c.events)k[f]?p.event.remove(e,f):p.removeEvent(e,f,c.handle);i[d]&&(delete i[d],j?delete e[h]:e.removeAttribute?e.removeAttribute(h):e[h]=null,p.deletedIds.push(d))}}}}),function(){var a,b;p.uaMatch=function(a){a=a.toLowerCase();var b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},a=p.uaMatch(g.userAgent),b={},a.browser&&(b[a.browser]=!0,b.version=a.version),b.chrome?b.webkit=!0:b.webkit&&(b.safari=!0),p.browser=b,p.sub=function(){function a(b,c){return new a.fn.init(b,c)}p.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function c(c,d){return d&&d instanceof p&&!(d instanceof a)&&(d=a(d)),p.fn.init.call(this,c,d,b)},a.fn.init.prototype=a.fn;var b=a(e);return a}}();var bH,bI,bJ,bK=/alpha\([^)]*\)/i,bL=/opacity=([^)]*)/,bM=/^(top|right|bottom|left)$/,bN=/^(none|table(?!-c[ea]).+)/,bO=/^margin/,bP=new RegExp("^("+q+")(.*)$","i"),bQ=new RegExp("^("+q+")(?!px)[a-z%]+$","i"),bR=new RegExp("^([-+])=("+q+")","i"),bS={},bT={position:"absolute",visibility:"hidden",display:"block"},bU={letterSpacing:0,fontWeight:400},bV=["Top","Right","Bottom","Left"],bW=["Webkit","O","Moz","ms"],bX=p.fn.toggle;p.fn.extend({css:function(a,c){return p.access(this,function(a,c,d){return d!==b?p.style(a,c,d):p.css(a,c)},a,c,arguments.length>1)},show:function(){return b$(this,!0)},hide:function(){return b$(this)},toggle:function(a,b){var c=typeof a=="boolean";return p.isFunction(a)&&p.isFunction(b)?bX.apply(this,arguments):this.each(function(){(c?a:bZ(this))?p(this).show():p(this).hide()})}}),p.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bH(a,"opacity");return c===""?"1":c}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":p.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!a||a.nodeType===3||a.nodeType===8||!a.style)return;var f,g,h,i=p.camelCase(c),j=a.style;c=p.cssProps[i]||(p.cssProps[i]=bY(j,i)),h=p.cssHooks[c]||p.cssHooks[i];if(d===b)return h&&"get"in h&&(f=h.get(a,!1,e))!==b?f:j[c];g=typeof d,g==="string"&&(f=bR.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat(p.css(a,c)),g="number");if(d==null||g==="number"&&isNaN(d))return;g==="number"&&!p.cssNumber[i]&&(d+="px");if(!h||!("set"in h)||(d=h.set(a,d,e))!==b)try{j[c]=d}catch(k){}},css:function(a,c,d,e){var f,g,h,i=p.camelCase(c);return c=p.cssProps[i]||(p.cssProps[i]=bY(a.style,i)),h=p.cssHooks[c]||p.cssHooks[i],h&&"get"in h&&(f=h.get(a,!0,e)),f===b&&(f=bH(a,c)),f==="normal"&&c in bU&&(f=bU[c]),d||e!==b?(g=parseFloat(f),d||p.isNumeric(g)?g||0:f):f},swap:function(a,b,c){var d,e,f={};for(e in b)f[e]=a.style[e],a.style[e]=b[e];d=c.call(a);for(e in b)a.style[e]=f[e];return d}}),a.getComputedStyle?bH=function(b,c){var d,e,f,g,h=a.getComputedStyle(b,null),i=b.style;return h&&(d=h[c],d===""&&!p.contains(b.ownerDocument,b)&&(d=p.style(b,c)),bQ.test(d)&&bO.test(c)&&(e=i.width,f=i.minWidth,g=i.maxWidth,i.minWidth=i.maxWidth=i.width=d,d=h.width,i.width=e,i.minWidth=f,i.maxWidth=g)),d}:e.documentElement.currentStyle&&(bH=function(a,b){var c,d,e=a.currentStyle&&a.currentStyle[b],f=a.style;return e==null&&f&&f[b]&&(e=f[b]),bQ.test(e)&&!bM.test(b)&&(c=f.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":e,e=f.pixelLeft+"px",f.left=c,d&&(a.runtimeStyle.left=d)),e===""?"auto":e}),p.each(["height","width"],function(a,b){p.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth===0&&bN.test(bH(a,"display"))?p.swap(a,bT,function(){return cb(a,b,d)}):cb(a,b,d)},set:function(a,c,d){return b_(a,c,d?ca(a,b,d,p.support.boxSizing&&p.css(a,"boxSizing")==="border-box"):0)}}}),p.support.opacity||(p.cssHooks.opacity={get:function(a,b){return bL.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=p.isNumeric(b)?"alpha(opacity="+b*100+")":"",f=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&p.trim(f.replace(bK,""))===""&&c.removeAttribute){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bK.test(f)?f.replace(bK,e):f+" "+e}}),p(function(){p.support.reliableMarginRight||(p.cssHooks.marginRight={get:function(a,b){return p.swap(a,{display:"inline-block"},function(){if(b)return bH(a,"marginRight")})}}),!p.support.pixelPosition&&p.fn.position&&p.each(["top","left"],function(a,b){p.cssHooks[b]={get:function(a,c){if(c){var d=bH(a,b);return bQ.test(d)?p(a).position()[b]+"px":d}}}})}),p.expr&&p.expr.filters&&(p.expr.filters.hidden=function(a){return a.offsetWidth===0&&a.offsetHeight===0||!p.support.reliableHiddenOffsets&&(a.style&&a.style.display||bH(a,"display"))==="none"},p.expr.filters.visible=function(a){return!p.expr.filters.hidden(a)}),p.each({margin:"",padding:"",border:"Width"},function(a,b){p.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bV[d]+b]=e[d]||e[d-2]||e[0];return f}},bO.test(a)||(p.cssHooks[a+b].set=b_)});var cd=/%20/g,ce=/\[\]$/,cf=/\r?\n/g,cg=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,ch=/^(?:select|textarea)/i;p.fn.extend({serialize:function(){return p.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?p.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ch.test(this.nodeName)||cg.test(this.type))}).map(function(a,b){var c=p(this).val();return c==null?null:p.isArray(c)?p.map(c,function(a,c){return{name:b.name,value:a.replace(cf,"\r\n")}}):{name:b.name,value:c.replace(cf,"\r\n")}}).get()}}),p.param=function(a,c){var d,e=[],f=function(a,b){b=p.isFunction(b)?b():b==null?"":b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=p.ajaxSettings&&p.ajaxSettings.traditional);if(p.isArray(a)||a.jquery&&!p.isPlainObject(a))p.each(a,function(){f(this.name,this.value)});else for(d in a)ci(d,a[d],c,f);return e.join("&").replace(cd,"+")};var cj,ck,cl=/#.*$/,cm=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,cn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,co=/^(?:GET|HEAD)$/,cp=/^\/\//,cq=/\?/,cr=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,cs=/([?&])_=[^&]*/,ct=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,cu=p.fn.load,cv={},cw={},cx=["*/"]+["*"];try{ck=f.href}catch(cy){ck=e.createElement("a"),ck.href="",ck=ck.href}cj=ct.exec(ck.toLowerCase())||[],p.fn.load=function(a,c,d){if(typeof a!="string"&&cu)return cu.apply(this,arguments);if(!this.length)return this;var e,f,g,h=this,i=a.indexOf(" ");return i>=0&&(e=a.slice(i,a.length),a=a.slice(0,i)),p.isFunction(c)?(d=c,c=b):c&&typeof c=="object"&&(f="POST"),p.ajax({url:a,type:f,dataType:"html",data:c,complete:function(a,b){d&&h.each(d,g||[a.responseText,b,a])}}).done(function(a){g=arguments,h.html(e?p("<div>").append(a.replace(cr,"")).find(e):a)}),this},p.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){p.fn[b]=function(a){return this.on(b,a)}}),p.each(["get","post"],function(a,c){p[c]=function(a,d,e,f){return p.isFunction(d)&&(f=f||e,e=d,d=b),p.ajax({type:c,url:a,data:d,success:e,dataType:f})}}),p.extend({getScript:function(a,c){return p.get(a,b,c,"script")},getJSON:function(a,b,c){return p.get(a,b,c,"json")},ajaxSetup:function(a,b){return b?cB(a,p.ajaxSettings):(b=a,a=p.ajaxSettings),cB(a,b),a},ajaxSettings:{url:ck,isLocal:cn.test(cj[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":cx},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":p.parseJSON,"text xml":p.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:cz(cv),ajaxTransport:cz(cw),ajax:function(a,c){function y(a,c,f,i){var k,s,t,u,w,y=c;if(v===2)return;v=2,h&&clearTimeout(h),g=b,e=i||"",x.readyState=a>0?4:0,f&&(u=cC(l,x,f));if(a>=200&&a<300||a===304)l.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(p.lastModified[d]=w),w=x.getResponseHeader("Etag"),w&&(p.etag[d]=w)),a===304?(y="notmodified",k=!0):(k=cD(l,u),y=k.state,s=k.data,t=k.error,k=!t);else{t=y;if(!y||a)y="error",a<0&&(a=0)}x.status=a,x.statusText=(c||y)+"",k?o.resolveWith(m,[s,y,x]):o.rejectWith(m,[x,y,t]),x.statusCode(r),r=b,j&&n.trigger("ajax"+(k?"Success":"Error"),[x,l,k?s:t]),q.fireWith(m,[x,y]),j&&(n.trigger("ajaxComplete",[x,l]),--p.active||p.event.trigger("ajaxStop"))}typeof a=="object"&&(c=a,a=b),c=c||{};var d,e,f,g,h,i,j,k,l=p.ajaxSetup({},c),m=l.context||l,n=m!==l&&(m.nodeType||m instanceof p)?p(m):p.event,o=p.Deferred(),q=p.Callbacks("once memory"),r=l.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,setRequestHeader:function(a,b){if(!v){var c=a.toLowerCase();a=u[c]=u[c]||a,t[a]=b}return this},getAllResponseHeaders:function(){return v===2?e:null},getResponseHeader:function(a){var c;if(v===2){if(!f){f={};while(c=cm.exec(e))f[c[1].toLowerCase()]=c[2]}c=f[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){return v||(l.mimeType=a),this},abort:function(a){return a=a||w,g&&g.abort(a),y(0,a),this}};o.promise(x),x.success=x.done,x.error=x.fail,x.complete=q.add,x.statusCode=function(a){if(a){var b;if(v<2)for(b in a)r[b]=[r[b],a[b]];else b=a[x.status],x.always(b)}return this},l.url=((a||l.url)+"").replace(cl,"").replace(cp,cj[1]+"//"),l.dataTypes=p.trim(l.dataType||"*").toLowerCase().split(s),l.crossDomain==null&&(i=ct.exec(l.url.toLowerCase())||!1,l.crossDomain=i&&i.join(":")+(i[3]?"":i[1]==="http:"?80:443)!==cj.join(":")+(cj[3]?"":cj[1]==="http:"?80:443)),l.data&&l.processData&&typeof l.data!="string"&&(l.data=p.param(l.data,l.traditional)),cA(cv,l,c,x);if(v===2)return x;j=l.global,l.type=l.type.toUpperCase(),l.hasContent=!co.test(l.type),j&&p.active++===0&&p.event.trigger("ajaxStart");if(!l.hasContent){l.data&&(l.url+=(cq.test(l.url)?"&":"?")+l.data,delete l.data),d=l.url;if(l.cache===!1){var z=p.now(),A=l.url.replace(cs,"$1_="+z);l.url=A+(A===l.url?(cq.test(l.url)?"&":"?")+"_="+z:"")}}(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",l.contentType),l.ifModified&&(d=d||l.url,p.lastModified[d]&&x.setRequestHeader("If-Modified-Since",p.lastModified[d]),p.etag[d]&&x.setRequestHeader("If-None-Match",p.etag[d])),x.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+(l.dataTypes[0]!=="*"?", "+cx+"; q=0.01":""):l.accepts["*"]);for(k in l.headers)x.setRequestHeader(k,l.headers[k]);if(!l.beforeSend||l.beforeSend.call(m,x,l)!==!1&&v!==2){w="abort";for(k in{success:1,error:1,complete:1})x[k](l[k]);g=cA(cw,l,c,x);if(!g)y(-1,"No Transport");else{x.readyState=1,j&&n.trigger("ajaxSend",[x,l]),l.async&&l.timeout>0&&(h=setTimeout(function(){x.abort("timeout")},l.timeout));try{v=1,g.send(t,y)}catch(B){if(v<2)y(-1,B);else throw B}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var cE=[],cF=/\?/,cG=/(=)\?(?=&|$)|\?\?/,cH=p.now();p.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=cE.pop()||p.expando+"_"+cH++;return this[a]=!0,a}}),p.ajaxPrefilter("json jsonp",function(c,d,e){var f,g,h,i=c.data,j=c.url,k=c.jsonp!==!1,l=k&&cG.test(j),m=k&&!l&&typeof i=="string"&&!(c.contentType||"").indexOf("application/x-www-form-urlencoded")&&cG.test(i);if(c.dataTypes[0]==="jsonp"||l||m)return f=c.jsonpCallback=p.isFunction(c.jsonpCallback)?c.jsonpCallback():c.jsonpCallback,g=a[f],l?c.url=j.replace(cG,"$1"+f):m?c.data=i.replace(cG,"$1"+f):k&&(c.url+=(cF.test(j)?"&":"?")+c.jsonp+"="+f),c.converters["script json"]=function(){return h||p.error(f+" was not called"),h[0]},c.dataTypes[0]="json",a[f]=function(){h=arguments},e.always(function(){a[f]=g,c[f]&&(c.jsonpCallback=d.jsonpCallback,cE.push(f)),h&&p.isFunction(g)&&g(h[0]),h=g=b}),"script"}),p.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){return p.globalEval(a),a}}}),p.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),p.ajaxTransport("script",function(a){if(a.crossDomain){var c,d=e.head||e.getElementsByTagName("head")[0]||e.documentElement;return{send:function(f,g){c=e.createElement("script"),c.async="async",a.scriptCharset&&(c.charset=a.scriptCharset),c.src=a.url,c.onload=c.onreadystatechange=function(a,e){if(e||!c.readyState||/loaded|complete/.test(c.readyState))c.onload=c.onreadystatechange=null,d&&c.parentNode&&d.removeChild(c),c=b,e||g(200,"success")},d.insertBefore(c,d.firstChild)},abort:function(){c&&c.onload(0,1)}}}});var cI,cJ=a.ActiveXObject?function(){for(var a in cI)cI[a](0,1)}:!1,cK=0;p.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&cL()||cM()}:cL,function(a){p.extend(p.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(p.ajaxSettings.xhr()),p.support.ajax&&p.ajaxTransport(function(c){if(!c.crossDomain||p.support.cors){var d;return{send:function(e,f){var g,h,i=c.xhr();c.username?i.open(c.type,c.url,c.async,c.username,c.password):i.open(c.type,c.url,c.async);if(c.xhrFields)for(h in c.xhrFields)i[h]=c.xhrFields[h];c.mimeType&&i.overrideMimeType&&i.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(h in e)i.setRequestHeader(h,e[h])}catch(j){}i.send(c.hasContent&&c.data||null),d=function(a,e){var h,j,k,l,m;try{if(d&&(e||i.readyState===4)){d=b,g&&(i.onreadystatechange=p.noop,cJ&&delete cI[g]);if(e)i.readyState!==4&&i.abort();else{h=i.status,k=i.getAllResponseHeaders(),l={},m=i.responseXML,m&&m.documentElement&&(l.xml=m);try{l.text=i.responseText}catch(a){}try{j=i.statusText}catch(n){j=""}!h&&c.isLocal&&!c.crossDomain?h=l.text?200:404:h===1223&&(h=204)}}}catch(o){e||f(-1,o)}l&&f(h,j,l,k)},c.async?i.readyState===4?setTimeout(d,0):(g=++cK,cJ&&(cI||(cI={},p(a).unload(cJ)),cI[g]=d),i.onreadystatechange=d):d()},abort:function(){d&&d(0,1)}}}});var cN,cO,cP=/^(?:toggle|show|hide)$/,cQ=new RegExp("^(?:([-+])=|)("+q+")([a-z%]*)$","i"),cR=/queueHooks$/,cS=[cY],cT={"*":[function(a,b){var c,d,e=this.createTween(a,b),f=cQ.exec(b),g=e.cur(),h=+g||0,i=1,j=20;if(f){c=+f[2],d=f[3]||(p.cssNumber[a]?"":"px");if(d!=="px"&&h){h=p.css(e.elem,a,!0)||c||1;do i=i||".5",h=h/i,p.style(e.elem,a,h+d);while(i!==(i=e.cur()/g)&&i!==1&&--j)}e.unit=d,e.start=h,e.end=f[1]?h+(f[1]+1)*c:c}return e}]};p.Animation=p.extend(cW,{tweener:function(a,b){p.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");var c,d=0,e=a.length;for(;d<e;d++)c=a[d],cT[c]=cT[c]||[],cT[c].unshift(b)},prefilter:function(a,b){b?cS.unshift(a):cS.push(a)}}),p.Tween=cZ,cZ.prototype={constructor:cZ,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(p.cssNumber[c]?"":"px")},cur:function(){var a=cZ.propHooks[this.prop];return a&&a.get?a.get(this):cZ.propHooks._default.get(this)},run:function(a){var b,c=cZ.propHooks[this.prop];return this.options.duration?this.pos=b=p.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):cZ.propHooks._default.set(this),this}},cZ.prototype.init.prototype=cZ.prototype,cZ.propHooks={_default:{get:function(a){var b;return a.elem[a.prop]==null||!!a.elem.style&&a.elem.style[a.prop]!=null?(b=p.css(a.elem,a.prop,!1,""),!b||b==="auto"?0:b):a.elem[a.prop]},set:function(a){p.fx.step[a.prop]?p.fx.step[a.prop](a):a.elem.style&&(a.elem.style[p.cssProps[a.prop]]!=null||p.cssHooks[a.prop])?p.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},cZ.propHooks.scrollTop=cZ.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},p.each(["toggle","show","hide"],function(a,b){var c=p.fn[b];p.fn[b]=function(d,e,f){return d==null||typeof d=="boolean"||!a&&p.isFunction(d)&&p.isFunction(e)?c.apply(this,arguments):this.animate(c$(b,!0),d,e,f)}}),p.fn.extend({fadeTo:function(a,b,c,d){return this.filter(bZ).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=p.isEmptyObject(a),f=p.speed(b,c,d),g=function(){var b=cW(this,p.extend({},a),f);e&&b.stop(!0)};return e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,c,d){var e=function(a){var b=a.stop;delete a.stop,b(d)};return typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,c=a!=null&&a+"queueHooks",f=p.timers,g=p._data(this);if(c)g[c]&&g[c].stop&&e(g[c]);else for(c in g)g[c]&&g[c].stop&&cR.test(c)&&e(g[c]);for(c=f.length;c--;)f[c].elem===this&&(a==null||f[c].queue===a)&&(f[c].anim.stop(d),b=!1,f.splice(c,1));(b||!d)&&p.dequeue(this,a)})}}),p.each({slideDown:c$("show"),slideUp:c$("hide"),slideToggle:c$("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){p.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),p.speed=function(a,b,c){var d=a&&typeof a=="object"?p.extend({},a):{complete:c||!c&&b||p.isFunction(a)&&a,duration:a,easing:c&&b||b&&!p.isFunction(b)&&b};d.duration=p.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in p.fx.speeds?p.fx.speeds[d.duration]:p.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";return d.old=d.complete,d.complete=function(){p.isFunction(d.old)&&d.old.call(this),d.queue&&p.dequeue(this,d.queue)},d},p.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},p.timers=[],p.fx=cZ.prototype.init,p.fx.tick=function(){var a,b=p.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||p.fx.stop()},p.fx.timer=function(a){a()&&p.timers.push(a)&&!cO&&(cO=setInterval(p.fx.tick,p.fx.interval))},p.fx.interval=13,p.fx.stop=function(){clearInterval(cO),cO=null},p.fx.speeds={slow:600,fast:200,_default:400},p.fx.step={},p.expr&&p.expr.filters&&(p.expr.filters.animated=function(a){return p.grep(p.timers,function(b){return a===b.elem}).length});var c_=/^(?:body|html)$/i;p.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){p.offset.setOffset(this,a,b)});var c,d,e,f,g,h,i,j={top:0,left:0},k=this[0],l=k&&k.ownerDocument;if(!l)return;return(d=l.body)===k?p.offset.bodyOffset(k):(c=l.documentElement,p.contains(c,k)?(typeof k.getBoundingClientRect!="undefined"&&(j=k.getBoundingClientRect()),e=da(l),f=c.clientTop||d.clientTop||0,g=c.clientLeft||d.clientLeft||0,h=e.pageYOffset||c.scrollTop,i=e.pageXOffset||c.scrollLeft,{top:j.top+h-f,left:j.left+i-g}):j)},p.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;return p.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(p.css(a,"marginTop"))||0,c+=parseFloat(p.css(a,"marginLeft"))||0),{top:b,left:c}},setOffset:function(a,b,c){var d=p.css(a,"position");d==="static"&&(a.style.position="relative");var e=p(a),f=e.offset(),g=p.css(a,"top"),h=p.css(a,"left"),i=(d==="absolute"||d==="fixed")&&p.inArray("auto",[g,h])>-1,j={},k={},l,m;i?(k=e.position(),l=k.top,m=k.left):(l=parseFloat(g)||0,m=parseFloat(h)||0),p.isFunction(b)&&(b=b.call(a,c,f)),b.top!=null&&(j.top=b.top-f.top+l),b.left!=null&&(j.left=b.left-f.left+m),"using"in b?b.using.call(a,j):e.css(j)}},p.fn.extend({position:function(){if(!this[0])return;var a=this[0],b=this.offsetParent(),c=this.offset(),d=c_.test(b[0].nodeName)?{top:0,left:0}:b.offset();return c.top-=parseFloat(p.css(a,"marginTop"))||0,c.left-=parseFloat(p.css(a,"marginLeft"))||0,d.top+=parseFloat(p.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(p.css(b[0],"borderLeftWidth"))||0,{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||e.body;while(a&&!c_.test(a.nodeName)&&p.css(a,"position")==="static")a=a.offsetParent;return a||e.body})}}),p.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);p.fn[a]=function(e){return p.access(this,function(a,e,f){var g=da(a);if(f===b)return g?c in g?g[c]:g.document.documentElement[e]:a[e];g?g.scrollTo(d?p(g).scrollLeft():f,d?f:p(g).scrollTop()):a[e]=f},a,e,arguments.length,null)}}),p.each({Height:"height",Width:"width"},function(a,c){p.each({padding:"inner"+a,content:c,"":"outer"+a},function(d,e){p.fn[e]=function(e,f){var g=arguments.length&&(d||typeof e!="boolean"),h=d||(e===!0||f===!0?"margin":"border");return p.access(this,function(c,d,e){var f;return p.isWindow(c)?c.document.documentElement["client"+a]:c.nodeType===9?(f=c.documentElement,Math.max(c.body["scroll"+a],f["scroll"+a],c.body["offset"+a],f["offset"+a],f["client"+a])):e===b?p.css(c,d,e,h):p.style(c,d,e,h)},c,g?e:b,g,null)}})}),a.jQuery=a.$=p,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return p})})(window);
|
style-guide/src/components/design-system-partials/otkit-breakpoints.js
|
opentable/design-tokens
|
import React from 'react';
import _ from 'lodash';
import token from 'otkit-breakpoints/token.common';
import SectionHeader from '../section-header';
import styles from '../../styles/index.module.scss';
const Breakpoints = () => {
var tokens = _.toPairsIn(token);
tokens = tokens.map((token, index) => {
return (
<div key={index}>
{_.kebabCase(token[0])}: {token[1]}
</div>
);
});
return (
<div className={styles.mainContainer}>
<SectionHeader text="Breakpoints" type="SectionHeader__small" />
{tokens}
</div>
);
};
export default Breakpoints;
|
server/sonar-web/src/main/js/apps/code/components/ComponentsEmpty.js
|
lbndev/sonarqube
|
/*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import React from 'react';
import { translate } from '../../../helpers/l10n';
const ComponentsEmpty = () => (
<tr>
<td colSpan="2">
{translate('no_results')}
</td>
<td colSpan="6" />
</tr>
);
export default ComponentsEmpty;
|
src/containers/MenuHeaderContainer.js
|
KmKm007/oa
|
import React from 'react'
import cs from 'classnames'
import createHistory from 'history/createHashHistory'
const history = createHistory()
class MenuHeaderContainer extends React.Component {
static defaultProps = {
defaultLeftLabel: '返回',
handleDefaultLeftClick: () => {
history.goBack()
}
}
render () {
const {
leftLabel,
rightLabel,
title,
handleLeftClick,
handleRightClick,
handleDefaultLeftClick,
defaultLeftLabel
} = this.props
const onLeftClick = handleLeftClick ? handleLeftClick : handleDefaultLeftClick
const onRightClick = handleRightClick
return (
<div className="header">
<div className={cs('text-center', 'headerLeftContainter')}>
<a onClick={e => {
e.preventDefault()
onLeftClick()
}}>
{leftLabel || defaultLeftLabel}
</a>
</div>
<h2 className={cs('text-center', 'headerMiddleContainer')}>{title}</h2>
<div className={cs('text-center', 'headerRightContainer')}>
<a onClick={e => {
e.preventDefault()
if (typeof(onRightClick) === 'function')
onRightClick()
}}>
{ rightLabel || ''}
</a>
</div>
</div>
)
}
}
export default MenuHeaderContainer
|
frontend/src/containers/ChartCard/index.js
|
qiubit/luminis
|
/*
* Copyright (C) 2017 Paweł Goliński
* Copyright (C) 2017 Piotr Wiśniewski
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
import React from 'react'
import Dygraph from 'dygraphs'
import { fromJS } from 'immutable'
import MomentDate from 'moment'
import DateTimePicker from 'react-datetime'
import NumericInput from 'react-numeric-input'
import { Card, CardTitle, CardText } from 'material-ui/Card'
import RaisedButton from 'material-ui/RaisedButton'
import 'dygraphs/dist/dygraph.css'
import {
requestNewChart,
cancelRequest,
} from '../RequestManager/actions'
import {
PENDING_STATE
} from '../RequestManager/constants'
import {
DATA_RANGE_LIVE,
DATA_RANGE_1D,
DATA_RANGE_30D,
DATA_RANGE_1Y,
DATA_RANGE_CUSTOM,
AGGREGATION_1M,
AGGREGATION_30M,
AGGREGATION_24H,
AGGREGATION_CUSTOM,
} from './constants'
class DatePickerBar extends React.Component {
constructor(props) {
super(props)
this.state = {
begin: props.begin,
end: props.end
}
this.setBegin = this.setBegin.bind(this)
this.setEnd = this.setEnd.bind(this)
}
setBegin(newBegin) {
if (!(typeof newBegin === 'string' || newBegin instanceof String)) {
this.setState({begin: newBegin})
}
}
setEnd(newEnd) {
if (!(typeof newEnd === 'string' || newEnd instanceof String)) {
this.setState({end: newEnd})
}
}
render() {
return (
<div style={{display: 'flex', justifyContent: 'space-between'}}>
<DateTimePicker
onChange={this.setBegin}
open={false}
dateFormat={'DD.MM.YYYY'}
timeFormat={'HH:mm:ss'}
defaultValue={this.props.begin}/>
<RaisedButton
onClick={this.props.onSubmit(this.state.begin, this.state.end)}
primary={true}
label="SUBMIT"
/>
<DateTimePicker
onChange={this.setEnd}
open={false}
dateFormat={'DD.MM.YYYY'}
timeFormat={'HH:mm:ss'}
defaultValue={this.props.end}/>
</div>
)
}
}
function StyledInput(props) {
return (
<NumericInput
{...props}
style={{input: {
'color': 'white',
'backgroundColor': 'rgb(48, 48, 48)',
'fontSize': '16px',
'boxShadow': 'rgba(0, 0, 0, 0.2) 0px 1px 6px, rgba(0, 0, 0, 0.12) 0px 1px 4px',
'height': '37px',
'textAlign': 'center',
'border': '0px',
}}}/>
)
}
class AggregationPickerBar extends React.Component {
constructor(props) {
super(props)
let sec = this.props.aggregationLength
let min = 0
let hours = 0
min = Math.floor(sec / 60)
sec -= min * 60
hours = Math.floor(min / 60)
min -= hours * 60
this.state = {
aggregationHours: hours,
aggregationMinutes: min,
aggregationSeconds: sec
}
this.getAggregationLength = this.getAggregationLength.bind(this)
}
getAggregationLength() {
return this.state.aggregationSeconds +
60 * this.state.aggregationMinutes + 3600 * this.state.aggregationHours
}
render() {
return (
<div>
<StyledInput
min={0}
format={(num) => num + 'h'}
value={this.state.aggregationHours}
onChange={(value) => {this.setState({aggregationHours: value})}}/>
<StyledInput
min={0}
max={59}
format={(num) => num + 'm'}
value={this.state.aggregationMinutes}
onChange={(value) => {this.setState({aggregationMinutes: value})}}/>
<StyledInput
min={0}
max={59}
format={(num) => num + 's'}
value={this.state.aggregationSeconds}
onChange={(value) => {this.setState({aggregationSeconds: value})}}/>
<RaisedButton
onClick={this.props.onSubmit(this.getAggregationLength())}
primary={true}
label="SUBMIT"
/>
</div>
)
}
}
class Graph extends React.Component {
shouldComponentUpdate(nextProps) {
return false
}
createGraph(data, labels, visibility) {
if (data.length > 0) {
return new Dygraph(
document.getElementById("graphdiv"),
data,
{
labels,
visibility
}
)
}
}
componentDidMount() {
this.graph = this.createGraph(this.props.data, this.props.labels, this.props.visibility)
}
componentWillReceiveProps(nextProps) {
// Don't create new Graph object if it was already created
// update it instead
if (this.graph) {
// update it only if something changed
if (this.props.data !== nextProps.data
|| this.props.labels !== nextProps.labels
|| this.props.visibility !== nextProps.visibility) {
this.graph.updateOptions({
'labels': nextProps.labels,
'visibility': nextProps.visibility,
'file': nextProps.data
})
}
} else {
this.graph = this.createGraph(this.props.data, this.props.labels, this.props.visibility)
}
}
render() {
return (
<div style={{ background: "#F0FFFF", color: "black", width: "100%" }} id="graphdiv"></div>
)
}
}
class ChartCard extends React.Component {
constructor(props) {
super(props)
let begin = (new MomentDate()).subtract(1, 'day')
let end = new MomentDate()
let initDataRange = fromJS({
begin,
end,
live: true
})
this.state = {
dataRange: initDataRange,
aggregationLength: 60,
requestDataRange: fromJS({}),
requestAggregationLength: null,
chartRequestId: null,
chartRequestData: null,
data: [],
labels: [],
visibility: [],
showDatePickers: false,
showAggregationPicker: false,
activeDataRangeButton: DATA_RANGE_LIVE,
activeAggregationButton: AGGREGATION_1M
}
this.onDataRangeChange = this.onDataRangeChange.bind(this)
this.onAggregationChange = this.onAggregationChange.bind(this)
this.onDataRangeSubmit = this.onDataRangeSubmit.bind(this)
this.onAggregationSubmit = this.onAggregationSubmit.bind(this)
this.updateSubscriptions = this.updateSubscriptions.bind(this)
this.updateLabels = this.updateLabels.bind(this)
this.updateVisibility = this.updateVisibility.bind(this)
this.updateAll = this.updateAll.bind(this)
}
// maps Luminis data chart to format needed by Dygraphs
makeData(chartData) {
// we don't want to change data stored inside RequestManager so
// make our own copy
let newData = chartData.slice()
for (var i = 0; i < chartData.length; ++i) {
// Luminis data is array of arrays so we also need to copy
// internal arrays
newData[i] = newData[i].slice()
// Dygraphs exptects Date object so we're converting timestamp here
newData[i][0] = new Date(newData[i][0] * 1000)
}
return newData
}
// create labels expected by Dygraphs
makeLabels(measurementDataMap){
let newLabels = []
// first element in point's array is always time
newLabels.push("Time")
measurementDataMap.forEach((measurementId) => {
newLabels.push(this.props.measurementNameGetter(measurementId.toString()))
})
return newLabels
}
// create table of visibility (bool values) expected by Dygraphs
makeVisibility(measurementIds, measurementIdsShown) {
let newVisibility = []
// time is always visible and Dygraphs doesn't expect value for time
measurementIds.forEach((measurementId) => {
newVisibility.push(measurementIdsShown.get(measurementId))
})
return newVisibility
}
makeRequest(nodeId, measurementIds, dataRange, aggregationLength) {
let requestedData =
measurementIds.map((measurementId) => Object({measurement_id: measurementId})).toJS()
let beginTs = Math.floor(dataRange.get('begin').valueOf() / 1000)
let endTs = Math.floor(dataRange.get('end').valueOf() / 1000)
let updateData = dataRange.get('live')
let aggregationType = 'mean'
return requestNewChart(
parseInt(nodeId, 10),
requestedData,
beginTs,
endTs,
updateData,
aggregationLength,
aggregationType)
}
updateSubscriptions(newMeasurementIds, newDataRange, newAggregationLength) {
if (this.state.chartRequestId) {
this.props.dispatch(cancelRequest(this.state.chartRequestId))
}
let newChartRequest = this.makeRequest(
this.props.params.nodeId,
newMeasurementIds,
newDataRange,
newAggregationLength)
this.props.dispatch(newChartRequest)
this.setState({
chartRequestId: newChartRequest.message.request_id,
requestDataRange: newDataRange,
requestAggregationLength: newAggregationLength,
})
}
updateLabels(newMeasurementIds) {
this.setState({
labels: this.makeLabels(newMeasurementIds)
})
}
updateVisibility(newMeasurementIds, newMeasurementIdsShown) {
this.setState({
visibility: this.makeVisibility(newMeasurementIds, newMeasurementIdsShown)
})
}
updateAll(newMeasurementIds, newMeasurementIdsShown, newRequestDataRange, newAggregationLength) {
this.updateSubscriptions(newMeasurementIds, newRequestDataRange, newAggregationLength)
this.updateLabels(newMeasurementIds)
this.updateVisibility(newMeasurementIds, newMeasurementIdsShown)
}
// Subscribe to live data on mount
componentWillMount() {
this.updateAll(
this.props.measurementIds,
this.props.measurementIdsShown,
this.state.dataRange,
this.state.aggregationLength)
}
componentWillUnmount() {
this.props.dispatch(cancelRequest(this.state.chartRequestId))
}
componentWillReceiveProps(nextProps) {
if (!this.props.measurementIds.equals(nextProps.measurementIds)) {
this.updateAll(
nextProps.measurementIds,
nextProps.measurementIdsShown,
this.state.dataRange,
this.state.aggregationLength)
} else if (!this.props.measurementIdsShown.equals(nextProps.measurementIdsShown)) {
this.updateVisibility(nextProps.measurementIds, nextProps.measurementIdsShown)
}
let request = nextProps.activeRequests.get(this.state.chartRequestId)
let newChartRequestData = null
if (request && request.get('state') !== PENDING_STATE) {
newChartRequestData = request.get('data').plot_data
}
if (newChartRequestData && this.state.chartRequestData !== newChartRequestData) {
this.setState({
chartRequestData: newChartRequestData,
data: this.makeData(newChartRequestData)})
}
}
onDataRangeChange = (button, begin, end, live, showDatePickers) => () => {
if (begin && end) {
let newDataRange = fromJS({
begin,
end,
live
})
this.setState({dataRange: newDataRange, activeDataRangeButton: button, showDatePickers})
this.updateAll(
this.props.measurementIds,
this.props.measurementIdsShown,
newDataRange, this.state.aggregationLength)
} else {
this.setState({activeDataRangeButton: button, showDatePickers})
}
}
onDataRangeSubmit = (newBegin, newEnd) => () => {
let newDataRange = this.state.dataRange
newDataRange = newDataRange.set('begin', newBegin).set('end', newEnd).set('live', false)
this.setState({dataRange: newDataRange})
this.updateAll(
this.props.measurementIds,
this.props.measurementIdsShown,
this.state.dataRange,
this.state.aggregationLength)
}
onAggregationSubmit = (newAggregationLength) => () => {
this.setState({aggregationLength: newAggregationLength})
this.updateAll(
this.props.measurementIds,
this.props.measurementIdsShown,
this.state.dataRange,
newAggregationLength)
}
onAggregationChange =
(newActiveAggregationButton, newAggregationLength, showAggregationPicker) => () => {
if (newAggregationLength) {
this.setState({
aggregationLength: newAggregationLength,
activeAggregationButton: newActiveAggregationButton,
showAggregationPicker })
this.updateAll(
this.props.measurementIds,
this.props.measurementIdsShown,
this.state.dataRange,
newAggregationLength)
} else {
this.setState({ activeAggregationButton: newActiveAggregationButton, showAggregationPicker })
}
}
render() {
const nodeMetadata = this.props.nodesMetadata.get(this.props.params.nodeId)
return (
<Card>
<CardTitle title={nodeMetadata.get('name')}/>
<CardText>
<div>
<Graph
data={this.state.data}
labels={this.state.labels}
visibility={this.state.visibility}/>
{
this.state.showDatePickers &&
<DatePickerBar
begin={this.state.dataRange.get('begin')}
end={this.state.dataRange.get('end')}
onSubmit={this.onDataRangeSubmit}
/>
}
<p>Data Range</p>
<RaisedButton
onClick={this.onDataRangeChange(
DATA_RANGE_LIVE,
(new MomentDate()).subtract(1, 'day'),
new MomentDate(),
true,
false)}
primary={this.state.activeDataRangeButton === DATA_RANGE_LIVE}
label="LIVE"
/>
<RaisedButton
onClick={this.onDataRangeChange(
DATA_RANGE_1D,
(new MomentDate()).subtract(1, 'day'),
new MomentDate(),
false,
false)}
primary={this.state.activeDataRangeButton === DATA_RANGE_1D}
label="1D"
/>
<RaisedButton
onClick={this.onDataRangeChange(
DATA_RANGE_30D,
(new MomentDate()).subtract(30, 'day'),
new MomentDate(),
false,
false)}
primary={this.state.activeDataRangeButton === DATA_RANGE_30D}
label="30D"
/>
<RaisedButton
onClick={this.onDataRangeChange(
DATA_RANGE_1Y,
(new MomentDate()).subtract(1, 'year'),
new MomentDate(),
false,
false)}
primary={this.state.activeDataRangeButton === DATA_RANGE_1Y}
label="1Y"
/>
<RaisedButton
onClick={this.onDataRangeChange(DATA_RANGE_CUSTOM, null, null, false, true)}
primary={this.state.activeDataRangeButton === DATA_RANGE_CUSTOM}
label="CUSTOM"
/>
</div>
<div>
<p>Aggregation</p>
<RaisedButton
onClick={this.onAggregationChange(AGGREGATION_1M, 60, false)}
primary={this.state.activeAggregationButton === AGGREGATION_1M}
label="1M"
/>
<RaisedButton
onClick={this.onAggregationChange(AGGREGATION_30M, 30 * 60, false)}
primary={this.state.activeAggregationButton === AGGREGATION_30M}
label="30M"
/>
<RaisedButton
onClick={this.onAggregationChange(AGGREGATION_24H, 24 * 60 * 60, false)}
primary={this.state.activeAggregationButton === AGGREGATION_24H}
label="24H"
/>
<RaisedButton
onClick={this.onAggregationChange(AGGREGATION_CUSTOM, null, true)}
primary={this.state.activeAggregationButton === AGGREGATION_CUSTOM}
label="CUSTOM"
/>
{
this.state.showAggregationPicker &&
<AggregationPickerBar
aggregationLength={this.state.aggregationLength}
onSubmit={this.onAggregationSubmit}
/>
}
</div>
</CardText>
</Card>
)
}
}
export default ChartCard
|
ajax/libs/quasar-framework/0.15.0-beta.10/quasar.mat.umd.js
|
sashberd/cdnjs
|
/*!
* Quasar Framework v0.15.0-beta.10
* (c) 2016-present Razvan Stoenescu
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('vue')) :
typeof define === 'function' && define.amd ? define(['vue'], factory) :
(global.Quasar = factory(global.Vue));
}(this, (function (Vue) { 'use strict';
Vue = Vue && Vue.hasOwnProperty('default') ? Vue['default'] : Vue;
var version = "0.15.0-beta.10";
function offset (el) {
if (el === window) {
return {top: 0, left: 0}
}
var ref = el.getBoundingClientRect();
var top = ref.top;
var left = ref.left;
return {top: top, left: left}
}
function style (el, property) {
return window.getComputedStyle(el).getPropertyValue(property)
}
function height (el) {
if (el === window) {
return viewport().height
}
return parseFloat(style(el, 'height'))
}
function width (el) {
if (el === window) {
return viewport().width
}
return parseFloat(style(el, 'width'))
}
function css (element, css) {
var style = element.style;
Object.keys(css).forEach(function (prop) {
style[prop] = css[prop];
});
}
function viewport () {
var
e = window,
a = 'inner';
if (!('innerWidth' in window)) {
a = 'client';
e = document.documentElement || document.body;
}
return {
width: e[a + 'Width'],
height: e[a + 'Height']
}
}
function ready (fn) {
if (typeof fn !== 'function') {
return
}
if (document.readyState === 'complete') {
return fn()
}
document.addEventListener('DOMContentLoaded', fn, false);
}
var prefix = ['-webkit-', '-moz-', '-ms-', '-o-'];
function cssTransform (val) {
var o = {transform: val};
prefix.forEach(function (p) {
o[p + 'transform'] = val;
});
return o
}
var dom = Object.freeze({
offset: offset,
style: style,
height: height,
width: width,
css: css,
viewport: viewport,
ready: ready,
cssTransform: cssTransform
});
/* eslint-disable no-useless-escape */
/* eslint-disable no-unused-expressions */
/* eslint-disable no-mixed-operators */
var isSSR = typeof window === 'undefined';
function getUserAgent () {
return (navigator.userAgent || navigator.vendor || window.opera).toLowerCase()
}
function getMatch (userAgent, platformMatch) {
var match = /(edge)\/([\w.]+)/.exec(userAgent) ||
/(opr)[\/]([\w.]+)/.exec(userAgent) ||
/(vivaldi)[\/]([\w.]+)/.exec(userAgent) ||
/(chrome)[\/]([\w.]+)/.exec(userAgent) ||
/(iemobile)[\/]([\w.]+)/.exec(userAgent) ||
/(version)(applewebkit)[\/]([\w.]+).*(safari)[\/]([\w.]+)/.exec(userAgent) ||
/(webkit)[\/]([\w.]+).*(version)[\/]([\w.]+).*(safari)[\/]([\w.]+)/.exec(userAgent) ||
/(webkit)[\/]([\w.]+)/.exec(userAgent) ||
/(opera)(?:.*version|)[\/]([\w.]+)/.exec(userAgent) ||
/(msie) ([\w.]+)/.exec(userAgent) ||
userAgent.indexOf('trident') >= 0 && /(rv)(?::| )([\w.]+)/.exec(userAgent) ||
userAgent.indexOf('compatible') < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(userAgent) ||
[];
return {
browser: match[5] || match[3] || match[1] || '',
version: match[2] || match[4] || '0',
versionNumber: match[4] || match[2] || '0',
platform: platformMatch[0] || ''
}
}
function getPlatformMatch (userAgent) {
return /(ipad)/.exec(userAgent) ||
/(ipod)/.exec(userAgent) ||
/(windows phone)/.exec(userAgent) ||
/(iphone)/.exec(userAgent) ||
/(kindle)/.exec(userAgent) ||
/(silk)/.exec(userAgent) ||
/(android)/.exec(userAgent) ||
/(win)/.exec(userAgent) ||
/(mac)/.exec(userAgent) ||
/(linux)/.exec(userAgent) ||
/(cros)/.exec(userAgent) ||
/(playbook)/.exec(userAgent) ||
/(bb)/.exec(userAgent) ||
/(blackberry)/.exec(userAgent) ||
[]
}
function getPlatform () {
var
userAgent = getUserAgent(),
platformMatch = getPlatformMatch(userAgent),
matched = getMatch(userAgent, platformMatch),
browser = {};
if (matched.browser) {
browser[matched.browser] = true;
browser.version = matched.version;
browser.versionNumber = parseInt(matched.versionNumber, 10);
}
if (matched.platform) {
browser[matched.platform] = true;
}
// These are all considered mobile platforms, meaning they run a mobile browser
if (browser.android || browser.bb || browser.blackberry || browser.ipad || browser.iphone ||
browser.ipod || browser.kindle || browser.playbook || browser.silk || browser['windows phone']) {
browser.mobile = true;
}
// Set iOS if on iPod, iPad or iPhone
if (browser.ipod || browser.ipad || browser.iphone) {
browser.ios = true;
}
if (browser['windows phone']) {
browser.winphone = true;
delete browser['windows phone'];
}
// These are all considered desktop platforms, meaning they run a desktop browser
if (browser.cros || browser.mac || browser.linux || browser.win) {
browser.desktop = true;
}
// Chrome, Opera 15+, Vivaldi and Safari are webkit based browsers
if (browser.chrome || browser.opr || browser.safari || browser.vivaldi) {
browser.webkit = true;
}
// IE11 has a new token so we will assign it msie to avoid breaking changes
if (browser.rv || browser.iemobile) {
matched.browser = 'ie';
browser.ie = true;
}
// Edge is officially known as Microsoft Edge, so rewrite the key to match
if (browser.edge) {
matched.browser = 'edge';
browser.edge = true;
}
// Blackberry browsers are marked as Safari on BlackBerry
if (browser.safari && browser.blackberry || browser.bb) {
matched.browser = 'blackberry';
browser.blackberry = true;
}
// Playbook browsers are marked as Safari on Playbook
if (browser.safari && browser.playbook) {
matched.browser = 'playbook';
browser.playbook = true;
}
// Opera 15+ are identified as opr
if (browser.opr) {
matched.browser = 'opera';
browser.opera = true;
}
// Stock Android browsers are marked as Safari on Android.
if (browser.safari && browser.android) {
matched.browser = 'android';
browser.android = true;
}
// Kindle browsers are marked as Safari on Kindle
if (browser.safari && browser.kindle) {
matched.browser = 'kindle';
browser.kindle = true;
}
// Kindle Silk browsers are marked as Safari on Kindle
if (browser.safari && browser.silk) {
matched.browser = 'silk';
browser.silk = true;
}
if (browser.vivaldi) {
matched.browser = 'vivaldi';
browser.vivaldi = true;
}
// Assign the name and platform variable
browser.name = matched.browser;
browser.platform = matched.platform;
if (window && window.process && window.process.versions && window.process.versions.electron) {
browser.electron = true;
}
else if (document.location.href.indexOf('chrome-extension://') === 0) {
browser.chromeExt = true;
}
else if (
window._cordovaNative ||
window.cordova ||
document.location.href.indexOf('http://') === -1
) {
browser.cordova = true;
}
return browser
}
var Platform = {
__installed: false,
install: function install (ref) {
var $q = ref.$q;
if (this.__installed) { return }
this.__installed = true;
if (isSSR) {
Platform.is = { ssr: true };
Platform.has = {
touch: false,
webStorage: false
};
Platform.within = { iframe: false };
}
else {
var webStorage;
try {
if (window.localStorage) {
webStorage = true;
}
}
catch (e) {
webStorage = false;
}
Platform.is = getPlatform();
Platform.has = {
touch: (function () { return !!('ontouchstart' in document.documentElement) || window.navigator.msMaxTouchPoints > 0; })(),
webStorage: webStorage
};
Platform.within = {
iframe: window.self !== window.top
};
}
$q.platform = Platform;
}
};
var History = {
__history: [],
add: function () {},
remove: function () {},
__installed: false,
install: function install () {
var this$1 = this;
if (this.__installed || !Platform.is.cordova || isSSR) {
return
}
this.__installed = true;
this.add = function (definition) {
this$1.__history.push(definition);
};
this.remove = function (definition) {
var index = this$1.__history.indexOf(definition);
if (index >= 0) {
this$1.__history.splice(index, 1);
}
};
document.addEventListener('deviceready', function () {
document.addEventListener('backbutton', function () {
if (this$1.__history.length) {
this$1.__history.pop().handler();
}
else {
window.history.back();
}
}, false);
});
}
}
/* eslint-disable no-extend-native, one-var, no-self-compare */
if (!Array.prototype.includes) {
Array.prototype.includes = function (searchEl, startFrom) {
var O = Object(this);
var len = parseInt(O.length, 10) || 0;
if (len === 0) {
return false
}
var n = parseInt(startFrom, 10) || 0;
var k;
if (n >= 0) {
k = n;
}
else {
k = len + n;
if (k < 0) { k = 0; }
}
var curEl;
while (k < len) {
curEl = O[k];
if (searchEl === curEl ||
(searchEl !== searchEl && curEl !== curEl)) { // NaN !== NaN
return true
}
k++;
}
return false
};
}
if (!String.prototype.startsWith) {
String.prototype.startsWith = function (str, position) {
position = position || 0;
return this.substr(position, str.length) === str
};
}
if (!String.prototype.endsWith) {
String.prototype.endsWith = function (str, position) {
var subjectString = this.toString();
if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
position = subjectString.length;
}
position -= str.length;
var lastIndex = subjectString.indexOf(str, position);
return lastIndex !== -1 && lastIndex === position
};
}
if (!isSSR && typeof Element.prototype.matches !== 'function') {
Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.webkitMatchesSelector || function matches (selector) {
var
element = this,
elements = (element.document || element.ownerDocument).querySelectorAll(selector),
index = 0;
while (elements[index] && elements[index] !== element) {
++index;
}
return Boolean(elements[index])
};
}
if (!isSSR && typeof Element.prototype.closest !== 'function') {
Element.prototype.closest = function closest (selector) {
var el = this;
while (el && el.nodeType === 1) {
if (el.matches(selector)) {
return el
}
el = el.parentNode;
}
return null
};
}
if (!Array.prototype.find) {
Object.defineProperty(Array.prototype, 'find', {
value: function value (predicate) {
if (this == null) {
throw new TypeError('Array.prototype.find called on null or undefined')
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function')
}
var value;
var
list = Object(this),
length = list.length >>> 0,
thisArg = arguments[1];
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return value
}
}
return undefined
}
});
}
var langEn = {
lang: 'en-us',
label: {
clear: 'Clear',
ok: 'OK',
cancel: 'Cancel',
close: 'Close',
set: 'Set',
select: 'Select',
reset: 'Reset',
remove: 'Remove',
update: 'Update',
create: 'Create',
search: 'Search',
filter: 'Filter',
refresh: 'Refresh'
},
date: {
days: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
daysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
firstDayOfWeek: 0, // 0-6, 0 - Sunday, 1 Monday, ...
format24h: false
},
pullToRefresh: {
pull: 'Pull down to refresh',
release: 'Release to refresh',
refresh: 'Refreshing...'
},
table: {
noData: 'No data available',
noResults: 'No matching records found',
loader: 'Loading...',
selectedRows: function (rows) { return rows > 0 ? (rows + " row" + (rows === 1 ? '' : 's') + " selected.") : 'No selected rows.'; },
rowsPerPage: 'Rows per page:',
allRows: 'All',
pagination: function (start, end, total) { return (start + "-" + end + " of " + total); },
columns: 'Columns'
},
editor: {
url: 'URL',
bold: 'Bold',
italic: 'Italic',
strikethrough: 'Strikethrough',
underline: 'Underline',
unorderedList: 'Unordered List',
orderedList: 'Ordered List',
subscript: 'Subscript',
superscript: 'Superscript',
hyperlink: 'Hyperlink',
toggleFullscreen: 'Toggle Fullscreen',
quote: 'Quote',
left: 'Left align',
center: 'Center align',
right: 'Right align',
justify: 'Justify align',
print: 'Print',
outdent: 'Decrease indentation',
indent: 'Increase indentation',
removeFormat: 'Remove formatting',
formatting: 'Formatting',
fontSize: 'Font Size',
align: 'Align',
hr: 'Insert Horizontal Rule',
undo: 'Undo',
redo: 'Redo',
header1: 'Header 1',
header2: 'Header 2',
header3: 'Header 3',
header4: 'Header 4',
header5: 'Header 5',
header6: 'Header 6',
paragraph: 'Paragraph',
code: 'Code',
size1: 'Very small',
size2: 'A bit small',
size3: 'Normal',
size4: 'Medium-large',
size5: 'Big',
size6: 'Very big',
size7: 'Maximum',
defaultFont: 'Default Font'
},
tree: {
noNodes: 'No nodes available',
noResults: 'No matching nodes found'
}
}
var i18n = {
__installed: false,
install: function install (ref) {
var this$1 = this;
var $q = ref.$q;
var Vue$$1 = ref.Vue;
var lang = ref.lang;
if (this.__installed) { return }
this.__installed = true;
this.set = function (lang) {
if ( lang === void 0 ) lang = langEn;
lang.set = this$1.set;
Vue$$1.set($q, 'i18n', lang);
this$1.name = lang.lang;
this$1.lang = lang;
};
this.set(lang);
}
}
var iconMaterial = {
name: 'material',
type: {
positive: 'check_circle',
negative: 'warning',
info: 'info',
warning: 'priority_high'
},
arrow: {
up: 'arrow_upward',
right: 'arrow_forward',
down: 'arrow_downward',
left: 'arrow_back'
},
chevron: {
left: 'chevron_left',
right: 'chevron_right'
},
pullToRefresh: {
arrow: 'arrow_downward',
refresh: 'refresh'
},
search: {
icon: 'search',
clear: 'cancel',
clearInverted: 'clear'
},
carousel: {
left: 'chevron_left',
right: 'chevron_right',
quickNav: 'lens'
},
checkbox: {
checked: {
ios: 'check_circle',
mat: 'check_box'
},
unchecked: {
ios: 'radio_button_unchecked',
mat: 'check_box_outline_blank'
},
indeterminate: {
ios: 'remove_circle_outline',
mat: 'indeterminate_check_box'
}
},
chip: {
close: 'cancel'
},
chipsInput: {
add: 'send'
},
collapsible: {
icon: 'keyboard_arrow_down'
},
datetime: {
arrowLeft: 'chevron_left',
arrowRight: 'chevron_right'
},
editor: {
bold: 'format_bold',
italic: 'format_italic',
strikethrough: 'strikethrough_s',
underline: 'format_underlined',
unorderedList: 'format_list_bulleted',
orderedList: 'format_list_numbered',
subscript: 'vertical_align_bottom',
superscript: 'vertical_align_top',
hyperlink: 'link',
toggleFullscreen: 'fullscreen',
quote: 'format_quote',
left: 'format_align_left',
center: 'format_align_center',
right: 'format_align_right',
justify: 'format_align_justify',
print: 'print',
outdent: 'format_indent_decrease',
indent: 'format_indent_increase',
removeFormat: 'format_clear',
formatting: 'text_format',
fontSize: 'format_size',
align: 'format_align_left',
hr: 'remove',
undo: 'undo',
redo: 'redo',
header: 'format_size',
code: 'code',
size: 'format_size',
font: 'font_download'
},
fab: {
icon: 'add',
activeIcon: 'close'
},
input: {
showPass: 'visibility',
hidePass: 'visibility_off',
showNumber: 'keyboard',
hideNumber: 'keyboard_hide',
clear: 'cancel',
dropdown: 'arrow_drop_down'
},
pagination: {
first: 'first_page',
prev: 'keyboard_arrow_left',
next: 'keyboard_arrow_right',
last: 'last_page'
},
radio: {
checked: {
ios: 'check',
mat: 'radio_button_checked'
},
unchecked: {
ios: '',
mat: 'radio_button_unchecked'
}
},
rating: {
icon: 'grade'
},
stepper: {
done: 'check',
active: 'edit',
error: 'warning'
},
tabs: {
left: 'chevron_left',
right: 'chevron_right'
},
table: {
arrowUp: 'arrow_upward',
warning: 'warning',
prevPage: 'chevron_left',
nextPage: 'chevron_right'
},
tree: {
icon: 'play_arrow'
},
uploader: {
done: 'done',
clear: 'clear',
add: 'add',
upload: 'cloud_upload',
expand: 'keyboard_arrow_down',
file: 'insert_drive_file'
}
}
var icons = {
__installed: false,
install: function install (ref) {
var this$1 = this;
var $q = ref.$q;
var Vue$$1 = ref.Vue;
var iconSet = ref.iconSet;
if (this.__installed) { return }
this.__installed = true;
this.set = function (iconDef) {
if ( iconDef === void 0 ) iconDef = iconMaterial;
iconDef.set = this$1.set;
Vue$$1.set($q, 'icon', iconDef);
this$1.name = iconDef.name;
this$1.def = iconDef;
};
// TODO default ???
this.set(iconSet);
}
}
function addBodyClasses () {
var cls = [
"mat",
Platform.is.desktop ? 'desktop' : 'mobile',
Platform.has.touch ? 'touch' : 'no-touch',
("platform-" + (Platform.is.ios ? 'ios' : 'mat'))
];
Platform.within.iframe && cls.push('within-iframe');
Platform.is.cordova && cls.push('cordova');
Platform.is.electron && cls.push('electron');
document.body.classList.add.apply(document.body.classList, cls);
}
function install (_Vue, opts) {
if ( opts === void 0 ) opts = {};
if (this.__installed) {
return
}
this.__installed = true;
var $q = {
version: version,
theme: "mat"
};
// required plugins
Platform.install({ $q: $q });
History.install();
i18n.install({ $q: $q, Vue: _Vue, lang: opts.i18n });
icons.install({ $q: $q, Vue: _Vue, iconSet: opts.iconSet });
if (!isSSR) {
// inject body classes
ready(addBodyClasses);
}
if (opts.directives) {
Object.keys(opts.directives).forEach(function (key) {
var d = opts.directives[key];
if (d.name !== undefined && !d.name.startsWith('q-')) {
_Vue.directive(d.name, d);
}
});
}
if (opts.components) {
Object.keys(opts.components).forEach(function (key) {
var c = opts.components[key];
if (c.name !== undefined && c.name.startsWith('q-')) {
_Vue.component(c.name, c);
}
});
}
if (opts.plugins) {
Object.keys(opts.plugins).forEach(function (key) {
var p = opts.plugins[key];
if (typeof p.install === 'function') {
p.install({ $q: $q, Vue: _Vue });
}
});
}
_Vue.prototype.$q = $q;
}
var handlers = [];
var EscapeKey = {
__installed: false,
__install: function __install () {
this.__installed = true;
window.addEventListener('keyup', function (evt) {
if (handlers.length === 0) {
return
}
if (evt.which === 27 || evt.keyCode === 27) {
handlers[handlers.length - 1]();
}
});
},
register: function register (handler) {
if (Platform.is.desktop) {
if (!this.__installed) {
this.__install();
}
handlers.push(handler);
}
},
pop: function pop () {
if (Platform.is.desktop) {
handlers.pop();
}
}
}
var toString = Object.prototype.toString;
var hasOwn = Object.prototype.hasOwnProperty;
var class2type = {};
'Boolean Number String Function Array Date RegExp Object'.split(' ').forEach(function (name) {
class2type['[object ' + name + ']'] = name.toLowerCase();
});
function type (obj) {
return obj === null ? String(obj) : class2type[toString.call(obj)] || 'object'
}
function isPlainObject (obj) {
if (!obj || type(obj) !== 'object') {
return false
}
if (obj.constructor &&
!hasOwn.call(obj, 'constructor') &&
!hasOwn.call(obj.constructor.prototype, 'isPrototypeOf')) {
return false
}
var key;
for (key in obj) {}
return key === undefined || hasOwn.call(obj, key)
}
function extend () {
var arguments$1 = arguments;
var
options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
if (typeof target === 'boolean') {
deep = target;
target = arguments[1] || {};
i = 2;
}
if (Object(target) !== target && type(target) !== 'function') {
target = {};
}
if (length === i) {
target = this;
i--;
}
for (; i < length; i++) {
if ((options = arguments$1[i]) !== null) {
for (name in options) {
src = target[name];
copy = options[name];
if (target === copy) {
continue
}
if (deep && copy && (isPlainObject(copy) || (copyIsArray = type(copy) === 'array'))) {
if (copyIsArray) {
copyIsArray = false;
clone = src && type(src) === 'array' ? src : [];
}
else {
clone = src && isPlainObject(src) ? src : {};
}
target[name] = extend(deep, clone, copy);
}
else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
return target
}
/* eslint prefer-promise-reject-errors: 0 */
var ModelToggleMixin = {
props: {
value: Boolean
},
data: function data () {
return {
showing: false
}
},
watch: {
value: function value (val) {
var this$1 = this;
if (this.disable && val) {
this.$emit('input', false);
return
}
this.$nextTick(function () {
if (this$1.value !== this$1.showing) {
this$1[val ? 'show' : 'hide']();
}
});
}
},
methods: {
toggle: function toggle (evt) {
return this[this.showing ? 'hide' : 'show'](evt)
},
show: function show (evt) {
var this$1 = this;
if (this.disable || this.showing) {
return this.showPromise || Promise.resolve(evt)
}
if (this.hidePromise) {
this.hidePromiseReject();
}
this.showing = true;
if (this.value === false) {
this.$emit('input', true);
}
if (this.$options.modelToggle === void 0 || this.$options.modelToggle.history) {
this.__historyEntry = {
handler: this.hide
};
History.add(this.__historyEntry);
}
if (!this.__show) {
this.$emit('show');
return Promise.resolve(evt)
}
this.showPromise = new Promise(function (resolve, reject) {
this$1.showPromiseResolve = function () {
this$1.showPromise = null;
this$1.$emit('show');
resolve(evt);
};
this$1.showPromiseReject = function () {
this$1.showPromise = null;
reject(null); // eslint prefer-promise-reject-errors: 0
};
});
this.__show(evt);
return this.showPromise || Promise.resolve(evt)
},
hide: function hide (evt) {
var this$1 = this;
if (this.disable || !this.showing) {
return this.hidePromise || Promise.resolve(evt)
}
if (this.showPromise) {
this.showPromiseReject();
}
this.showing = false;
if (this.value === true) {
this.$emit('input', false);
}
if (this.__historyEntry) {
History.remove(this.__historyEntry);
this.__historyEntry = null;
}
if (!this.__hide) {
this.$emit('hide');
return Promise.resolve()
}
this.hidePromise = new Promise(function (resolve, reject) {
this$1.hidePromiseResolve = function () {
this$1.hidePromise = null;
this$1.$emit('hide');
resolve();
};
this$1.hidePromiseReject = function () {
this$1.hidePromise = null;
reject(null);
};
});
this.__hide(evt);
return this.hidePromise || Promise.resolve(evt)
}
},
beforeDestroy: function beforeDestroy () {
if (this.showing) {
this.showPromise && this.showPromiseReject();
this.hidePromise && this.hidePromiseReject();
this.$emit('input', false);
this.__hide && this.__hide();
}
}
}
var positions = {
top: 'items-start justify-center with-backdrop',
bottom: 'items-end justify-center with-backdrop',
right: 'items-center justify-end with-backdrop',
left: 'items-center justify-start with-backdrop'
};
var positionCSS = {
maxHeight: '80vh',
height: 'auto'
};
function additionalCSS (position) {
var css = {};
if (['left', 'right'].includes(position)) {
css.maxWidth = '90vw';
}
return css
}
var openedModalNumber = 0;
var QModal = {
name: 'q-modal',
mixins: [ModelToggleMixin],
props: {
position: {
type: String,
default: '',
validator: function validator (val) {
return val === '' || ['top', 'bottom', 'left', 'right'].includes(val)
}
},
transition: String,
enterClass: String,
leaveClass: String,
positionClasses: {
type: String,
default: 'flex-center'
},
contentClasses: [Object, Array, String],
contentCss: [Object, Array, String],
noBackdropDismiss: {
type: Boolean,
default: false
},
noEscDismiss: {
type: Boolean,
default: false
},
minimized: Boolean,
maximized: Boolean
},
watch: {
$route: function $route () {
this.hide();
}
},
computed: {
modalClasses: function modalClasses () {
var cls = this.position
? positions[this.position]
: this.positionClasses;
if (this.maximized) {
return ['maximized', cls]
}
else if (this.minimized) {
return ['minimized', cls]
}
return cls
},
transitionProps: function transitionProps () {
if (this.position) {
return { name: ("q-modal-" + (this.position)) }
}
if (this.enterClass === void 0 && this.leaveClass === void 0) {
return { name: this.transition || 'q-modal' }
}
return {
enterActiveClass: this.enterClass,
leaveActiveClass: this.leaveClass
}
},
modalCss: function modalCss () {
if (this.position) {
var css = Array.isArray(this.contentCss)
? this.contentCss
: [this.contentCss];
css.unshift(extend(
{},
positionCSS,
additionalCSS(this.position)
));
return css
}
return this.contentCss
}
},
methods: {
__dismiss: function __dismiss () {
var this$1 = this;
if (this.noBackdropDismiss) {
return
}
this.hide().then(function () {
this$1.$emit('dismiss');
});
},
__show: function __show () {
var this$1 = this;
var body = document.body;
body.appendChild(this.$el);
body.classList.add('with-modal');
EscapeKey.register(function () {
if (!this$1.noEscDismiss) {
this$1.hide().then(function () {
this$1.$emit('escape-key');
});
}
});
openedModalNumber++;
var content = this.$refs.content;
content.scrollTop = 0
;['modal-scroll', 'layout-view'].forEach(function (c) {
[].slice.call(content.getElementsByClassName(c)).forEach(function (el) {
el.scrollTop = 0;
});
});
},
__hide: function __hide () {
EscapeKey.pop();
openedModalNumber--;
if (openedModalNumber === 0) {
var body = document.body;
body.classList.remove('with-modal');
}
}
},
mounted: function mounted () {
if (this.value) {
this.show();
}
},
beforeDestroy: function beforeDestroy () {
if (this.$el.parentNode) {
this.$el.parentNode.removeChild(this.$el);
}
},
render: function render (h) {
var this$1 = this;
return h('transition', {
props: this.transitionProps,
on: {
afterEnter: function () {
this$1.showPromise && this$1.showPromiseResolve();
},
enterCancelled: function () {
this$1.showPromise && this$1.showPromiseReject();
},
afterLeave: function () {
this$1.hidePromise && this$1.hidePromiseResolve();
},
leaveCancelled: function () {
this$1.hidePromise && this$1.hidePromiseReject();
}
}
}, [
h('div', {
staticClass: 'modal fullscreen row',
'class': this.modalClasses,
on: {
click: this.__dismiss
},
directives: [{
name: 'show',
value: this.showing
}]
}, [
h('div', {
ref: 'content',
staticClass: 'modal-content scroll',
style: this.modalCss,
'class': this.contentClasses,
on: {
click: function click (e) {
e.stopPropagation();
},
touchstart: function touchstart (e) {
e.stopPropagation();
}
}
}, [ this.$slots.default ])
])
])
}
}
var QModalLayout = {
name: 'q-modal-layout',
props: {
headerStyle: [String, Object, Array],
headerClass: [String, Object, Array],
contentStyle: [String, Object, Array],
contentClass: [String, Object, Array],
footerStyle: [String, Object, Array],
footerClass: [String, Object, Array]
},
render: function render (h) {
var child = [];
if (this.$slots.header || ("mat" !== 'ios' && this.$slots.navigation)) {
child.push(h('div', {
staticClass: 'q-layout-header',
style: this.headerStyle,
'class': this.headerClass
}, [
this.$slots.header,
this.$slots.navigation
]));
}
child.push(h('div', {
staticClass: 'q-modal-layout-content col scroll',
style: this.contentStyle,
'class': this.contentClass
}, [
this.$slots.default
]));
if (this.$slots.footer || ("mat" === 'ios' && this.$slots.navigation)) {
child.push(h('div', {
staticClass: 'q-layout-footer',
style: this.footerStyle,
'class': this.footerClass
}, [
this.$slots.footer,
null
]));
}
return h('div', {
staticClass: 'q-modal-layout column absolute-full'
}, child)
}
}
var QIcon = {
name: 'q-icon',
props: {
name: String,
mat: String,
ios: String,
color: String,
size: String
},
computed: {
icon: function icon () {
return this.mat && "mat" === 'mat'
? this.mat
: (this.ios && "mat" === 'ios' ? this.ios : this.name)
},
classes: function classes () {
var cls;
var icon = this.icon;
if (!icon) {
cls = '';
}
else if (icon.startsWith('fa-')) {
// Fontawesome 4
cls = "fa " + icon;
}
else if (/^fa[s|r|l|b]{0,1} /.test(icon)) {
// Fontawesome 5
cls = icon;
}
else if (icon.startsWith('bt-')) {
cls = "bt " + icon;
}
else if (icon.startsWith('ion-') || icon.startsWith('icon-')) {
cls = "" + icon;
}
else if (icon.startsWith('mdi-')) {
cls = "mdi " + icon;
}
else {
cls = 'material-icons';
}
return this.color
? (cls + " text-" + (this.color))
: cls
},
content: function content () {
return this.classes.startsWith('material-icons')
? this.icon.replace(/ /g, '_')
: ' '
},
style: function style () {
if (this.size) {
return { fontSize: this.size }
}
}
},
render: function render (h) {
return h('i', {
staticClass: 'q-icon',
'class': this.classes,
style: this.style,
attrs: { 'aria-hidden': true }
}, [
this.content,
this.$slots.default
])
}
}
function textStyle (n) {
return n === void 0 || n < 2
? {}
: {overflow: 'hidden', display: '-webkit-box', '-webkit-box-orient': 'vertical', '-webkit-line-clamp': n}
}
function itemClasses (prop) {
return {
'q-item': true,
'q-item-division': true,
'relative-position': true,
'q-item-dark': prop.dark,
'q-item-dense': prop.dense,
'q-item-sparse': prop.sparse,
'q-item-separator': prop.separator,
'q-item-inset-separator': prop.insetSeparator,
'q-item-multiline': prop.multiline,
'q-item-highlight': prop.highlight,
'q-item-link': prop.to || prop.link
}
}
var ItemMixin = {
props: {
dark: Boolean,
dense: Boolean,
sparse: Boolean,
separator: Boolean,
insetSeparator: Boolean,
multiline: Boolean,
highlight: Boolean,
tag: {
type: String,
default: 'div'
}
}
};
var routerLinkEventName = 'qrouterlinkclick';
var evt = null;
if (!isSSR) {
try {
evt = new Event(routerLinkEventName);
}
catch (e) {
// IE doesn't support `new Event()`, so...`
evt = document.createEvent('Event');
evt.initEvent(routerLinkEventName, true, false);
}
}
var RouterLinkMixin = {
props: {
to: [String, Object],
exact: Boolean,
append: Boolean,
replace: Boolean
},
data: function data () {
return {
routerLinkEventName: routerLinkEventName
}
}
};
var QItem = {
name: 'q-item',
mixins: [
ItemMixin,
{ props: RouterLinkMixin.props }
],
props: {
active: Boolean,
link: Boolean
},
computed: {
classes: function classes () {
var cls = itemClasses(this.$props);
return this.to !== void 0
? cls
: [{active: this.active}, cls]
}
},
render: function render (h) {
return this.to !== void 0
? h('router-link', { props: this.$props, 'class': this.classes }, [ this.$slots.default ])
: h(this.tag, { 'class': this.classes }, [ this.$slots.default ])
}
}
var QItemSeparator = {
name: 'q-item-separator',
props: {
inset: Boolean
},
render: function render (h) {
return h('div', {
staticClass: 'q-item-separator-component',
'class': {
'q-item-separator-inset-component': this.inset
}
}, [
this.$slots.default
])
}
}
function text (h, name, val, n) {
n = parseInt(n, 10);
return h('div', {
staticClass: ("q-item-" + name + (n === 1 ? ' ellipsis' : '')),
style: textStyle(n)
}, [ val ])
}
var QItemMain = {
name: 'q-item-main',
props: {
label: String,
labelLines: [String, Number],
sublabel: String,
sublabelLines: [String, Number],
inset: Boolean,
tag: {
type: String,
default: 'div'
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-item-main q-item-section',
'class': {
'q-item-main-inset': this.inset
}
}, [
this.label ? text(h, 'label', this.label, this.labelLines) : null,
this.sublabel ? text(h, 'sublabel', this.sublabel, this.sublabelLines) : null,
this.$slots.default
])
}
}
var QItemSide = {
name: 'q-item-side',
props: {
right: Boolean,
icon: String,
letter: {
type: String,
validator: function (v) { return v.length === 1; }
},
inverted: Boolean, // for icon and letter only
avatar: String,
image: String,
stamp: String,
color: String,
textColor: String // only for inverted icon/letter
},
computed: {
type: function type () {
var this$1 = this;
return ['icon', 'image', 'avatar', 'letter', 'stamp'].find(function (type) { return this$1[type]; })
},
classes: function classes () {
var cls = [ ("q-item-side-" + (this.right ? 'right' : 'left')) ];
if (this.color && (!this.icon && !this.letter)) {
cls.push(("text-" + (this.color)));
}
return cls
},
typeClasses: function typeClasses () {
var cls = [ ("q-item-" + (this.type)) ];
if (this.color) {
if (this.inverted && (this.icon || this.letter)) {
cls.push(("bg-" + (this.color)));
}
else if (!this.textColor) {
cls.push(("text-" + (this.color)));
}
}
this.textColor && cls.push(("text-" + (this.textColor)));
if (this.inverted) {
this.icon && cls.push('q-item-icon-inverted');
this.letter && cls.push('q-item-letter-inverted');
}
return cls
},
imagePath: function imagePath () {
return this.image || this.avatar
}
},
render: function render (h) {
var child;
if (this.type) {
if (this.icon) {
child = h(QIcon, {
'class': this.typeClasses,
props: { name: this.icon }
}, [ this.$slots.default ]);
}
else if (this.imagePath) {
child = h('img', {
'class': this.typeClasses,
attrs: { src: this.imagePath }
});
}
else {
child = h('div', { 'class': this.typeClasses }, [ this.stamp || this.letter ]);
}
}
return h('div', {
staticClass: 'q-item-side q-item-section',
'class': this.classes
}, [
child,
this.$slots.default
])
}
}
var QItemTile = {
name: 'q-item-tile',
props: {
icon: String,
letter: Boolean,
inverted: Boolean, // for icon and letter only
image: Boolean,
avatar: Boolean,
stamp: Boolean,
label: Boolean,
sublabel: Boolean,
lines: [Number, String],
color: String,
textColor: String // only for inverted icon/letter
},
computed: {
hasLines: function hasLines () {
return (this.label || this.sublabel) && this.lines
},
type: function type () {
var this$1 = this;
return ['icon', 'label', 'sublabel', 'image', 'avatar', 'letter', 'stamp'].find(function (type) { return this$1[type]; })
},
classes: function classes () {
var cls = [];
if (this.color) {
if (this.inverted) {
cls.push(("bg-" + (this.color)));
}
else if (!this.textColor) {
cls.push(("text-" + (this.color)));
}
}
this.textColor && cls.push(("text-" + (this.textColor)));
this.type && cls.push(("q-item-" + (this.type)));
if (this.inverted) {
this.icon && cls.push('q-item-icon-inverted');
this.letter && cls.push('q-item-letter-inverted');
}
if (this.hasLines && (this.lines === '1' || this.lines === 1)) {
cls.push('ellipsis');
}
return cls
},
style: function style () {
if (this.hasLines) {
return textStyle(this.lines)
}
}
},
render: function render (h) {
var data = {
'class': this.classes,
style: this.style
};
if (this.icon) {
data.props = { name: this.icon };
}
return h(this.icon ? QIcon : 'div', data, [ this.$slots.default ])
}
}
function push (child, h, name, slot, replace, conf) {
var defaultProps = { props: { right: conf.right } };
if (slot && replace) {
child.push(h(name, defaultProps, slot));
return
}
var v = false;
for (var p in conf) {
if (conf.hasOwnProperty(p)) {
v = conf[p];
if (v !== void 0 && v !== true) {
child.push(h(name, { props: conf }));
break
}
}
}
slot && child.push(h(name, defaultProps, slot));
}
var QItemWrapper = {
name: 'q-item-wrapper',
props: {
cfg: {
type: Object,
default: function () { return ({}); }
},
slotReplace: Boolean
},
render: function render (h) {
var
cfg = this.cfg,
replace = this.slotReplace,
child = [];
push(child, h, QItemSide, this.$slots.left, replace, {
icon: cfg.icon,
color: cfg.leftColor,
avatar: cfg.avatar,
letter: cfg.letter,
image: cfg.image
});
push(child, h, QItemMain, this.$slots.main, replace, {
label: cfg.label,
sublabel: cfg.sublabel,
labelLines: cfg.labelLines,
sublabelLines: cfg.sublabelLines,
inset: cfg.inset
});
push(child, h, QItemSide, this.$slots.right, replace, {
right: true,
icon: cfg.rightIcon,
color: cfg.rightColor,
avatar: cfg.rightAvatar,
letter: cfg.rightLetter,
image: cfg.rightImage,
stamp: cfg.stamp
});
child.push(this.$slots.default);
return h(QItem, {
attrs: this.$attrs,
on: this.$listeners,
props: cfg
}, child)
}
}
var QList = {
name: 'q-list',
props: {
noBorder: Boolean,
dark: Boolean,
dense: Boolean,
sparse: Boolean,
striped: Boolean,
stripedOdd: Boolean,
separator: Boolean,
insetSeparator: Boolean,
multiline: Boolean,
highlight: Boolean,
link: Boolean
},
computed: {
classes: function classes () {
return {
'no-border': this.noBorder,
'q-list-dark': this.dark,
'q-list-dense': this.dense,
'q-list-sparse': this.sparse,
'q-list-striped': this.striped,
'q-list-striped-odd': this.stripedOdd,
'q-list-separator': this.separator,
'q-list-inset-separator': this.insetSeparator,
'q-list-multiline': this.multiline,
'q-list-highlight': this.highlight,
'q-list-link': this.link
}
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-list',
'class': this.classes
}, [
this.$slots.default
])
}
}
var QListHeader = {
name: 'q-list-header',
props: {
inset: Boolean
},
render: function render (h) {
return h('div', {
staticClass: 'q-list-header',
'class': {
'q-list-header-inset': this.inset
}
}, [
this.$slots.default
])
}
}
var QActionSheet = {
name: 'q-action-sheet',
props: {
value: Boolean,
title: String,
grid: Boolean,
actions: Array,
dismissLabel: String
},
computed: {
contentCss: function contentCss () {
}
},
render: function render (h) {
var this$1 = this;
var
child = [],
title = this.$slots.title || this.title;
if (title) {
child.push(
h('div', {
staticClass: 'q-actionsheet-title column justify-center'
}, [ title ])
);
}
child.push(
h(
'div',
{ staticClass: 'q-actionsheet-body scroll' },
this.actions
? [
this.grid
? h('div', { staticClass: 'q-actionsheet-grid row wrap items-center justify-between' }, this.__getActions(h))
: h(QList, { staticClass: 'no-border', props: { link: true } }, this.__getActions(h))
]
: [ this.$slots.default ]
)
);
return h(QModal, {
ref: 'modal',
props: {
value: this.value,
position: 'bottom',
contentCss: this.contentCss
},
on: {
input: function (val) {
this$1.$emit('input', val);
},
show: function () {
this$1.$emit('show');
},
hide: function () {
this$1.$emit('hide');
},
dismiss: function () {
this$1.__onCancel();
},
'escape-key': function () {
this$1.hide().then(function () {
this$1.$emit('escape-key');
this$1.__onCancel();
});
}
}
}, child)
},
methods: {
show: function show () {
return this.$refs.modal.show()
},
hide: function hide () {
return this.$refs.modal.hide()
},
__getActions: function __getActions (h) {
var this$1 = this;
var obj;
return this.actions.map(function (action) { return action.label
? h(this$1.grid ? 'div' : QItem, ( obj = {
staticClass: this$1.grid
? 'q-actionsheet-grid-item cursor-pointer relative-position column inline flex-center'
: null,
'class': action.classes,
attrs: {
tabindex: 0
}
}, obj[this$1.grid ? 'on' : 'nativeOn'] = {
click: function () { return this$1.__onOk(action); },
keydown: function () { return this$1.__onOk(action); }
}, obj), this$1.grid
? [
action.icon ? h(QIcon, { props: { name: action.icon, color: action.color } }) : null,
action.avatar ? h('img', { domProps: { src: action.avatar }, staticClass: 'avatar' }) : null,
h('span', [ action.label ])
]
: [
h(QItemSide, { props: { icon: action.icon, color: action.color, avatar: action.avatar } }),
h(QItemMain, { props: { inset: true, label: action.label } })
]
)
: h(QItemSeparator, { staticClass: 'col-12' }); }
)
},
__onOk: function __onOk (action) {
var this$1 = this;
this.hide().then(function () {
if (typeof action.handler === 'function') {
action.handler();
}
this$1.$emit('ok', action);
});
},
__onCancel: function __onCancel () {
var this$1 = this;
this.hide().then(function () {
this$1.$emit('cancel');
});
}
}
}
var units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB'];
function humanStorageSize (bytes) {
var u = 0;
while (Math.abs(bytes) >= 1024 && u < units.length - 1) {
bytes /= 1024;
++u;
}
return ((bytes.toFixed(1)) + " " + (units[u]))
}
function capitalize (str) {
return str.charAt(0).toUpperCase() + str.slice(1)
}
function between (v, min, max) {
if (max <= min) {
return min
}
return Math.min(max, Math.max(min, v))
}
function normalizeToInterval (v, min, max) {
if (max <= min) {
return min
}
var size = (max - min + 1);
var index = v % size;
if (index < min) {
index = size + index;
}
return index
}
function pad (v, length, char) {
if ( length === void 0 ) length = 2;
if ( char === void 0 ) char = '0';
var val = '' + v;
return val.length >= length
? val
: new Array(length - val.length + 1).join(char) + val
}
var format = Object.freeze({
humanStorageSize: humanStorageSize,
capitalize: capitalize,
between: between,
normalizeToInterval: normalizeToInterval,
pad: pad
});
var xhr = isSSR ? null : XMLHttpRequest;
var send = isSSR ? null : xhr.prototype.send;
function translate (ref) {
var p = ref.p;
var pos = ref.pos;
var active = ref.active;
var horiz = ref.horiz;
var reverse = ref.reverse;
var x = 1, y = 1;
if (horiz) {
if (reverse) { x = -1; }
if (pos === 'bottom') { y = -1; }
return cssTransform(("translate3d(" + (x * (p - 100)) + "%, " + (active ? 0 : y * -200) + "%, 0)"))
}
if (reverse) { y = -1; }
if (pos === 'right') { x = -1; }
return cssTransform(("translate3d(" + (active ? 0 : x * -200) + "%, " + (y * (p - 100)) + "%, 0)"))
}
function inc (p, amount) {
if (typeof amount !== 'number') {
if (p < 25) {
amount = Math.random() * (5 - 3 + 1) + 3;
}
else if (p < 65) {
amount = Math.random() * 3;
}
else if (p < 85) {
amount = Math.random() * 2;
}
else if (p < 99) {
amount = 0.5;
}
else {
amount = 0;
}
}
return between(p + amount, 0, 100)
}
function highjackAjax (startHandler, endHandler) {
xhr.prototype.send = function () {
var this$1 = this;
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
startHandler();
this.addEventListener('abort', endHandler, false);
this.addEventListener('readystatechange', function () {
if (this$1.readyState === 4) {
endHandler();
}
}, false);
send.apply(this, args);
};
}
function restoreAjax () {
xhr.prototype.send = send;
}
var QAjaxBar = {
name: 'q-ajax-bar',
props: {
position: {
type: String,
default: 'top',
validator: function validator (val) {
return ['top', 'right', 'bottom', 'left'].includes(val)
}
},
size: {
type: String,
default: '4px'
},
color: {
type: String,
default: 'red'
},
speed: {
type: Number,
default: 250
},
delay: {
type: Number,
default: 1000
},
reverse: Boolean
},
data: function data () {
return {
animate: false,
active: false,
progress: 0,
calls: 0
}
},
computed: {
classes: function classes () {
return [
this.position,
{ 'no-trantion': this.animate }
]
},
innerClasses: function innerClasses () {
return ("bg-" + (this.color))
},
style: function style$$1 () {
var o = translate({
p: this.progress,
pos: this.position,
active: this.active,
horiz: this.horizontal,
reverse: this.reverse
});
o[this.sizeProp] = this.size;
return o
},
horizontal: function horizontal () {
return this.position === 'top' || this.position === 'bottom'
},
sizeProp: function sizeProp () {
return this.horizontal ? 'height' : 'width'
}
},
methods: {
start: function start () {
var this$1 = this;
this.calls++;
if (!this.active) {
this.progress = 0;
this.active = true;
this.animate = false;
this.$emit('start');
this.timer = setTimeout(function () {
this$1.animate = true;
this$1.move();
}, this.delay);
}
else if (this.closing) {
this.closing = false;
clearTimeout(this.timer);
this.progress = 0;
this.move();
}
},
increment: function increment (amount) {
if (this.active) {
this.progress = inc(this.progress, amount);
}
},
stop: function stop () {
var this$1 = this;
this.calls = Math.max(0, this.calls - 1);
if (this.calls > 0) {
return
}
clearTimeout(this.timer);
if (!this.animate) {
this.active = false;
return
}
this.closing = true;
this.progress = 100;
this.$emit('stop');
this.timer = setTimeout(function () {
this$1.closing = false;
this$1.active = false;
}, 1050);
},
move: function move () {
var this$1 = this;
this.timer = setTimeout(function () {
this$1.increment();
this$1.move();
}, this.speed);
}
},
mounted: function mounted () {
highjackAjax(this.start, this.stop);
},
beforeDestroy: function beforeDestroy () {
if (!isSSR) {
clearTimeout(this.timer);
restoreAjax();
}
},
render: function render (h) {
if (isSSR) { return }
return h('div', {
staticClass: 'q-loading-bar shadow-4',
'class': this.classes,
style: this.style
}, [
h('div', {
staticClass: 'q-loading-bar-inner',
'class': this.innerClasses
})
])
}
}
function getEvent (e) {
return e || window.event
}
function rightClick (e) {
e = getEvent(e);
if (e.which) {
return e.which === 3
}
if (e.button) {
return e.button === 2
}
return false
}
function getEventKey (e) {
e = getEvent(e);
return e.which || e.keyCode
}
function position (e) {
var posx, posy;
e = getEvent(e);
if (e.touches && e.touches[0]) {
e = e.touches[0];
}
else if (e.changedTouches && e.changedTouches[0]) {
e = e.changedTouches[0];
}
if (e.clientX || e.clientY) {
posx = e.clientX;
posy = e.clientY;
}
else if (e.pageX || e.pageY) {
posx = e.pageX - document.body.scrollLeft - document.documentElement.scrollLeft;
posy = e.pageY - document.body.scrollTop - document.documentElement.scrollTop;
}
else {
var offset = targetElement(e).getBoundingClientRect();
posx = ((offset.right - offset.left) / 2) + offset.left;
posy = ((offset.bottom - offset.top) / 2) + offset.top;
}
return {
top: posy,
left: posx
}
}
function targetElement (e) {
var target;
e = getEvent(e);
if (e.target) {
target = e.target;
}
else if (e.srcElement) {
target = e.srcElement;
}
// defeat Safari bug
if (target.nodeType === 3) {
target = target.parentNode;
}
return target
}
// Reasonable defaults
var PIXEL_STEP = 10;
var LINE_HEIGHT = 40;
var PAGE_HEIGHT = 800;
function getMouseWheelDistance (e) {
var
sX = 0, sY = 0, // spinX, spinY
pX = 0, pY = 0; // pixelX, pixelY
// Legacy
if ('detail' in e) { sY = e.detail; }
if ('wheelDelta' in e) { sY = -e.wheelDelta / 120; }
if ('wheelDeltaY' in e) { sY = -e.wheelDeltaY / 120; }
if ('wheelDeltaX' in e) { sX = -e.wheelDeltaX / 120; }
// side scrolling on FF with DOMMouseScroll
if ('axis' in e && e.axis === e.HORIZONTAL_AXIS) {
sX = sY;
sY = 0;
}
pX = sX * PIXEL_STEP;
pY = sY * PIXEL_STEP;
if ('deltaY' in e) { pY = e.deltaY; }
if ('deltaX' in e) { pX = e.deltaX; }
if ((pX || pY) && e.deltaMode) {
if (e.deltaMode === 1) { // delta in LINE units
pX *= LINE_HEIGHT;
pY *= LINE_HEIGHT;
}
else { // delta in PAGE units
pX *= PAGE_HEIGHT;
pY *= PAGE_HEIGHT;
}
}
// Fall-back if spin cannot be determined
if (pX && !sX) { sX = (pX < 1) ? -1 : 1; }
if (pY && !sY) { sY = (pY < 1) ? -1 : 1; }
/*
* spinX -- normalized spin speed (use for zoom) - x plane
* spinY -- " - y plane
* pixelX -- normalized distance (to pixels) - x plane
* pixelY -- " - y plane
*/
return {
spinX: sX,
spinY: sY,
pixelX: pX,
pixelY: pY
}
}
function stopAndPrevent (e) {
if (!e) {
return
}
e.preventDefault();
e.stopPropagation();
}
var event = Object.freeze({
rightClick: rightClick,
getEventKey: getEventKey,
position: position,
targetElement: targetElement,
getMouseWheelDistance: getMouseWheelDistance,
stopAndPrevent: stopAndPrevent
});
function showRipple (evt, el, stopPropagation) {
if (stopPropagation) {
evt.stopPropagation();
}
var
container = document.createElement('span'),
animNode = document.createElement('span');
container.appendChild(animNode);
container.className = 'q-ripple-container';
var size = el.clientWidth > el.clientHeight ? el.clientWidth : el.clientHeight;
size = (size * 2) + "px";
animNode.className = 'q-ripple-animation';
css(animNode, { width: size, height: size });
el.appendChild(container);
var
offset$$1 = el.getBoundingClientRect(),
pos = position(evt),
x = pos.left - offset$$1.left,
y = pos.top - offset$$1.top;
animNode.classList.add('q-ripple-animation-enter', 'q-ripple-animation-visible');
css(animNode, cssTransform(("translate(-50%, -50%) translate(" + x + "px, " + y + "px) scale(.001)")));
setTimeout(function () {
animNode.classList.remove('q-ripple-animation-enter');
css(animNode, cssTransform(("translate(-50%, -50%) translate(" + x + "px, " + y + "px)")));
setTimeout(function () {
animNode.classList.remove('q-ripple-animation-visible');
setTimeout(function () {
animNode.parentNode.remove();
}, 300);
}, 400);
}, 25);
}
function shouldAbort (ref) {
var mat = ref.mat;
var ios = ref.ios;
return (
(mat && "mat" !== 'mat') ||
(ios && "mat" !== 'ios')
)
}
var Ripple = {
name: 'ripple',
inserted: function inserted (el, ref) {
var value = ref.value;
var modifiers = ref.modifiers;
if (shouldAbort(modifiers)) {
return
}
var ctx = {
enabled: value !== false,
click: function click (evt) {
if (ctx.enabled) {
showRipple(evt, el, modifiers.stop);
}
}
};
el.__qripple = ctx;
el.addEventListener('click', ctx.click, false);
},
update: function update (el, ref) {
var value = ref.value;
var oldValue = ref.oldValue;
if (el.__qripple && value !== oldValue) {
el.__qripple.enabled = value !== false;
}
},
unbind: function unbind (el, ref) {
var modifiers = ref.modifiers;
if (shouldAbort(modifiers)) {
return
}
el.removeEventListener('click', el.__qripple.click, false);
delete el.__qripple;
}
}
var alignMap = {
left: 'start',
center: 'center',
right: 'end',
between: 'between',
around: 'around'
};
var AlignMixin = {
props: {
align: {
type: String,
default: 'center',
validator: function (v) { return ['left', 'right', 'center', 'between', 'around'].includes(v); }
}
},
computed: {
alignClass: function alignClass () {
return ("justify-" + (alignMap[this.align]))
}
}
}
var sizes = {
xs: 8, sm: 10, md: 14, lg: 20, xl: 24
};
var BtnMixin = {
mixins: [AlignMixin],
components: {
QIcon: QIcon
},
directives: {
Ripple: Ripple
},
props: {
disable: Boolean,
label: [Number, String],
noCaps: Boolean,
noWrap: Boolean,
icon: String,
iconRight: String,
round: Boolean,
outline: Boolean,
flat: Boolean,
rounded: Boolean,
push: Boolean,
size: String,
fab: Boolean,
fabMini: Boolean,
color: String,
textColor: String,
glossy: Boolean,
dense: Boolean,
noRipple: Boolean,
tabindex: Number
},
computed: {
style: function style () {
if (this.size && !this.fab && !this.fabMini) {
return {
fontSize: this.size in sizes ? ((sizes[this.size]) + "px") : this.size
}
}
},
isRectangle: function isRectangle () {
return !this.isRound
},
isRound: function isRound () {
return this.round || this.fab || this.fabMini
},
shape: function shape () {
return ("q-btn-" + (this.isRound ? 'round' : 'rectangle'))
},
isDisabled: function isDisabled () {
return this.disable || this.loading
},
hasRipple: function hasRipple () {
return "mat" === 'mat' && !this.noRipple && !this.isDisabled
},
classes: function classes () {
var cls = [ this.shape ];
if (this.fab) {
cls.push('q-btn-fab');
}
else if (this.fabMini) {
cls.push('q-btn-fab-mini');
}
if (this.flat) {
cls.push('q-btn-flat');
}
else if (this.outline) {
cls.push('q-btn-outline');
}
else if (this.push) {
cls.push('q-btn-push');
}
if (this.isDisabled) {
cls.push('disabled');
}
else {
cls.push('q-focusable q-hoverable');
}
if (this.color) {
if (this.flat || this.outline) {
cls.push(("text-" + (this.textColor || this.color)));
}
else {
cls.push(("bg-" + (this.color)));
cls.push(("text-" + (this.textColor || 'white')));
}
}
else if (this.textColor) {
cls.push(("text-" + (this.textColor)));
}
cls.push({
'q-btn-no-uppercase': this.noCaps,
'q-btn-rounded': this.rounded,
'q-btn-dense': this.dense,
'glossy': this.glossy
});
return cls
},
innerClasses: function innerClasses () {
var classes = [ this.alignClass ];
if (this.noWrap) {
classes.push('no-wrap', 'text-no-wrap');
}
return classes
}
},
methods: {
removeFocus: function removeFocus (e) {
// if is touch enabled and focus was received from pointer
if (this.$q.platform.has.touch && e.detail) {
this.$el.blur();
}
}
}
}
var mixin = {
props: {
color: String,
size: {
type: [Number, String],
default: '1em'
}
},
computed: {
classes: function classes () {
if (this.color) {
return ("text-" + (this.color))
}
}
}
}
var DefaultSpinner = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner q-spinner-mat",class:_vm.classes,attrs:{"width":_vm.size,"height":_vm.size,"viewBox":"25 25 50 50"}},[_c('circle',{staticClass:"path",attrs:{"cx":"50","cy":"50","r":"20","fill":"none","stroke":"currentColor","stroke-width":"3","stroke-miterlimit":"10"}})])},staticRenderFns: [],
name: 'q-spinner-mat',
mixins: [mixin]
}
var audio = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"fill":"currentColor","width":_vm.size,"height":_vm.size,"viewBox":"0 0 55 80","xmlns":"http://www.w3.org/2000/svg"}},[_c('g',{attrs:{"transform":"matrix(1 0 0 -1 0 80)"}},[_c('rect',{attrs:{"width":"10","height":"20","rx":"3"}},[_c('animate',{attrs:{"attributeName":"height","begin":"0s","dur":"4.3s","values":"20;45;57;80;64;32;66;45;64;23;66;13;64;56;34;34;2;23;76;79;20","calcMode":"linear","repeatCount":"indefinite"}})]),_c('rect',{attrs:{"x":"15","width":"10","height":"80","rx":"3"}},[_c('animate',{attrs:{"attributeName":"height","begin":"0s","dur":"2s","values":"80;55;33;5;75;23;73;33;12;14;60;80","calcMode":"linear","repeatCount":"indefinite"}})]),_c('rect',{attrs:{"x":"30","width":"10","height":"50","rx":"3"}},[_c('animate',{attrs:{"attributeName":"height","begin":"0s","dur":"1.4s","values":"50;34;78;23;56;23;34;76;80;54;21;50","calcMode":"linear","repeatCount":"indefinite"}})]),_c('rect',{attrs:{"x":"45","width":"10","height":"30","rx":"3"}},[_c('animate',{attrs:{"attributeName":"height","begin":"0s","dur":"2s","values":"30;45;13;80;56;72;45;76;34;23;67;30","calcMode":"linear","repeatCount":"indefinite"}})])])])},staticRenderFns: [],
name: 'q-spinner-audio',
mixins: [mixin]
}
var ball = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"stroke":"currentColor","width":_vm.size,"height":_vm.size,"viewBox":"0 0 57 57","xmlns":"http://www.w3.org/2000/svg"}},[_c('g',{attrs:{"transform":"translate(1 1)","stroke-width":"2","fill":"none","fill-rule":"evenodd"}},[_c('circle',{attrs:{"cx":"5","cy":"50","r":"5"}},[_c('animate',{attrs:{"attributeName":"cy","begin":"0s","dur":"2.2s","values":"50;5;50;50","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"cx","begin":"0s","dur":"2.2s","values":"5;27;49;5","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"27","cy":"5","r":"5"}},[_c('animate',{attrs:{"attributeName":"cy","begin":"0s","dur":"2.2s","from":"5","to":"5","values":"5;50;50;5","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"cx","begin":"0s","dur":"2.2s","from":"27","to":"27","values":"27;49;5;27","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"49","cy":"50","r":"5"}},[_c('animate',{attrs:{"attributeName":"cy","begin":"0s","dur":"2.2s","values":"50;50;5;50","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"cx","from":"49","to":"49","begin":"0s","dur":"2.2s","values":"49;5;27;49","calcMode":"linear","repeatCount":"indefinite"}})])])])},staticRenderFns: [],
name: 'q-spinner-ball',
mixins: [mixin]
}
var bars = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"fill":"currentColor","width":_vm.size,"height":_vm.size,"viewBox":"0 0 135 140","xmlns":"http://www.w3.org/2000/svg"}},[_c('rect',{attrs:{"y":"10","width":"15","height":"120","rx":"6"}},[_c('animate',{attrs:{"attributeName":"height","begin":"0.5s","dur":"1s","values":"120;110;100;90;80;70;60;50;40;140;120","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"y","begin":"0.5s","dur":"1s","values":"10;15;20;25;30;35;40;45;50;0;10","calcMode":"linear","repeatCount":"indefinite"}})]),_c('rect',{attrs:{"x":"30","y":"10","width":"15","height":"120","rx":"6"}},[_c('animate',{attrs:{"attributeName":"height","begin":"0.25s","dur":"1s","values":"120;110;100;90;80;70;60;50;40;140;120","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"y","begin":"0.25s","dur":"1s","values":"10;15;20;25;30;35;40;45;50;0;10","calcMode":"linear","repeatCount":"indefinite"}})]),_c('rect',{attrs:{"x":"60","width":"15","height":"140","rx":"6"}},[_c('animate',{attrs:{"attributeName":"height","begin":"0s","dur":"1s","values":"120;110;100;90;80;70;60;50;40;140;120","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"y","begin":"0s","dur":"1s","values":"10;15;20;25;30;35;40;45;50;0;10","calcMode":"linear","repeatCount":"indefinite"}})]),_c('rect',{attrs:{"x":"90","y":"10","width":"15","height":"120","rx":"6"}},[_c('animate',{attrs:{"attributeName":"height","begin":"0.25s","dur":"1s","values":"120;110;100;90;80;70;60;50;40;140;120","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"y","begin":"0.25s","dur":"1s","values":"10;15;20;25;30;35;40;45;50;0;10","calcMode":"linear","repeatCount":"indefinite"}})]),_c('rect',{attrs:{"x":"120","y":"10","width":"15","height":"120","rx":"6"}},[_c('animate',{attrs:{"attributeName":"height","begin":"0.5s","dur":"1s","values":"120;110;100;90;80;70;60;50;40;140;120","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"y","begin":"0.5s","dur":"1s","values":"10;15;20;25;30;35;40;45;50;0;10","calcMode":"linear","repeatCount":"indefinite"}})])])},staticRenderFns: [],
name: 'q-spinner-bars',
mixins: [mixin]
}
var circles = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"fill":"currentColor","width":_vm.size,"height":_vm.size,"viewBox":"0 0 135 135","xmlns":"http://www.w3.org/2000/svg"}},[_c('path',{attrs:{"d":"M67.447 58c5.523 0 10-4.477 10-10s-4.477-10-10-10-10 4.477-10 10 4.477 10 10 10zm9.448 9.447c0 5.523 4.477 10 10 10 5.522 0 10-4.477 10-10s-4.478-10-10-10c-5.523 0-10 4.477-10 10zm-9.448 9.448c-5.523 0-10 4.477-10 10 0 5.522 4.477 10 10 10s10-4.478 10-10c0-5.523-4.477-10-10-10zM58 67.447c0-5.523-4.477-10-10-10s-10 4.477-10 10 4.477 10 10 10 10-4.477 10-10z"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"rotate","from":"0 67 67","to":"-360 67 67","dur":"2.5s","repeatCount":"indefinite"}})],1),_c('path',{attrs:{"d":"M28.19 40.31c6.627 0 12-5.374 12-12 0-6.628-5.373-12-12-12-6.628 0-12 5.372-12 12 0 6.626 5.372 12 12 12zm30.72-19.825c4.686 4.687 12.284 4.687 16.97 0 4.686-4.686 4.686-12.284 0-16.97-4.686-4.687-12.284-4.687-16.97 0-4.687 4.686-4.687 12.284 0 16.97zm35.74 7.705c0 6.627 5.37 12 12 12 6.626 0 12-5.373 12-12 0-6.628-5.374-12-12-12-6.63 0-12 5.372-12 12zm19.822 30.72c-4.686 4.686-4.686 12.284 0 16.97 4.687 4.686 12.285 4.686 16.97 0 4.687-4.686 4.687-12.284 0-16.97-4.685-4.687-12.283-4.687-16.97 0zm-7.704 35.74c-6.627 0-12 5.37-12 12 0 6.626 5.373 12 12 12s12-5.374 12-12c0-6.63-5.373-12-12-12zm-30.72 19.822c-4.686-4.686-12.284-4.686-16.97 0-4.686 4.687-4.686 12.285 0 16.97 4.686 4.687 12.284 4.687 16.97 0 4.687-4.685 4.687-12.283 0-16.97zm-35.74-7.704c0-6.627-5.372-12-12-12-6.626 0-12 5.373-12 12s5.374 12 12 12c6.628 0 12-5.373 12-12zm-19.823-30.72c4.687-4.686 4.687-12.284 0-16.97-4.686-4.686-12.284-4.686-16.97 0-4.687 4.686-4.687 12.284 0 16.97 4.686 4.687 12.284 4.687 16.97 0z"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"rotate","from":"0 67 67","to":"360 67 67","dur":"8s","repeatCount":"indefinite"}})],1)])},staticRenderFns: [],
name: 'q-spinner-circles',
mixins: [mixin]
}
var comment = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"width":_vm.size,"height":_vm.size,"xmlns":"http://www.w3.org/2000/svg","viewBox":"0 0 100 100","preserveAspectRatio":"xMidYMid"}},[_c('rect',{attrs:{"x":"0","y":"0","width":"100","height":"100","fill":"none"}}),_c('path',{attrs:{"d":"M78,19H22c-6.6,0-12,5.4-12,12v31c0,6.6,5.4,12,12,12h37.2c0.4,3,1.8,5.6,3.7,7.6c2.4,2.5,5.1,4.1,9.1,4 c-1.4-2.1-2-7.2-2-10.3c0-0.4,0-0.8,0-1.3h8c6.6,0,12-5.4,12-12V31C90,24.4,84.6,19,78,19z","fill":"currentColor"}}),_c('circle',{attrs:{"cx":"30","cy":"47","r":"5","fill":"#fff"}},[_c('animate',{attrs:{"attributeName":"opacity","from":"0","to":"1","values":"0;1;1","keyTimes":"0;0.2;1","dur":"1s","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"50","cy":"47","r":"5","fill":"#fff"}},[_c('animate',{attrs:{"attributeName":"opacity","from":"0","to":"1","values":"0;0;1;1","keyTimes":"0;0.2;0.4;1","dur":"1s","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"70","cy":"47","r":"5","fill":"#fff"}},[_c('animate',{attrs:{"attributeName":"opacity","from":"0","to":"1","values":"0;0;1;1","keyTimes":"0;0.4;0.6;1","dur":"1s","repeatCount":"indefinite"}})])])},staticRenderFns: [],
name: 'q-spinner-comment',
mixins: [mixin]
}
var cube = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"width":_vm.size,"height":_vm.size,"xmlns":"http://www.w3.org/2000/svg","viewBox":"0 0 100 100","preserveAspectRatio":"xMidYMid"}},[_c('rect',{attrs:{"x":"0","y":"0","width":"100","height":"100","fill":"none"}}),_c('g',{attrs:{"transform":"translate(25 25)"}},[_c('rect',{attrs:{"x":"-20","y":"-20","width":"40","height":"40","fill":"currentColor","opacity":"0.9"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"scale","from":"1.5","to":"1","repeatCount":"indefinite","begin":"0s","dur":"1s","calcMode":"spline","keySplines":"0.2 0.8 0.2 0.8","keyTimes":"0;1"}})],1)]),_c('g',{attrs:{"transform":"translate(75 25)"}},[_c('rect',{attrs:{"x":"-20","y":"-20","width":"40","height":"40","fill":"currentColor","opacity":"0.8"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"scale","from":"1.5","to":"1","repeatCount":"indefinite","begin":"0.1s","dur":"1s","calcMode":"spline","keySplines":"0.2 0.8 0.2 0.8","keyTimes":"0;1"}})],1)]),_c('g',{attrs:{"transform":"translate(25 75)"}},[_c('rect',{staticClass:"cube",attrs:{"x":"-20","y":"-20","width":"40","height":"40","fill":"currentColor","opacity":"0.7"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"scale","from":"1.5","to":"1","repeatCount":"indefinite","begin":"0.3s","dur":"1s","calcMode":"spline","keySplines":"0.2 0.8 0.2 0.8","keyTimes":"0;1"}})],1)]),_c('g',{attrs:{"transform":"translate(75 75)"}},[_c('rect',{staticClass:"cube",attrs:{"x":"-20","y":"-20","width":"40","height":"40","fill":"currentColor","opacity":"0.6"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"scale","from":"1.5","to":"1","repeatCount":"indefinite","begin":"0.2s","dur":"1s","calcMode":"spline","keySplines":"0.2 0.8 0.2 0.8","keyTimes":"0;1"}})],1)])])},staticRenderFns: [],
name: 'q-spinner-cube',
mixins: [mixin]
}
var dots = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"fill":"currentColor","width":_vm.size,"height":_vm.size,"viewBox":"0 0 120 30","xmlns":"http://www.w3.org/2000/svg"}},[_c('circle',{attrs:{"cx":"15","cy":"15","r":"15"}},[_c('animate',{attrs:{"attributeName":"r","from":"15","to":"15","begin":"0s","dur":"0.8s","values":"15;9;15","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"fill-opacity","from":"1","to":"1","begin":"0s","dur":"0.8s","values":"1;.5;1","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"60","cy":"15","r":"9","fill-opacity":".3"}},[_c('animate',{attrs:{"attributeName":"r","from":"9","to":"9","begin":"0s","dur":"0.8s","values":"9;15;9","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"fill-opacity","from":".5","to":".5","begin":"0s","dur":"0.8s","values":".5;1;.5","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"105","cy":"15","r":"15"}},[_c('animate',{attrs:{"attributeName":"r","from":"15","to":"15","begin":"0s","dur":"0.8s","values":"15;9;15","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"fill-opacity","from":"1","to":"1","begin":"0s","dur":"0.8s","values":"1;.5;1","calcMode":"linear","repeatCount":"indefinite"}})])])},staticRenderFns: [],
name: 'q-spinner-dots',
mixins: [mixin]
}
var facebook = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"width":_vm.size,"height":_vm.size,"viewBox":"0 0 100 100","xmlns":"http://www.w3.org/2000/svg","preserveAspectRatio":"xMidYMid"}},[_c('g',{attrs:{"transform":"translate(20 50)"}},[_c('rect',{attrs:{"x":"-10","y":"-30","width":"20","height":"60","fill":"currentColor","opacity":"0.6"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"scale","from":"2","to":"1","begin":"0s","repeatCount":"indefinite","dur":"1s","calcMode":"spline","keySplines":"0.1 0.9 0.4 1","keyTimes":"0;1","values":"2;1"}})],1)]),_c('g',{attrs:{"transform":"translate(50 50)"}},[_c('rect',{attrs:{"x":"-10","y":"-30","width":"20","height":"60","fill":"currentColor","opacity":"0.8"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"scale","from":"2","to":"1","begin":"0.1s","repeatCount":"indefinite","dur":"1s","calcMode":"spline","keySplines":"0.1 0.9 0.4 1","keyTimes":"0;1","values":"2;1"}})],1)]),_c('g',{attrs:{"transform":"translate(80 50)"}},[_c('rect',{attrs:{"x":"-10","y":"-30","width":"20","height":"60","fill":"currentColor","opacity":"0.9"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"scale","from":"2","to":"1","begin":"0.2s","repeatCount":"indefinite","dur":"1s","calcMode":"spline","keySplines":"0.1 0.9 0.4 1","keyTimes":"0;1","values":"2;1"}})],1)])])},staticRenderFns: [],
name: 'q-spinner-facebook',
mixins: [mixin]
}
var gears = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"width":_vm.size,"height":_vm.size,"viewBox":"0 0 100 100","preserveAspectRatio":"xMidYMid","xmlns":"http://www.w3.org/2000/svg"}},[_c('g',{attrs:{"transform":"translate(-20,-20)"}},[_c('path',{attrs:{"d":"M79.9,52.6C80,51.8,80,50.9,80,50s0-1.8-0.1-2.6l-5.1-0.4c-0.3-2.4-0.9-4.6-1.8-6.7l4.2-2.9c-0.7-1.6-1.6-3.1-2.6-4.5 L70,35c-1.4-1.9-3.1-3.5-4.9-4.9l2.2-4.6c-1.4-1-2.9-1.9-4.5-2.6L59.8,27c-2.1-0.9-4.4-1.5-6.7-1.8l-0.4-5.1C51.8,20,50.9,20,50,20 s-1.8,0-2.6,0.1l-0.4,5.1c-2.4,0.3-4.6,0.9-6.7,1.8l-2.9-4.1c-1.6,0.7-3.1,1.6-4.5,2.6l2.1,4.6c-1.9,1.4-3.5,3.1-5,4.9l-4.5-2.1 c-1,1.4-1.9,2.9-2.6,4.5l4.1,2.9c-0.9,2.1-1.5,4.4-1.8,6.8l-5,0.4C20,48.2,20,49.1,20,50s0,1.8,0.1,2.6l5,0.4 c0.3,2.4,0.9,4.7,1.8,6.8l-4.1,2.9c0.7,1.6,1.6,3.1,2.6,4.5l4.5-2.1c1.4,1.9,3.1,3.5,5,4.9l-2.1,4.6c1.4,1,2.9,1.9,4.5,2.6l2.9-4.1 c2.1,0.9,4.4,1.5,6.7,1.8l0.4,5.1C48.2,80,49.1,80,50,80s1.8,0,2.6-0.1l0.4-5.1c2.3-0.3,4.6-0.9,6.7-1.8l2.9,4.2 c1.6-0.7,3.1-1.6,4.5-2.6L65,69.9c1.9-1.4,3.5-3,4.9-4.9l4.6,2.2c1-1.4,1.9-2.9,2.6-4.5L73,59.8c0.9-2.1,1.5-4.4,1.8-6.7L79.9,52.6 z M50,65c-8.3,0-15-6.7-15-15c0-8.3,6.7-15,15-15s15,6.7,15,15C65,58.3,58.3,65,50,65z","fill":"currentColor"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"rotate","from":"90 50 50","to":"0 50 50","dur":"1s","repeatCount":"indefinite"}})],1)]),_c('g',{attrs:{"transform":"translate(20,20) rotate(15 50 50)"}},[_c('path',{attrs:{"d":"M79.9,52.6C80,51.8,80,50.9,80,50s0-1.8-0.1-2.6l-5.1-0.4c-0.3-2.4-0.9-4.6-1.8-6.7l4.2-2.9c-0.7-1.6-1.6-3.1-2.6-4.5 L70,35c-1.4-1.9-3.1-3.5-4.9-4.9l2.2-4.6c-1.4-1-2.9-1.9-4.5-2.6L59.8,27c-2.1-0.9-4.4-1.5-6.7-1.8l-0.4-5.1C51.8,20,50.9,20,50,20 s-1.8,0-2.6,0.1l-0.4,5.1c-2.4,0.3-4.6,0.9-6.7,1.8l-2.9-4.1c-1.6,0.7-3.1,1.6-4.5,2.6l2.1,4.6c-1.9,1.4-3.5,3.1-5,4.9l-4.5-2.1 c-1,1.4-1.9,2.9-2.6,4.5l4.1,2.9c-0.9,2.1-1.5,4.4-1.8,6.8l-5,0.4C20,48.2,20,49.1,20,50s0,1.8,0.1,2.6l5,0.4 c0.3,2.4,0.9,4.7,1.8,6.8l-4.1,2.9c0.7,1.6,1.6,3.1,2.6,4.5l4.5-2.1c1.4,1.9,3.1,3.5,5,4.9l-2.1,4.6c1.4,1,2.9,1.9,4.5,2.6l2.9-4.1 c2.1,0.9,4.4,1.5,6.7,1.8l0.4,5.1C48.2,80,49.1,80,50,80s1.8,0,2.6-0.1l0.4-5.1c2.3-0.3,4.6-0.9,6.7-1.8l2.9,4.2 c1.6-0.7,3.1-1.6,4.5-2.6L65,69.9c1.9-1.4,3.5-3,4.9-4.9l4.6,2.2c1-1.4,1.9-2.9,2.6-4.5L73,59.8c0.9-2.1,1.5-4.4,1.8-6.7L79.9,52.6 z M50,65c-8.3,0-15-6.7-15-15c0-8.3,6.7-15,15-15s15,6.7,15,15C65,58.3,58.3,65,50,65z","fill":"currentColor"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"rotate","from":"0 50 50","to":"90 50 50","dur":"1s","repeatCount":"indefinite"}})],1)])])},staticRenderFns: [],
name: 'q-spinner-gears',
mixins: [mixin]
}
var grid = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"fill":"currentColor","width":_vm.size,"height":_vm.size,"viewBox":"0 0 105 105","xmlns":"http://www.w3.org/2000/svg"}},[_c('circle',{attrs:{"cx":"12.5","cy":"12.5","r":"12.5"}},[_c('animate',{attrs:{"attributeName":"fill-opacity","begin":"0s","dur":"1s","values":"1;.2;1","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"12.5","cy":"52.5","r":"12.5","fill-opacity":".5"}},[_c('animate',{attrs:{"attributeName":"fill-opacity","begin":"100ms","dur":"1s","values":"1;.2;1","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"52.5","cy":"12.5","r":"12.5"}},[_c('animate',{attrs:{"attributeName":"fill-opacity","begin":"300ms","dur":"1s","values":"1;.2;1","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"52.5","cy":"52.5","r":"12.5"}},[_c('animate',{attrs:{"attributeName":"fill-opacity","begin":"600ms","dur":"1s","values":"1;.2;1","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"92.5","cy":"12.5","r":"12.5"}},[_c('animate',{attrs:{"attributeName":"fill-opacity","begin":"800ms","dur":"1s","values":"1;.2;1","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"92.5","cy":"52.5","r":"12.5"}},[_c('animate',{attrs:{"attributeName":"fill-opacity","begin":"400ms","dur":"1s","values":"1;.2;1","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"12.5","cy":"92.5","r":"12.5"}},[_c('animate',{attrs:{"attributeName":"fill-opacity","begin":"700ms","dur":"1s","values":"1;.2;1","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"52.5","cy":"92.5","r":"12.5"}},[_c('animate',{attrs:{"attributeName":"fill-opacity","begin":"500ms","dur":"1s","values":"1;.2;1","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"92.5","cy":"92.5","r":"12.5"}},[_c('animate',{attrs:{"attributeName":"fill-opacity","begin":"200ms","dur":"1s","values":"1;.2;1","calcMode":"linear","repeatCount":"indefinite"}})])])},staticRenderFns: [],
name: 'q-spinner-grid',
mixins: [mixin]
}
var hearts = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"fill":"currentColor","width":_vm.size,"height":_vm.size,"viewBox":"0 0 140 64","xmlns":"http://www.w3.org/2000/svg"}},[_c('path',{attrs:{"d":"M30.262 57.02L7.195 40.723c-5.84-3.976-7.56-12.06-3.842-18.063 3.715-6 11.467-7.65 17.306-3.68l4.52 3.76 2.6-5.274c3.716-6.002 11.47-7.65 17.304-3.68 5.84 3.97 7.56 12.054 3.842 18.062L34.49 56.118c-.897 1.512-2.793 1.915-4.228.9z","fill-opacity":".5"}},[_c('animate',{attrs:{"attributeName":"fill-opacity","begin":"0s","dur":"1.4s","values":"0.5;1;0.5","calcMode":"linear","repeatCount":"indefinite"}})]),_c('path',{attrs:{"d":"M105.512 56.12l-14.44-24.272c-3.716-6.008-1.996-14.093 3.843-18.062 5.835-3.97 13.588-2.322 17.306 3.68l2.6 5.274 4.52-3.76c5.84-3.97 13.593-2.32 17.308 3.68 3.718 6.003 1.998 14.088-3.842 18.064L109.74 57.02c-1.434 1.014-3.33.61-4.228-.9z","fill-opacity":".5"}},[_c('animate',{attrs:{"attributeName":"fill-opacity","begin":"0.7s","dur":"1.4s","values":"0.5;1;0.5","calcMode":"linear","repeatCount":"indefinite"}})]),_c('path',{attrs:{"d":"M67.408 57.834l-23.01-24.98c-5.864-6.15-5.864-16.108 0-22.248 5.86-6.14 15.37-6.14 21.234 0L70 16.168l4.368-5.562c5.863-6.14 15.375-6.14 21.235 0 5.863 6.14 5.863 16.098 0 22.247l-23.007 24.98c-1.43 1.556-3.757 1.556-5.188 0z"}})])},staticRenderFns: [],
name: 'q-spinner-hearts',
mixins: [mixin]
}
var hourglass = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"width":_vm.size,"height":_vm.size,"viewBox":"0 0 100 100","preserveAspectRatio":"xMidYMid","xmlns":"http://www.w3.org/2000/svg"}},[_c('g',[_c('path',{staticClass:"glass",attrs:{"fill":"none","stroke":"currentColor","stroke-width":"5","stroke-miterlimit":"10","d":"M58.4,51.7c-0.9-0.9-1.4-2-1.4-2.3s0.5-0.4,1.4-1.4 C70.8,43.8,79.8,30.5,80,15.5H70H30H20c0.2,15,9.2,28.1,21.6,32.3c0.9,0.9,1.4,1.2,1.4,1.5s-0.5,1.6-1.4,2.5 C29.2,56.1,20.2,69.5,20,85.5h10h40h10C79.8,69.5,70.8,55.9,58.4,51.7z"}}),_c('clipPath',{attrs:{"id":"uil-hourglass-clip1"}},[_c('rect',{staticClass:"clip",attrs:{"x":"15","y":"20","width":"70","height":"25"}},[_c('animate',{attrs:{"attributeName":"height","from":"25","to":"0","dur":"1s","repeatCount":"indefinite","vlaues":"25;0;0","keyTimes":"0;0.5;1"}}),_c('animate',{attrs:{"attributeName":"y","from":"20","to":"45","dur":"1s","repeatCount":"indefinite","vlaues":"20;45;45","keyTimes":"0;0.5;1"}})])]),_c('clipPath',{attrs:{"id":"uil-hourglass-clip2"}},[_c('rect',{staticClass:"clip",attrs:{"x":"15","y":"55","width":"70","height":"25"}},[_c('animate',{attrs:{"attributeName":"height","from":"0","to":"25","dur":"1s","repeatCount":"indefinite","vlaues":"0;25;25","keyTimes":"0;0.5;1"}}),_c('animate',{attrs:{"attributeName":"y","from":"80","to":"55","dur":"1s","repeatCount":"indefinite","vlaues":"80;55;55","keyTimes":"0;0.5;1"}})])]),_c('path',{staticClass:"sand",attrs:{"d":"M29,23c3.1,11.4,11.3,19.5,21,19.5S67.9,34.4,71,23H29z","clip-path":"url(#uil-hourglass-clip1)","fill":"currentColor"}}),_c('path',{staticClass:"sand",attrs:{"d":"M71.6,78c-3-11.6-11.5-20-21.5-20s-18.5,8.4-21.5,20H71.6z","clip-path":"url(#uil-hourglass-clip2)","fill":"currentColor"}}),_c('animateTransform',{attrs:{"attributeName":"transform","type":"rotate","from":"0 50 50","to":"180 50 50","repeatCount":"indefinite","dur":"1s","values":"0 50 50;0 50 50;180 50 50","keyTimes":"0;0.7;1"}})],1)])},staticRenderFns: [],
name: 'q-spinner-hourglass',
mixins: [mixin]
}
var infinity = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"width":_vm.size,"height":_vm.size,"viewBox":"0 0 100 100","preserveAspectRatio":"xMidYMid"}},[_c('path',{attrs:{"d":"M24.3,30C11.4,30,5,43.3,5,50s6.4,20,19.3,20c19.3,0,32.1-40,51.4-40C88.6,30,95,43.3,95,50s-6.4,20-19.3,20C56.4,70,43.6,30,24.3,30z","fill":"none","stroke":"currentColor","stroke-width":"8","stroke-dasharray":"10.691205342610678 10.691205342610678","stroke-dashoffset":"0"}},[_c('animate',{attrs:{"attributeName":"stroke-dashoffset","from":"0","to":"21.382410685221355","begin":"0","dur":"2s","repeatCount":"indefinite","fill":"freeze"}})])])},staticRenderFns: [],
name: 'q-spinner-infinity',
mixins: [mixin]
}
var QSpinner_ios = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"width":_vm.size,"height":_vm.size,"stroke":"currentColor","fill":"currentColor","viewBox":"0 0 64 64"}},[_c('g',{attrs:{"stroke-width":"4","stroke-linecap":"round"}},[_c('line',{attrs:{"y1":"17","y2":"29","transform":"translate(32,32) rotate(180)"}},[_c('animate',{attrs:{"attributeName":"stroke-opacity","dur":"750ms","values":"1;.85;.7;.65;.55;.45;.35;.25;.15;.1;0;1","repeatCount":"indefinite"}})]),_c('line',{attrs:{"y1":"17","y2":"29","transform":"translate(32,32) rotate(210)"}},[_c('animate',{attrs:{"attributeName":"stroke-opacity","dur":"750ms","values":"0;1;.85;.7;.65;.55;.45;.35;.25;.15;.1;0","repeatCount":"indefinite"}})]),_c('line',{attrs:{"y1":"17","y2":"29","transform":"translate(32,32) rotate(240)"}},[_c('animate',{attrs:{"attributeName":"stroke-opacity","dur":"750ms","values":".1;0;1;.85;.7;.65;.55;.45;.35;.25;.15;.1","repeatCount":"indefinite"}})]),_c('line',{attrs:{"y1":"17","y2":"29","transform":"translate(32,32) rotate(270)"}},[_c('animate',{attrs:{"attributeName":"stroke-opacity","dur":"750ms","values":".15;.1;0;1;.85;.7;.65;.55;.45;.35;.25;.15","repeatCount":"indefinite"}})]),_c('line',{attrs:{"y1":"17","y2":"29","transform":"translate(32,32) rotate(300)"}},[_c('animate',{attrs:{"attributeName":"stroke-opacity","dur":"750ms","values":".25;.15;.1;0;1;.85;.7;.65;.55;.45;.35;.25","repeatCount":"indefinite"}})]),_c('line',{attrs:{"y1":"17","y2":"29","transform":"translate(32,32) rotate(330)"}},[_c('animate',{attrs:{"attributeName":"stroke-opacity","dur":"750ms","values":".35;.25;.15;.1;0;1;.85;.7;.65;.55;.45;.35","repeatCount":"indefinite"}})]),_c('line',{attrs:{"y1":"17","y2":"29","transform":"translate(32,32) rotate(0)"}},[_c('animate',{attrs:{"attributeName":"stroke-opacity","dur":"750ms","values":".45;.35;.25;.15;.1;0;1;.85;.7;.65;.55;.45","repeatCount":"indefinite"}})]),_c('line',{attrs:{"y1":"17","y2":"29","transform":"translate(32,32) rotate(30)"}},[_c('animate',{attrs:{"attributeName":"stroke-opacity","dur":"750ms","values":".55;.45;.35;.25;.15;.1;0;1;.85;.7;.65;.55","repeatCount":"indefinite"}})]),_c('line',{attrs:{"y1":"17","y2":"29","transform":"translate(32,32) rotate(60)"}},[_c('animate',{attrs:{"attributeName":"stroke-opacity","dur":"750ms","values":".65;.55;.45;.35;.25;.15;.1;0;1;.85;.7;.65","repeatCount":"indefinite"}})]),_c('line',{attrs:{"y1":"17","y2":"29","transform":"translate(32,32) rotate(90)"}},[_c('animate',{attrs:{"attributeName":"stroke-opacity","dur":"750ms","values":".7;.65;.55;.45;.35;.25;.15;.1;0;1;.85;.7","repeatCount":"indefinite"}})]),_c('line',{attrs:{"y1":"17","y2":"29","transform":"translate(32,32) rotate(120)"}},[_c('animate',{attrs:{"attributeName":"stroke-opacity","dur":"750ms","values":".85;.7;.65;.55;.45;.35;.25;.15;.1;0;1;.85","repeatCount":"indefinite"}})]),_c('line',{attrs:{"y1":"17","y2":"29","transform":"translate(32,32) rotate(150)"}},[_c('animate',{attrs:{"attributeName":"stroke-opacity","dur":"750ms","values":"1;.85;.7;.65;.55;.45;.35;.25;.15;.1;0;1","repeatCount":"indefinite"}})])])])},staticRenderFns: [],
name: 'q-spinner-ios',
mixins: [mixin]
}
var oval = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"stroke":"currentColor","width":_vm.size,"height":_vm.size,"viewBox":"0 0 38 38","xmlns":"http://www.w3.org/2000/svg"}},[_c('g',{attrs:{"transform":"translate(1 1)","stroke-width":"2","fill":"none","fill-rule":"evenodd"}},[_c('circle',{attrs:{"stroke-opacity":".5","cx":"18","cy":"18","r":"18"}}),_c('path',{attrs:{"d":"M36 18c0-9.94-8.06-18-18-18"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"rotate","from":"0 18 18","to":"360 18 18","dur":"1s","repeatCount":"indefinite"}})],1)])])},staticRenderFns: [],
name: 'q-spinner-oval',
mixins: [mixin]
}
var pie = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"width":_vm.size,"height":_vm.size,"viewBox":"0 0 100 100","preserveAspectRatio":"xMidYMid","xmlns":"http://www.w3.org/2000/svg"}},[_c('path',{attrs:{"d":"M0 50A50 50 0 0 1 50 0L50 50L0 50","fill":"currentColor","opacity":"0.5"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"rotate","from":"0 50 50","to":"360 50 50","dur":"0.8s","repeatCount":"indefinite"}})],1),_c('path',{attrs:{"d":"M50 0A50 50 0 0 1 100 50L50 50L50 0","fill":"currentColor","opacity":"0.5"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"rotate","from":"0 50 50","to":"360 50 50","dur":"1.6s","repeatCount":"indefinite"}})],1),_c('path',{attrs:{"d":"M100 50A50 50 0 0 1 50 100L50 50L100 50","fill":"currentColor","opacity":"0.5"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"rotate","from":"0 50 50","to":"360 50 50","dur":"2.4s","repeatCount":"indefinite"}})],1),_c('path',{attrs:{"d":"M50 100A50 50 0 0 1 0 50L50 50L50 100","fill":"currentColor","opacity":"0.5"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"rotate","from":"0 50 50","to":"360 50 50","dur":"3.2s","repeatCount":"indefinite"}})],1)])},staticRenderFns: [],
name: 'q-spinner-pie',
mixins: [mixin]
}
var puff = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"stroke":"currentColor","width":_vm.size,"height":_vm.size,"viewBox":"0 0 44 44","xmlns":"http://www.w3.org/2000/svg"}},[_c('g',{attrs:{"fill":"none","fill-rule":"evenodd","stroke-width":"2"}},[_c('circle',{attrs:{"cx":"22","cy":"22","r":"1"}},[_c('animate',{attrs:{"attributeName":"r","begin":"0s","dur":"1.8s","values":"1; 20","calcMode":"spline","keyTimes":"0; 1","keySplines":"0.165, 0.84, 0.44, 1","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"stroke-opacity","begin":"0s","dur":"1.8s","values":"1; 0","calcMode":"spline","keyTimes":"0; 1","keySplines":"0.3, 0.61, 0.355, 1","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"22","cy":"22","r":"1"}},[_c('animate',{attrs:{"attributeName":"r","begin":"-0.9s","dur":"1.8s","values":"1; 20","calcMode":"spline","keyTimes":"0; 1","keySplines":"0.165, 0.84, 0.44, 1","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"stroke-opacity","begin":"-0.9s","dur":"1.8s","values":"1; 0","calcMode":"spline","keyTimes":"0; 1","keySplines":"0.3, 0.61, 0.355, 1","repeatCount":"indefinite"}})])])])},staticRenderFns: [],
name: 'q-spinner-puff',
mixins: [mixin]
}
var radio = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"width":_vm.size,"height":_vm.size,"viewBox":"0 0 100 100","preserveAspectRatio":"xMidYMid","xmlns":"http://www.w3.org/2000/svg"}},[_c('g',{attrs:{"transform":"scale(0.55)"}},[_c('circle',{attrs:{"cx":"30","cy":"150","r":"30","fill":"currentColor"}},[_c('animate',{attrs:{"attributeName":"opacity","from":"0","to":"1","dur":"1s","begin":"0","repeatCount":"indefinite","keyTimes":"0;0.5;1","values":"0;1;1"}})]),_c('path',{attrs:{"d":"M90,150h30c0-49.7-40.3-90-90-90v30C63.1,90,90,116.9,90,150z","fill":"currentColor"}},[_c('animate',{attrs:{"attributeName":"opacity","from":"0","to":"1","dur":"1s","begin":"0.1","repeatCount":"indefinite","keyTimes":"0;0.5;1","values":"0;1;1"}})]),_c('path',{attrs:{"d":"M150,150h30C180,67.2,112.8,0,30,0v30C96.3,30,150,83.7,150,150z","fill":"currentColor"}},[_c('animate',{attrs:{"attributeName":"opacity","from":"0","to":"1","dur":"1s","begin":"0.2","repeatCount":"indefinite","keyTimes":"0;0.5;1","values":"0;1;1"}})])])])},staticRenderFns: [],
name: 'q-spinner-radio',
mixins: [mixin]
}
var rings = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"stroke":"currentColor","width":_vm.size,"height":_vm.size,"viewBox":"0 0 45 45","xmlns":"http://www.w3.org/2000/svg"}},[_c('g',{attrs:{"fill":"none","fill-rule":"evenodd","transform":"translate(1 1)","stroke-width":"2"}},[_c('circle',{attrs:{"cx":"22","cy":"22","r":"6"}},[_c('animate',{attrs:{"attributeName":"r","begin":"1.5s","dur":"3s","values":"6;22","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"stroke-opacity","begin":"1.5s","dur":"3s","values":"1;0","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"stroke-width","begin":"1.5s","dur":"3s","values":"2;0","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"22","cy":"22","r":"6"}},[_c('animate',{attrs:{"attributeName":"r","begin":"3s","dur":"3s","values":"6;22","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"stroke-opacity","begin":"3s","dur":"3s","values":"1;0","calcMode":"linear","repeatCount":"indefinite"}}),_c('animate',{attrs:{"attributeName":"stroke-width","begin":"3s","dur":"3s","values":"2;0","calcMode":"linear","repeatCount":"indefinite"}})]),_c('circle',{attrs:{"cx":"22","cy":"22","r":"8"}},[_c('animate',{attrs:{"attributeName":"r","begin":"0s","dur":"1.5s","values":"6;1;2;3;4;5;6","calcMode":"linear","repeatCount":"indefinite"}})])])])},staticRenderFns: [],
name: 'q-spinner-rings',
mixins: [mixin]
}
var tail = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('svg',{staticClass:"q-spinner",class:_vm.classes,attrs:{"width":_vm.size,"height":_vm.size,"viewBox":"0 0 38 38","xmlns":"http://www.w3.org/2000/svg"}},[_c('defs',[_c('linearGradient',{attrs:{"x1":"8.042%","y1":"0%","x2":"65.682%","y2":"23.865%","id":"a"}},[_c('stop',{attrs:{"stop-color":"currentColor","stop-opacity":"0","offset":"0%"}}),_c('stop',{attrs:{"stop-color":"currentColor","stop-opacity":".631","offset":"63.146%"}}),_c('stop',{attrs:{"stop-color":"currentColor","offset":"100%"}})],1)],1),_c('g',{attrs:{"transform":"translate(1 1)","fill":"none","fill-rule":"evenodd"}},[_c('path',{attrs:{"d":"M36 18c0-9.94-8.06-18-18-18","stroke":"url(#a)","stroke-width":"2"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"rotate","from":"0 18 18","to":"360 18 18","dur":"0.9s","repeatCount":"indefinite"}})],1),_c('circle',{attrs:{"fill":"currentColor","cx":"36","cy":"18","r":"1"}},[_c('animateTransform',{attrs:{"attributeName":"transform","type":"rotate","from":"0 18 18","to":"360 18 18","dur":"0.9s","repeatCount":"indefinite"}})],1)])])},staticRenderFns: [],
name: 'q-spinner-tail',
mixins: [mixin]
}
var QSpinner = {
mixins: [DefaultSpinner],
name: 'q-spinner'
};
var QBtn = {
name: 'q-btn',
mixins: [BtnMixin],
props: {
value: Boolean,
loader: Boolean,
percentage: Number,
darkPercentage: Boolean,
waitForRipple: Boolean,
repeatTimeout: [Number, Function]
},
data: function data () {
return {
loading: this.value || false,
repeated: 0
}
},
watch: {
value: function value (val) {
if (this.loading !== val) {
this.loading = val;
}
}
},
computed: {
hasPercentage: function hasPercentage () {
return this.percentage !== void 0
},
width: function width () {
return ((between(this.percentage, 0, 100)) + "%")
},
hasNoRepeat: function hasNoRepeat () {
return this.isDisabled || !this.repeatTimeout || this.loader !== false
}
},
methods: {
click: function click (e) {
var this$1 = this;
clearTimeout(this.timer);
if (this.isDisabled || this.repeated) {
this.repeated = 0;
return
}
var trigger = function () {
this$1.removeFocus(e);
if (this$1.loader !== false || this$1.$slots.loading) {
this$1.loading = true;
this$1.$emit('input', true);
}
this$1.$emit('click', e, function () {
this$1.loading = false;
this$1.$emit('input', false);
});
};
if (this.waitForRipple && this.hasRipple) {
this.timer = setTimeout(trigger, 350);
}
else {
trigger();
}
},
startRepeat: function startRepeat (e) {
var this$1 = this;
this.repeated = 0;
var setTimer = function () {
this$1.timer = setTimeout(
trigger,
typeof this$1.repeatTimeout === 'function'
? this$1.repeatTimeout(this$1.repeated)
: this$1.repeatTimeout
);
};
var trigger = function () {
if (this$1.hasNoRepeat || this$1.$slots.loading) {
return
}
this$1.repeated += 1;
this$1.$emit('click', e);
setTimer();
};
setTimer();
},
endRepeat: function endRepeat () {
clearTimeout(this.timer);
}
},
beforeDestroy: function beforeDestroy () {
clearTimeout(this.timer);
},
render: function render (h) {
var on = this.hasNoRepeat || this.$slots.loading
? {}
: {
mousedown: this.startRepeat,
touchstart: this.startRepeat,
mouseup: this.endRepeat,
mouseleave: this.endRepeat,
touchend: this.endRepeat
};
on.click = this.click;
return h('button', {
staticClass: 'q-btn inline relative-position',
'class': this.classes,
style: this.style,
attrs: { tabindex: this.isDisabled ? -1 : this.tabindex || 0 },
on: on,
directives: this.hasRipple
? [{
name: 'ripple',
value: true
}]
: null
}, [
h('div', { staticClass: 'q-focus-helper' }),
this.loading && this.hasPercentage
? h('div', {
staticClass: 'q-btn-progress absolute-full',
'class': { 'q-btn-dark-progress': this.darkPercentage },
style: { width: this.width }
})
: null,
h('div', {
staticClass: 'q-btn-inner row col items-center',
'class': this.innerClasses
},
this.loading
? [ this.$slots.loading || h(QSpinner) ]
: [
this.icon
? h('q-icon', {
'class': { 'on-left': this.label && this.isRectangle },
props: { name: this.icon }
})
: null,
this.label && this.isRectangle ? h('div', [ this.label ]) : null,
this.$slots.default,
this.iconRight && this.isRectangle
? h('q-icon', {
staticClass: 'on-right',
props: { name: this.iconRight }
})
: null
]
)
])
}
}
var QBtnGroup = {
name: 'q-btn-group',
props: {
outline: Boolean,
flat: Boolean,
rounded: Boolean,
push: Boolean
},
computed: {
classes: function classes () {
var this$1 = this;
return ['outline', 'flat', 'rounded', 'push']
.filter(function (t) { return this$1[t]; })
.map(function (t) { return ("q-btn-group-" + t); }).join(' ')
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-btn-group row no-wrap inline',
'class': this.classes
}, [
this.$slots.default
])
}
}
function getAnchorPosition (el, offset) {
var ref = el.getBoundingClientRect();
var top = ref.top;
var left = ref.left;
var right = ref.right;
var bottom = ref.bottom;
var a = {
top: top,
left: left,
width: el.offsetWidth,
height: el.offsetHeight
};
if (offset) {
a.top -= offset[1];
a.left -= offset[0];
if (bottom) {
bottom += offset[1];
}
if (right) {
right += offset[0];
}
a.width += offset[0];
a.height += offset[1];
}
a.right = right || a.left + a.width;
a.bottom = bottom || a.top + a.height;
a.middle = a.left + ((a.right - a.left) / 2);
a.center = a.top + ((a.bottom - a.top) / 2);
return a
}
function getTargetPosition (el) {
return {
top: 0,
center: el.offsetHeight / 2,
bottom: el.offsetHeight,
left: 0,
middle: el.offsetWidth / 2,
right: el.offsetWidth
}
}
function getOverlapMode (anchor, target, median) {
if ([anchor, target].indexOf(median) >= 0) { return 'auto' }
if (anchor === target) { return 'inclusive' }
return 'exclusive'
}
function getPositions (anchor, target) {
var
a = extend({}, anchor),
t = extend({}, target);
var positions = {
x: ['left', 'right'].filter(function (p) { return p !== t.horizontal; }),
y: ['top', 'bottom'].filter(function (p) { return p !== t.vertical; })
};
var overlap = {
x: getOverlapMode(a.horizontal, t.horizontal, 'middle'),
y: getOverlapMode(a.vertical, t.vertical, 'center')
};
positions.x.splice(overlap.x === 'auto' ? 0 : 1, 0, 'middle');
positions.y.splice(overlap.y === 'auto' ? 0 : 1, 0, 'center');
if (overlap.y !== 'auto') {
a.vertical = a.vertical === 'top' ? 'bottom' : 'top';
if (overlap.y === 'inclusive') {
t.vertical = t.vertical;
}
}
if (overlap.x !== 'auto') {
a.horizontal = a.horizontal === 'left' ? 'right' : 'left';
if (overlap.y === 'inclusive') {
t.horizontal = t.horizontal;
}
}
return {
positions: positions,
anchorPos: a
}
}
function applyAutoPositionIfNeeded (anchor, target, selfOrigin, anchorOrigin, targetPosition) {
var ref = getPositions(anchorOrigin, selfOrigin);
var positions = ref.positions;
var anchorPos = ref.anchorPos;
if (targetPosition.top < 0 || targetPosition.top + target.bottom > window.innerHeight) {
var newTop = anchor[anchorPos.vertical] - target[positions.y[0]];
if (newTop + target.bottom <= window.innerHeight) {
targetPosition.top = newTop;
}
else {
newTop = anchor[anchorPos.vertical] - target[positions.y[1]];
if (newTop + target.bottom <= window.innerHeight) {
targetPosition.top = newTop;
}
}
}
if (targetPosition.left < 0 || targetPosition.left + target.right > window.innerWidth) {
var newLeft = anchor[anchorPos.horizontal] - target[positions.x[0]];
if (newLeft + target.right <= window.innerWidth) {
targetPosition.left = newLeft;
}
else {
newLeft = anchor[anchorPos.horizontal] - target[positions.x[1]];
if (newLeft + target.right <= window.innerWidth) {
targetPosition.left = newLeft;
}
}
}
return targetPosition
}
function parseHorizTransformOrigin (pos) {
return pos === 'middle' ? 'center' : pos
}
function getTransformProperties (ref) {
var selfOrigin = ref.selfOrigin;
var
vert = selfOrigin.vertical,
horiz = parseHorizTransformOrigin(selfOrigin.horizontal);
return {
'transform-origin': vert + ' ' + horiz + ' 0px'
}
}
function setPosition (ref) {
var el = ref.el;
var anchorEl = ref.anchorEl;
var anchorOrigin = ref.anchorOrigin;
var selfOrigin = ref.selfOrigin;
var maxHeight = ref.maxHeight;
var event = ref.event;
var anchorClick = ref.anchorClick;
var touchPosition = ref.touchPosition;
var offset = ref.offset;
var anchor;
el.style.maxHeight = maxHeight || '65vh';
if (event && (!anchorClick || touchPosition)) {
var ref$1 = position(event);
var top = ref$1.top;
var left = ref$1.left;
anchor = {top: top, left: left, width: 1, height: 1, right: left + 1, center: top, middle: left, bottom: top + 1};
}
else {
anchor = getAnchorPosition(anchorEl, offset);
}
var target = getTargetPosition(el);
var targetPosition = {
top: anchor[anchorOrigin.vertical] - target[selfOrigin.vertical],
left: anchor[anchorOrigin.horizontal] - target[selfOrigin.horizontal]
};
targetPosition = applyAutoPositionIfNeeded(anchor, target, selfOrigin, anchorOrigin, targetPosition);
el.style.top = Math.max(0, targetPosition.top) + 'px';
el.style.left = Math.max(0, targetPosition.left) + 'px';
}
function positionValidator (pos) {
var parts = pos.split(' ');
if (parts.length !== 2) {
return false
}
if (!['top', 'center', 'bottom'].includes(parts[0])) {
console.error('Anchor/Self position must start with one of top/center/bottom');
return false
}
if (!['left', 'middle', 'right'].includes(parts[1])) {
console.error('Anchor/Self position must end with one of left/middle/right');
return false
}
return true
}
function offsetValidator (val) {
if (!val) { return true }
if (val.length !== 2) { return false }
if (typeof val[0] !== 'number' || typeof val[1] !== 'number') {
return false
}
return true
}
function parsePosition (pos) {
var parts = pos.split(' ');
return {vertical: parts[0], horizontal: parts[1]}
}
function debounce (fn, wait, immediate) {
if ( wait === void 0 ) wait = 250;
var timeout;
function debounced () {
var this$1 = this;
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
var later = function () {
timeout = null;
if (!immediate) {
fn.apply(this$1, args);
}
};
clearTimeout(timeout);
if (immediate && !timeout) {
fn.apply(this, args);
}
timeout = setTimeout(later, wait);
}
debounced.cancel = function () {
clearTimeout(timeout);
};
return debounced
}
function frameDebounce (fn) {
var wait = false;
return function () {
var this$1 = this;
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
if (wait) { return }
wait = true;
window.requestAnimationFrame(function () {
fn.apply(this$1, args);
wait = false;
});
}
}
function getScrollTarget (el) {
return el.closest('.scroll') || window
}
function getScrollHeight (el) {
return (el === window ? document.body : el).scrollHeight
}
function getScrollPosition (scrollTarget) {
if (scrollTarget === window) {
return window.pageYOffset || window.scrollY || document.body.scrollTop || 0
}
return scrollTarget.scrollTop
}
function animScrollTo (el, to, duration) {
if (duration <= 0) {
return
}
var pos = getScrollPosition(el);
window.requestAnimationFrame(function () {
setScroll(el, pos + (to - pos) / duration * 16);
if (el.scrollTop !== to) {
animScrollTo(el, to, duration - 16);
}
});
}
function setScroll (scrollTarget, offset$$1) {
if (scrollTarget === window) {
document.documentElement.scrollTop = offset$$1;
document.body.scrollTop = offset$$1;
return
}
scrollTarget.scrollTop = offset$$1;
}
function setScrollPosition (scrollTarget, offset$$1, duration) {
if (duration) {
animScrollTo(scrollTarget, offset$$1, duration);
return
}
setScroll(scrollTarget, offset$$1);
}
var size;
function getScrollbarWidth () {
if (size !== undefined) {
return size
}
var
inner = document.createElement('p'),
outer = document.createElement('div');
css(inner, {
width: '100%',
height: '200px'
});
css(outer, {
position: 'absolute',
top: '0px',
left: '0px',
visibility: 'hidden',
width: '200px',
height: '150px',
overflow: 'hidden'
});
outer.appendChild(inner);
document.body.appendChild(outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
var w2 = inner.offsetWidth;
if (w1 === w2) {
w2 = outer.clientWidth;
}
document.body.removeChild(outer);
size = w1 - w2;
return size
}
var scroll = Object.freeze({
getScrollTarget: getScrollTarget,
getScrollHeight: getScrollHeight,
getScrollPosition: getScrollPosition,
animScrollTo: animScrollTo,
setScrollPosition: setScrollPosition,
getScrollbarWidth: getScrollbarWidth
});
var QPopover = {
name: 'q-popover',
mixins: [ModelToggleMixin],
props: {
anchor: {
type: String,
default: 'bottom left',
validator: positionValidator
},
self: {
type: String,
default: 'top left',
validator: positionValidator
},
fit: Boolean,
maxHeight: String,
touchPosition: Boolean,
anchorClick: {
/*
for handling anchor outside of Popover
example: context menu component
*/
type: Boolean,
default: true
},
offset: {
type: Array,
validator: offsetValidator
},
disable: Boolean
},
watch: {
$route: function $route () {
this.hide();
}
},
computed: {
transformCSS: function transformCSS () {
return getTransformProperties({selfOrigin: this.selfOrigin})
},
anchorOrigin: function anchorOrigin () {
return parsePosition(this.anchor)
},
selfOrigin: function selfOrigin () {
return parsePosition(this.self)
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-popover animate-scale',
style: this.transformCSS,
on: {
click: function click (e) { e.stopPropagation(); }
}
}, this.$slots.default)
},
created: function created () {
var this$1 = this;
this.__updatePosition = frameDebounce(function () { this$1.reposition(); });
},
mounted: function mounted () {
var this$1 = this;
this.$nextTick(function () {
this$1.anchorEl = this$1.$el.parentNode;
this$1.anchorEl.removeChild(this$1.$el);
if (this$1.anchorEl.classList.contains('q-btn-inner') || this$1.anchorEl.classList.contains('q-if-inner')) {
this$1.anchorEl = this$1.anchorEl.parentNode;
}
if (this$1.anchorClick) {
this$1.anchorEl.classList.add('cursor-pointer');
this$1.anchorEl.addEventListener('click', this$1.toggle);
}
});
if (this.value) {
this.show();
}
},
beforeDestroy: function beforeDestroy () {
if (this.anchorClick && this.anchorEl) {
this.anchorEl.removeEventListener('click', this.toggle);
}
},
methods: {
__show: function __show (evt) {
var this$1 = this;
document.body.appendChild(this.$el);
EscapeKey.register(function () { this$1.hide(); });
this.scrollTarget = getScrollTarget(this.anchorEl);
this.scrollTarget.addEventListener('scroll', this.__updatePosition);
window.addEventListener('resize', this.__updatePosition);
this.reposition(evt);
clearTimeout(this.timer);
this.timer = setTimeout(function () {
document.body.addEventListener('click', this$1.__bodyHide, true);
document.body.addEventListener('touchstart', this$1.__bodyHide, true);
this$1.showPromise && this$1.showPromiseResolve();
}, 0);
},
__bodyHide: function __bodyHide (evt) {
if (
evt && evt.target &&
(this.$el.contains(evt.target) || this.anchorEl.contains(evt.target))
) {
return
}
this.hide(evt);
},
__hide: function __hide () {
clearTimeout(this.timer);
document.body.removeEventListener('click', this.__bodyHide, true);
document.body.removeEventListener('touchstart', this.__bodyHide, true);
this.scrollTarget.removeEventListener('scroll', this.__updatePosition);
window.removeEventListener('resize', this.__updatePosition);
EscapeKey.pop();
document.body.removeChild(this.$el);
this.hidePromise && this.hidePromiseResolve();
},
reposition: function reposition (event) {
var this$1 = this;
this.$nextTick(function () {
if (this$1.fit) {
this$1.$el.style.minWidth = width(this$1.anchorEl) + 'px';
}
var ref = this$1.anchorEl.getBoundingClientRect();
var top = ref.top;
var ref$1 = viewport();
var height$$1 = ref$1.height;
if (top < 0 || top > height$$1) {
return this$1.hide()
}
setPosition({
event: event,
el: this$1.$el,
offset: this$1.offset,
anchorEl: this$1.anchorEl,
anchorOrigin: this$1.anchorOrigin,
selfOrigin: this$1.selfOrigin,
maxHeight: this$1.maxHeight,
anchorClick: this$1.anchorClick,
touchPosition: this$1.touchPosition
});
});
}
}
}
var QBtnDropdown = {
name: 'q-btn-dropdown',
mixins: [BtnMixin],
props: {
value: Boolean,
label: String,
split: Boolean
},
render: function render (h) {
var this$1 = this;
var
Popover = h(
QPopover,
{
ref: 'popover',
props: {
value: this.value,
disable: this.disable,
fit: true,
anchorClick: !this.split,
anchor: 'bottom right',
self: 'top right'
},
on: {
show: function (e) {
this$1.$emit('show', e);
this$1.$emit('input', true);
},
hide: function (e) {
this$1.$emit('hide', e);
this$1.$emit('input', false);
}
}
},
this.$slots.default
),
Icon = h(
'q-icon',
{
props: {
name: this.$q.icon.input.dropdown,
color: this.textColor
},
staticClass: 'transition-generic',
'class': {
'rotate-180': this.showing,
'on-right': !this.split,
'q-btn-dropdown-arrow': !this.split
}
}
),
child = [Popover];
var getBtn = function () {
return h(
QBtn,
{
props: {
disable: this$1.disable,
noCaps: this$1.noCaps,
noWrap: this$1.noWrap,
icon: this$1.icon,
label: this$1.label,
iconRight: this$1.split ? this$1.iconRight : null,
outline: this$1.outline,
flat: this$1.flat,
rounded: this$1.rounded,
push: this$1.push,
size: this$1.size,
color: this$1.color,
textColor: this$1.textColor,
glossy: this$1.glossy,
dense: this$1.dense,
noRipple: this$1.noRipple,
waitForRipple: this$1.waitForRipple
},
staticClass: ("" + (this$1.split ? 'q-btn-dropdown-current' : 'q-btn-dropdown q-btn-dropdown-simple')),
on: {
click: function (e) {
this$1.split && this$1.hide();
if (!this$1.disable) {
this$1.$emit('click', e);
}
}
}
},
this$1.split ? null : child
)
};
if (!this.split) {
child.push(Icon);
return getBtn()
}
return h(
QBtnGroup,
{
props: {
outline: this.outline,
flat: this.flat,
rounded: this.rounded,
push: this.push
},
staticClass: 'q-btn-dropdown q-btn-dropdown-split no-wrap'
},
[
getBtn(),
h(
QBtn,
{
props: {
disable: this.disable,
flat: this.flat,
rounded: this.rounded,
push: this.push,
size: this.size,
color: this.color,
dense: this.dense,
glossy: this.glossy,
noRipple: this.noRipple,
waitForRipple: this.waitForRipple
},
staticClass: 'q-btn-dropdown-arrow',
on: { click: function () { this$1.toggle(); } }
},
[ Icon ]
),
child
]
)
},
methods: {
toggle: function toggle () {
return this.$refs.popover.toggle()
},
show: function show () {
return this.$refs.popover.show()
},
hide: function hide () {
return this.$refs.popover.hide()
}
}
}
var QBtnToggle = {
name: 'q-btn-toggle',
props: {
value: {
required: true
},
// To avoid seeing the active raise shadow through the transparent button, give it a color (even white).
color: String,
textColor: String,
toggleColor: {
type: String,
default: 'primary'
},
textToggleColor: String,
options: {
type: Array,
required: true,
validator: function (v) { return v.every(function (opt) { return ('label' in opt || 'icon' in opt) && 'value' in opt; }); }
},
disable: Boolean,
noCaps: Boolean,
noWrap: Boolean,
outline: Boolean,
flat: Boolean,
dense: Boolean,
rounded: Boolean,
push: Boolean,
size: String,
glossy: Boolean,
noRipple: Boolean,
waitForRipple: Boolean
},
computed: {
val: function val () {
var this$1 = this;
return this.options.map(function (opt) { return opt.value === this$1.value; })
}
},
methods: {
set: function set (value, opt) {
var this$1 = this;
this.$emit('input', value, opt);
this.$nextTick(function () {
if (JSON.stringify(value) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', value, opt);
}
});
}
},
render: function render (h) {
var this$1 = this;
return h(QBtnGroup, {
staticClass: 'q-btn-toggle',
props: {
outline: this.outline,
flat: this.flat,
rounded: this.rounded,
push: this.push
}
},
this.options.map(
function (opt, i) { return h(QBtn, {
key: ("" + (opt.label) + (opt.icon) + (opt.iconRight)),
on: { click: function () { return this$1.set(opt.value, opt); } },
props: {
disable: this$1.disable,
label: opt.label,
// Colors come from the button specific options first, then from general props
color: this$1.val[i] ? opt.toggleColor || this$1.toggleColor : opt.color || this$1.color,
textColor: this$1.val[i] ? opt.textToggleColor || this$1.textToggleColor : opt.textColor || this$1.textColor,
icon: opt.icon,
iconRight: opt.iconRight,
noCaps: this$1.noCaps,
noWrap: this$1.noWrap,
outline: this$1.outline,
flat: this$1.flat,
rounded: this$1.rounded,
push: this$1.push,
glossy: this$1.glossy,
size: this$1.size,
dense: this$1.dense,
noRipple: this$1.noRipple,
waitForRipple: this$1.waitForRipple,
tabindex: opt.tabindex
}
}); }
))
}
}
var QAlert = {
name: 'q-alert',
props: {
type: {
type: String,
validator: function (v) { return ['positive', 'negative', 'warning', 'info'].includes(v); }
},
color: {
type: String,
default: 'negative'
},
textColor: String,
message: String,
detail: String,
icon: String,
avatar: String,
actions: Array
},
computed: {
computedIcon: function computedIcon () {
return this.icon
? this.icon
: this.$q.icon.type[this.type || this.color]
},
classes: function classes () {
return ("bg-" + (this.type || this.color) + " text-" + (this.textColor || 'white'))
}
},
render: function render (h) {
var this$1 = this;
var side = [];
if (this.avatar) {
side.push(
h('img', {
staticClass: 'avatar',
domProps: { src: this.avatar }
})
);
}
else if (this.icon || this.type) {
side.push(
h(QIcon, {
props: { name: this.computedIcon }
})
);
}
return h('div', [
h('div', {
staticClass: 'q-alert row no-wrap shadow-2',
'class': this.classes
}, [
side.length
? h('div', { staticClass: 'q-alert-side row col-auto flex-center' }, side)
: null,
h('div', {
staticClass: 'q-alert-content col self-center'
}, [
h('div', this.$slots.default || this.message),
this.detail ? h('div', { staticClass: 'q-alert-detail' }, [ this.detail ]) : null
]),
this.actions && this.actions.length
? h('div', {
staticClass: 'q-alert-actions col-auto gutter-xs flex-center'
},
this.actions.map(function (action) { return h('div', [
h(QBtn, {
staticClass: 'full-width',
props: {
flat: true,
dense: true,
icon: action.icon,
justify: 'start',
label: action.closeBtn === true
? (typeof action.label === 'string' ? action.label : this$1.$q.i18n.label.close)
: action.label
},
on: {
click: function () { return action.handler(); }
}
})
]); }
))
: null
])
])
}
}
function filter (terms, ref) {
var field = ref.field;
var list = ref.list;
var token = terms.toLowerCase();
return list.filter(function (item) { return ('' + item[field]).toLowerCase().startsWith(token); })
}
function s4 () {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1)
}
function uid () {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4()
}
var QAutocomplete = {
name: 'q-autocomplete',
props: {
minCharacters: {
type: Number,
default: 1
},
maxResults: {
type: Number,
default: 6
},
debounce: {
type: Number,
default: 500
},
filter: {
type: Function,
default: filter
},
staticData: Object,
separator: Boolean
},
inject: {
__input: {
default: function default$1 () {
console.error('QAutocomplete needs to be child of QInput or QSearch');
}
},
__inputDebounce: { default: null }
},
data: function data () {
return {
searchId: '',
results: [],
selectedIndex: -1,
width: 0,
enterKey: false,
timer: null
}
},
watch: {
'__input.val': function _input_val () {
if (this.enterKey) {
this.enterKey = false;
}
else {
this.__delayTrigger();
}
}
},
computed: {
computedResults: function computedResults () {
return this.maxResults && this.results.length > 0
? this.results.slice(0, this.maxResults)
: []
},
computedWidth: function computedWidth () {
return {minWidth: this.width}
},
searching: function searching () {
return this.searchId.length > 0
}
},
methods: {
isWorking: function isWorking () {
return this.$refs && this.$refs.popover
},
trigger: function trigger () {
var this$1 = this;
if (!this.__input.hasFocus() || !this.isWorking()) {
return
}
var terms = [null, void 0].includes(this.__input.val) ? '' : String(this.__input.val);
var searchId = uid();
this.searchId = searchId;
if (terms.length < this.minCharacters) {
this.searchId = '';
this.__clearSearch();
this.hide();
return
}
this.width = width(this.inputEl) + 'px';
if (this.staticData) {
this.searchId = '';
this.results = this.filter(terms, this.staticData);
var popover = this.$refs.popover;
if (this.results.length) {
this.selectedIndex = 0;
if (popover.showing) {
popover.reposition();
}
else {
popover.show();
}
}
else {
popover.hide();
}
return
}
this.__input.loading = true;
this.$emit('search', terms, function (results) {
if (!this$1.isWorking() || this$1.searchId !== searchId) {
return
}
this$1.__clearSearch();
if (Array.isArray(results) && results.length > 0) {
this$1.results = results;
this$1.selectedIndex = 0;
this$1.$refs.popover.show();
return
}
this$1.hide();
});
},
hide: function hide () {
this.results = [];
this.selectedIndex = -1;
return this.isWorking()
? this.$refs.popover.hide()
: Promise.resolve()
},
blurHide: function blurHide () {
var this$1 = this;
this.__clearSearch();
setTimeout(function () { return this$1.hide(); }, 300);
},
__clearSearch: function __clearSearch () {
clearTimeout(this.timer);
this.__input.loading = false;
this.searchId = '';
},
setValue: function setValue (result) {
var value = this.staticData ? result[this.staticData.field] : result.value;
var suffix = this.__inputDebounce ? 'Debounce' : '';
if (this.inputEl && this.__input && !this.__input.hasFocus()) {
this.inputEl.focus();
}
this.enterKey = this.__input && value !== this.__input.val;
this[("__input" + suffix)].set(value);
this.$emit('selected', result);
this.__clearSearch();
this.hide();
},
move: function move (offset$$1) {
this.selectedIndex = normalizeToInterval(
this.selectedIndex + offset$$1,
0,
this.computedResults.length - 1
);
},
setCurrentSelection: function setCurrentSelection () {
if (this.selectedIndex >= 0 && this.selectedIndex < this.results.length) {
this.setValue(this.results[this.selectedIndex]);
}
},
__delayTrigger: function __delayTrigger () {
this.__clearSearch();
if (!this.__input.hasFocus()) {
return
}
if (this.staticData) {
this.trigger();
return
}
this.timer = setTimeout(this.trigger, this.debounce);
},
__handleKeypress: function __handleKeypress (e) {
switch (e.keyCode || e.which) {
case 38: // up
this.__moveCursor(-1, e);
break
case 40: // down
this.__moveCursor(1, e);
break
case 13: // enter
this.setCurrentSelection();
stopAndPrevent(e);
break
case 27: // escape
this.__clearSearch();
break
case 9: // tab
this.hide();
break
}
},
__moveCursor: function __moveCursor (offset$$1, e) {
stopAndPrevent(e);
if (!this.$refs.popover.showing) {
this.trigger();
}
else {
this.move(offset$$1);
}
}
},
mounted: function mounted () {
var this$1 = this;
this.__input.register();
if (this.__inputDebounce) {
this.__inputDebounce.setChildDebounce(true);
}
this.$nextTick(function () {
this$1.inputEl = this$1.__input.getEl();
this$1.inputEl.addEventListener('keydown', this$1.__handleKeypress);
this$1.inputEl.addEventListener('blur', this$1.blurHide);
});
},
beforeDestroy: function beforeDestroy () {
this.__clearSearch();
this.__input.unregister();
if (this.__inputDebounce) {
this.__inputDebounce.setChildDebounce(false);
}
if (this.inputEl) {
this.inputEl.removeEventListener('keydown', this.__handleKeypress);
this.inputEl.removeEventListener('blur', this.blurHide);
this.hide();
}
},
render: function render (h) {
var this$1 = this;
return h(QPopover, {
ref: 'popover',
props: {
fit: true,
offset: [0, 10],
anchorClick: false
},
on: {
show: function () { return this$1.$emit('show'); },
hide: function () { return this$1.$emit('hide'); }
}
}, [
h(QList, {
props: {
noBorder: true,
separator: this.separator
},
style: this.computedWidth
},
this.computedResults.map(function (result, index) { return h(QItemWrapper, {
key: result.id || JSON.stringify(result),
'class': {
active: this$1.selectedIndex === index,
'cursor-pointer': !result.disable
},
props: { cfg: result },
nativeOn: {
mouseenter: function () { !result.disable && (this$1.selectedIndex = index); },
click: function () { !result.disable && this$1.setValue(result); }
}
}); }))
])
}
}
var QBreadcrumbs = {
name: 'q-breadcrumbs',
mixins: [AlignMixin],
props: {
color: {
type: String,
default: 'faded'
},
activeColor: {
type: String,
default: 'primary'
},
separator: {
type: String,
default: '/'
},
align: {
default: 'left'
}
},
computed: {
classes: function classes () {
return [("text-" + (this.color)), this.alignClass]
}
},
render: function render (h) {
var this$1 = this;
var
child = [],
length = this.$slots.default.length - 1,
separator = this.$scopedSlots.separator || (function () { return this$1.separator; }),
color = "text-" + (this.color),
active = "text-" + (this.activeColor);
this.$slots.default.forEach(function (comp, i) {
if (comp.componentOptions && comp.componentOptions.tag === 'q-breadcrumbs-el') {
var middle = i < length;
child.push(h('div', {
'class': [ middle ? active : color, middle ? 'text-weight-bold' : 'q-breadcrumbs-last' ]
}, [ comp ]));
if (middle) {
child.push(h('div', { staticClass: "q-breadcrumbs-separator", 'class': color }, [ separator() ]));
}
}
else {
child.push(comp);
}
});
return h('div', {
staticClass: 'q-breadcrumbs flex gutter-xs items-center overflow-hidden',
'class': this.classes
}, child)
}
}
var QBreadcrumbsEl = {
name: 'q-breadcrumbs-el',
mixins: [{ props: RouterLinkMixin.props }],
props: {
label: String,
icon: String,
color: String,
noRipple: Boolean
},
computed: {
link: function link () {
return this.to !== void 0
}
},
render: function render (h) {
return h(this.link ? 'router-link' : 'span', {
staticClass: 'q-breadcrumbs-el flex inline items-center relative-position',
props: this.link
? {
to: this.to,
exact: this.exact,
append: this.append,
replace: this.replace
}
: null
},
this.label || this.icon
? [
this.icon ? h(QIcon, { staticClass: 'q-breacrumbs-el-icon q-mr-sm', props: { name: this.icon } }) : null,
this.label
]
: [ this.$slots.default ]
)
}
}
var QCard = {
name: 'q-card',
props: {
square: Boolean,
flat: Boolean,
inline: Boolean,
color: String,
textColor: String
},
computed: {
classes: function classes () {
var cls = [{
'no-border-radius': this.square,
'no-shadow': this.flat,
'inline-block': this.inline
}];
if (this.color) {
cls.push(("bg-" + (this.color)));
cls.push("q-card-dark");
cls.push(("text-" + (this.textColor || 'white')));
}
else if (this.textColor) {
cls.push(("text-" + (this.textColor)));
}
return cls
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-card',
'class': this.classes
}, [
this.$slots.default
])
}
}
var QCardTitle = {
name: 'q-card-title',
render: function render (h) {
return h('div', {
staticClass: 'q-card-primary q-card-container row no-wrap'
}, [
h('div', {staticClass: 'col column'}, [
h('div', {staticClass: 'q-card-title'}, [ this.$slots.default ]),
h('div', {staticClass: 'q-card-subtitle'}, [ this.$slots.subtitle ])
]),
h('div', {staticClass: 'col-auto self-center q-card-title-extra'}, [ this.$slots.right ])
])
}
}
var QCardMain = {
name: 'q-card-main',
render: function render (h) {
return h('div', {
staticClass: 'q-card-main q-card-container'
}, [
this.$slots.default
])
}
}
var QCardActions = {
name: 'q-card-actions',
props: {
vertical: Boolean,
align: {
type: String,
default: 'start',
validator: function (v) { return ['start', 'center', 'end', 'around', 'between'].includes(v); }
}
},
computed: {
classes: function classes () {
return "q-card-actions-" + (this.vertical ? 'vert column justify-start' : 'horiz row') + " " +
(this.vertical ? 'items' : 'justify') + "-" + (this.align)
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-card-actions',
'class': this.classes
}, [
this.$slots.default
])
}
}
var QCardMedia = {
name: 'q-card-media',
props: {
overlayPosition: {
type: String,
default: 'bottom',
validator: function (v) { return ['top', 'bottom', 'full'].includes(v); }
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-card-media relative-position'
}, [
this.$slots.default,
this.$slots.overlay
? h('div', {
staticClass: 'q-card-media-overlay',
'class': ("absolute-" + (this.overlayPosition))
}, [
this.$slots.overlay
])
: null
])
}
}
var QCardSeparator = {
name: 'q-card-separator',
props: {
inset: Boolean
},
render: function render (h) {
return h('div', {
staticClass: 'q-card-separator',
'class': { inset: this.inset }
}, [
this.$slots.default
])
}
}
function getDirection (mod) {
if (Object.keys(mod).length === 0) {
return {
horizontal: true,
vertical: true
}
}
var dir = {};['horizontal', 'vertical'].forEach(function (direction) {
if (mod[direction]) {
dir[direction] = true;
}
});
return dir
}
function updateClasses (el, dir, scroll) {
el.classList.add('q-touch');
if (!scroll) {
if (dir.horizontal && !dir.vertical) {
el.classList.add('q-touch-y');
el.classList.remove('q-touch-x');
}
else if (!dir.horizontal && dir.vertical) {
el.classList.add('q-touch-x');
el.classList.remove('q-touch-y');
}
}
}
function processChanges (evt, ctx, isFinal) {
var
direction,
pos = position(evt),
distX = pos.left - ctx.event.x,
distY = pos.top - ctx.event.y,
absDistX = Math.abs(distX),
absDistY = Math.abs(distY);
if (ctx.direction.horizontal && !ctx.direction.vertical) {
direction = distX < 0 ? 'left' : 'right';
}
else if (!ctx.direction.horizontal && ctx.direction.vertical) {
direction = distY < 0 ? 'up' : 'down';
}
else if (absDistX >= absDistY) {
direction = distX < 0 ? 'left' : 'right';
}
else {
direction = distY < 0 ? 'up' : 'down';
}
return {
evt: evt,
position: pos,
direction: direction,
isFirst: ctx.event.isFirst,
isFinal: Boolean(isFinal),
duration: new Date().getTime() - ctx.event.time,
distance: {
x: absDistX,
y: absDistY
},
delta: {
x: pos.left - ctx.event.lastX,
y: pos.top - ctx.event.lastY
}
}
}
function shouldTrigger (ctx, changes) {
if (ctx.direction.horizontal && ctx.direction.vertical) {
return true
}
if (ctx.direction.horizontal && !ctx.direction.vertical) {
return Math.abs(changes.delta.x) > 0
}
if (!ctx.direction.horizontal && ctx.direction.vertical) {
return Math.abs(changes.delta.y) > 0
}
}
var TouchPan = {
name: 'touch-pan',
bind: function bind (el, binding) {
var mouse = !binding.modifiers.nomouse;
var ctx = {
handler: binding.value,
scroll: binding.modifiers.scroll,
direction: getDirection(binding.modifiers),
mouseStart: function mouseStart (evt) {
if (mouse) {
document.addEventListener('mousemove', ctx.mouseMove);
document.addEventListener('mouseup', ctx.mouseEnd);
}
ctx.start(evt);
},
start: function start (evt) {
var pos = position(evt);
ctx.event = {
x: pos.left,
y: pos.top,
time: new Date().getTime(),
detected: false,
prevent: ctx.direction.horizontal && ctx.direction.vertical,
isFirst: true,
lastX: pos.left,
lastY: pos.top
};
},
mouseMove: function mouseMove (evt) {
ctx.event.prevent = true;
ctx.move(evt);
},
move: function move (evt) {
if (ctx.event.prevent) {
if (!ctx.scroll) {
evt.preventDefault();
}
var changes = processChanges(evt, ctx, false);
if (shouldTrigger(ctx, changes)) {
ctx.handler(changes);
ctx.event.lastX = changes.position.left;
ctx.event.lastY = changes.position.top;
ctx.event.isFirst = false;
}
return
}
if (ctx.event.detected) {
return
}
ctx.event.detected = true;
var
pos = position(evt),
distX = pos.left - ctx.event.x,
distY = pos.top - ctx.event.y;
if (ctx.direction.horizontal && !ctx.direction.vertical) {
if (Math.abs(distX) > Math.abs(distY)) {
evt.preventDefault();
ctx.event.prevent = true;
}
}
else if (Math.abs(distX) < Math.abs(distY)) {
ctx.event.prevent = true;
}
},
mouseEnd: function mouseEnd (evt) {
if (mouse) {
document.removeEventListener('mousemove', ctx.mouseMove);
document.removeEventListener('mouseup', ctx.mouseEnd);
}
ctx.end(evt);
},
end: function end (evt) {
if (!ctx.event.prevent || ctx.event.isFirst) {
return
}
ctx.handler(processChanges(evt, ctx, true));
}
};
el.__qtouchpan = ctx;
updateClasses(el, ctx.direction, ctx.scroll);
if (mouse) {
el.addEventListener('mousedown', ctx.mouseStart);
}
el.addEventListener('touchstart', ctx.start);
el.addEventListener('touchmove', ctx.move);
el.addEventListener('touchend', ctx.end);
},
update: function update (el, binding) {
if (binding.oldValue !== binding.value) {
el.__qtouchpan.handler = binding.value;
}
},
unbind: function unbind (el, binding) {
var ctx = el.__qtouchpan;
el.removeEventListener('touchstart', ctx.start);
el.removeEventListener('mousedown', ctx.mouseStart);
el.removeEventListener('touchmove', ctx.move);
el.removeEventListener('touchend', ctx.end);
delete el.__qtouchpan;
}
}
function isDate (v) {
return Object.prototype.toString.call(v) === '[object Date]'
}
function isNumber (v) {
return typeof v === 'number' && isFinite(v)
}
var linear = function (t) { return t; };
var easeInQuad = function (t) { return t * t; };
var easeOutQuad = function (t) { return t * (2 - t); };
var easeInOutQuad = function (t) { return t < 0.5
? 2 * t * t
: -1 + (4 - 2 * t) * t; };
var easeInCubic = function (t) { return Math.pow( t, 3 ); };
var easeOutCubic = function (t) { return 1 + Math.pow( (t - 1), 3 ); };
var easeInOutCubic = function (t) { return t < 0.5
? 4 * Math.pow( t, 3 )
: 1 + (t - 1) * Math.pow( (2 * t - 2), 2 ); };
var easeInQuart = function (t) { return Math.pow( t, 4 ); };
var easeOutQuart = function (t) { return 1 - Math.pow( (t - 1), 4 ); };
var easeInOutQuart = function (t) { return t < 0.5
? 8 * Math.pow( t, 4 )
: 1 - 8 * Math.pow( (t - 1), 4 ); };
var easeInQuint = function (t) { return Math.pow( t, 5 ); };
var easeOutQuint = function (t) { return 1 + Math.pow( (t - 1), 5 ); };
var easeInOutQuint = function (t) { return t < 0.5
? 16 * Math.pow( t, 5 )
: 1 + 16 * Math.pow( (t - 1), 5 ); };
var easeInCirc = function (t) { return -1 * Math.sqrt(1 - Math.pow( t, 2 )) + 1; };
var easeOutCirc = function (t) { return Math.sqrt(-1 * (t - 2) * t); };
var easeInOutCirc = function (t) { return t < 0.5
? 0.5 * (1 - Math.sqrt(1 - 4 * t * t))
: 0.5 * (1 + Math.sqrt(-3 + 8 * t - 4 * t * t)); };
var overshoot = function (t) { return -1 * (Math.pow( Math.E, (-6.3 * t) )) * (Math.cos(5 * t)) + 1; };
/* -- Material Design curves -- */
/**
* Faster ease in, slower ease out
*/
var standard = function (t) { return t < 0.4031
? 12 * Math.pow( t, 4 )
: 1 / 1290 * (11 * Math.sqrt(-40000 * t * t + 80000 * t - 23359) - 129); };
var decelerate = easeOutCubic;
var accelerate = easeInCubic;
var sharp = easeInOutQuad;
var easing = Object.freeze({
linear: linear,
easeInQuad: easeInQuad,
easeOutQuad: easeOutQuad,
easeInOutQuad: easeInOutQuad,
easeInCubic: easeInCubic,
easeOutCubic: easeOutCubic,
easeInOutCubic: easeInOutCubic,
easeInQuart: easeInQuart,
easeOutQuart: easeOutQuart,
easeInOutQuart: easeInOutQuart,
easeInQuint: easeInQuint,
easeOutQuint: easeOutQuint,
easeInOutQuint: easeInOutQuint,
easeInCirc: easeInCirc,
easeOutCirc: easeOutCirc,
easeInOutCirc: easeInOutCirc,
overshoot: overshoot,
standard: standard,
decelerate: decelerate,
accelerate: accelerate,
sharp: sharp
});
var ids = {};
function start (ref) {
var name = ref.name;
var duration = ref.duration; if ( duration === void 0 ) duration = 300;
var to = ref.to;
var from = ref.from;
var apply = ref.apply;
var done = ref.done;
var cancel = ref.cancel;
var easing = ref.easing;
var id = name;
var start = performance.now();
if (id) {
stop(id);
}
else {
id = uid();
}
var delta = easing || linear;
var handler = function () {
var progress = (performance.now() - start) / duration;
if (progress > 1) {
progress = 1;
}
var newPos = from + (to - from) * delta(progress);
apply(newPos, progress);
if (progress === 1) {
delete ids[id];
done && done(newPos);
return
}
anim.last = {
pos: newPos,
progress: progress
};
anim.timer = window.requestAnimationFrame(handler);
};
var anim = ids[id] = {
cancel: cancel,
timer: window.requestAnimationFrame(handler)
};
return id
}
function stop (id) {
if (!id) {
return
}
var anim = ids[id];
if (anim && anim.timer) {
cancelAnimationFrame(anim.timer);
anim.cancel && anim.cancel(anim.last);
delete ids[id];
}
}
var animate = Object.freeze({
start: start,
stop: stop
});
var FullscreenMixin = {
data: function data () {
return {
inFullscreen: false
}
},
watch: {
$route: function $route () {
this.exitFullscreen();
}
},
methods: {
toggleFullscreen: function toggleFullscreen () {
if (this.inFullscreen) {
this.exitFullscreen();
}
else {
this.setFullscreen();
}
},
setFullscreen: function setFullscreen () {
if (this.inFullscreen) {
return
}
this.inFullscreen = true;
this.container = this.$el.parentNode;
this.container.replaceChild(this.fullscreenFillerNode, this.$el);
document.body.appendChild(this.$el);
document.body.classList.add('with-mixin-fullscreen');
this.__historyFullscreen = {
handler: this.exitFullscreen
};
History.add(this.__historyFullscreen);
},
exitFullscreen: function exitFullscreen () {
if (!this.inFullscreen) {
return
}
if (this.__historyFullscreen) {
History.remove(this.__historyFullscreen);
this.__historyFullscreen = null;
}
this.container.replaceChild(this.$el, this.fullscreenFillerNode);
document.body.classList.remove('with-mixin-fullscreen');
this.inFullscreen = false;
}
},
created: function created () {
this.fullscreenFillerNode = document.createElement('span');
},
beforeDestroy: function beforeDestroy () {
this.exitFullscreen();
}
}
var QCarousel = {
name: 'q-carousel',
mixins: [FullscreenMixin],
directives: {
TouchPan: TouchPan
},
props: {
value: Number,
color: {
type: String,
default: 'primary'
},
height: String,
arrows: Boolean,
infinite: Boolean,
animation: {
type: [Number, Boolean],
default: true
},
easing: Function,
swipeEasing: Function,
noSwipe: Boolean,
autoplay: [Number, Boolean],
handleArrowKeys: Boolean,
quickNav: Boolean,
quickNavIcon: String
},
provide: function provide () {
return {
'carousel': this
}
},
data: function data () {
return {
position: 0,
slide: 0,
positionSlide: 0,
slidesNumber: 0,
animUid: false
}
},
watch: {
value: function value (v) {
if (v !== this.slide) {
this.goToSlide(v);
}
},
autoplay: function autoplay () {
this.__planAutoPlay();
},
infinite: function infinite () {
this.__planAutoPlay();
},
handleArrowKeys: function handleArrowKeys (v) {
this.__setArrowKeys(v);
}
},
computed: {
trackPosition: function trackPosition () {
return cssTransform(("translateX(" + (this.position) + "%)"))
},
infiniteLeft: function infiniteLeft () {
return this.infinite && this.slidesNumber > 1 && this.positionSlide < 0
},
infiniteRight: function infiniteRight () {
return this.infinite && this.slidesNumber > 1 && this.positionSlide >= this.slidesNumber
},
canGoToPrevious: function canGoToPrevious () {
return this.infinite ? this.slidesNumber > 1 : this.slide > 0
},
canGoToNext: function canGoToNext () {
return this.infinite ? this.slidesNumber > 1 : this.slide < this.slidesNumber - 1
},
computedStyle: function computedStyle () {
if (!this.inFullscreen && this.height) {
return ("height: " + (this.height))
}
},
slotScope: function slotScope () {
return {
slide: this.slide,
slidesNumber: this.slidesNumber,
percentage: this.slidesNumber < 2
? 100
: 100 * this.slide / (this.slidesNumber - 1),
goToSlide: this.goToSlide,
previous: this.previous,
next: this.next,
color: this.color,
inFullscreen: this.inFullscreen,
toggleFullscreen: this.toggleFullscreen,
canGoToNext: this.canGoToNext,
canGoToPrevious: this.canGoToPrevious
}
}
},
methods: {
previous: function previous () {
return this.canGoToPrevious
? this.goToSlide(this.slide - 1)
: Promise.resolve()
},
next: function next () {
return this.canGoToNext
? this.goToSlide(this.slide + 1)
: Promise.resolve()
},
goToSlide: function goToSlide (slide, fromSwipe) {
var this$1 = this;
if ( fromSwipe === void 0 ) fromSwipe = false;
return new Promise(function (resolve, reject) {
var
direction = '',
pos;
this$1.__cleanup();
var finish = function () {
this$1.$emit('input', this$1.slide);
this$1.$emit('slide-direction', direction);
this$1.__planAutoPlay();
resolve();
};
if (this$1.slidesNumber < 2) {
this$1.slide = 0;
this$1.positionSlide = 0;
pos = 0;
}
else {
if (!this$1.hasOwnProperty('initialPosition')) {
this$1.position = -this$1.slide * 100;
}
direction = slide > this$1.slide ? 'next' : 'previous';
if (this$1.infinite) {
this$1.slide = normalizeToInterval(slide, 0, this$1.slidesNumber - 1);
pos = normalizeToInterval(slide, -1, this$1.slidesNumber);
if (!fromSwipe) {
this$1.positionSlide = pos;
}
}
else {
this$1.slide = between(slide, 0, this$1.slidesNumber - 1);
this$1.positionSlide = this$1.slide;
pos = this$1.slide;
}
}
pos = pos * -100;
if (!this$1.animation) {
this$1.position = pos;
finish();
return
}
this$1.animationInProgress = true;
this$1.animUid = start({
from: this$1.position,
to: pos,
duration: isNumber(this$1.animation) ? this$1.animation : 300,
easing: fromSwipe
? this$1.swipeEasing || decelerate
: this$1.easing || standard,
apply: function (pos) {
this$1.position = pos;
},
done: function () {
if (this$1.infinite) {
this$1.position = -this$1.slide * 100;
this$1.positionSlide = this$1.slide;
}
this$1.animationInProgress = false;
finish();
}
});
})
},
stopAnimation: function stopAnimation () {
stop(this.animUid);
this.animationInProgress = false;
},
__pan: function __pan (event) {
var this$1 = this;
if (this.infinite && this.animationInProgress) {
return
}
if (event.isFirst) {
this.initialPosition = this.position;
this.__cleanup();
}
var delta = (event.direction === 'left' ? -1 : 1) * event.distance.x;
if (
(this.infinite && this.slidesNumber < 2) ||
(
!this.infinite &&
(
(this.slide === 0 && delta > 0) ||
(this.slide === this.slidesNumber - 1 && delta < 0)
)
)
) {
delta = delta / 10;
}
this.position = this.initialPosition + delta / this.$refs.track.offsetWidth * 100;
this.positionSlide = (event.direction === 'left' ? this.slide + 1 : this.slide - 1);
if (event.isFinal) {
this.goToSlide(
event.distance.x < 100
? this.slide
: this.positionSlide,
true
).then(function () {
delete this$1.initialPosition;
});
}
},
__planAutoPlay: function __planAutoPlay () {
var this$1 = this;
this.$nextTick(function () {
if (this$1.autoplay) {
clearTimeout(this$1.timer);
this$1.timer = setTimeout(
this$1.next,
isNumber(this$1.autoplay) ? this$1.autoplay : 5000
);
}
});
},
__cleanup: function __cleanup () {
this.stopAnimation();
clearTimeout(this.timer);
},
__handleArrowKey: function __handleArrowKey (e) {
var key = getEventKey(e);
if (key === 37) { // left arrow key
this.previous();
}
else if (key === 39) { // right arrow key
this.next();
}
},
__setArrowKeys: function __setArrowKeys (/* boolean */ state) {
var op = (state === true ? 'add' : 'remove') + "EventListener";
document[op]('keydown', this.__handleArrowKey);
},
__registerSlide: function __registerSlide () {
this.slidesNumber++;
},
__unregisterSlide: function __unregisterSlide () {
this.slidesNumber--;
},
__getScopedSlots: function __getScopedSlots (h) {
var this$1 = this;
if (this.slidesNumber === 0) {
return
}
var slots = this.$scopedSlots;
if (slots) {
return Object.keys(slots)
.filter(function (key) { return key.startsWith('control-'); })
.map(function (key) { return slots[key](this$1.slotScope); })
}
},
__getQuickNav: function __getQuickNav (h) {
var this$1 = this;
if (this.slidesNumber === 0 || !this.quickNav) {
return
}
var
slot = this.$scopedSlots['quick-nav'],
items = [];
if (slot) {
var loop = function ( i ) {
items.push(slot({
slide: i,
before: i < this$1.slide,
current: i === this$1.slide,
after: i > this$1.slide,
color: this$1.color,
goToSlide: function (slide) { this$1.goToSlide(slide || i); }
}));
};
for (var i = 0; i < this.slidesNumber; i++) loop( i );
}
else {
var loop$1 = function ( i ) {
items.push(h(QBtn, {
key: i,
'class': { inactive: i !== this$1.slide },
props: {
icon: this$1.quickNavIcon || this$1.$q.icon.carousel.quickNav,
round: true,
flat: true,
dense: true,
color: this$1.color
},
on: {
click: function () {
this$1.goToSlide(i);
}
}
}));
};
for (var i$1 = 0; i$1 < this.slidesNumber; i$1++) loop$1( i$1 );
}
return h('div', {
staticClass: 'q-carousel-quick-nav absolute-bottom scroll text-center',
'class': ("text-" + (this.color))
}, items)
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-carousel',
style: this.computedStyle,
'class': { fullscreen: this.inFullscreen }
}, [
h('div', {
staticClass: 'q-carousel-inner',
directives: this.noSwipe
? null
: [{
name: 'touch-pan',
modifiers: { horizontal: true },
value: this.__pan
}]
}, [
h('div', {
ref: 'track',
staticClass: 'q-carousel-track',
style: this.trackPosition,
'class': {
'infinite-left': this.infiniteLeft,
'infinite-right': this.infiniteRight
}
}, [
h('div', { staticClass: 'q-carousel-slide', style: ("flex: 0 0 " + (100) + "%"), directives: [{ name: 'show', value: this.infiniteRight }] }),
this.$slots.default,
h('div', { staticClass: 'q-carousel-slide', style: ("flex: 0 0 " + (100) + "%"), directives: [{ name: 'show', value: this.infiniteLeft }] })
])
]),
this.arrows ? h(QBtn, {
staticClass: 'q-carousel-left-arrow absolute',
props: { color: this.color, icon: this.$q.icon.carousel.left, fabMini: true, flat: true },
directives: [{ name: 'show', value: this.canGoToPrevious }],
on: { click: this.previous }
}) : null,
this.arrows ? h(QBtn, {
staticClass: 'q-carousel-right-arrow absolute',
props: { color: this.color, icon: this.$q.icon.carousel.right, fabMini: true, flat: true },
directives: [{ name: 'show', value: this.canGoToNext }],
on: { click: this.next }
}) : null,
this.__getQuickNav(h),
this.__getScopedSlots(h),
this.$slots.control
])
},
mounted: function mounted () {
var this$1 = this;
this.__planAutoPlay();
if (this.handleArrowKeys) {
this.__setArrowKeys(true);
}
this.__stopSlideNumberNotifier = this.$watch('slidesNumber', function (val) {
this$1.$emit('slides-number', val);
if (this$1.value >= val) {
this$1.$emit('input', val - 1);
}
}, { immediate: true });
},
beforeDestroy: function beforeDestroy () {
this.__cleanup();
this.__stopSlideNumberNotifier();
if (this.handleArrowKeys) {
this.__setArrowKeys(false);
}
}
}
var QCarouselSlide = {
name: 'q-carousel-slide',
inject: {
carousel: {
default: function default$1 () {
console.error('QCarouselSlide needs to be child of QCarousel');
}
}
},
props: {
imgSrc: String
},
computed: {
computedStyle: function computedStyle () {
var style = {};
if (this.imgSrc) {
style.backgroundImage = "url(" + (this.imgSrc) + ")";
style.backgroundSize = "cover";
style.backgroundPosition = "50%";
}
if (!this.carousel.inFullscreen && this.carousel.height) {
style.maxHeight = this.carousel.height;
}
return style
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-carousel-slide relative-position scroll',
style: this.computedStyle
}, this.$slots.default)
},
created: function created () {
this.carousel.__registerSlide();
},
beforeDestroy: function beforeDestroy () {
this.carousel.__unregisterSlide();
}
}
var QCarouselControl = {
name: 'q-carousel-control',
props: {
position: {
type: String,
default: 'bottom-right'
},
offset: {
type: Array,
default: function () { return [18, 18]; }
}
},
computed: {
computedClass: function computedClass () {
return ("absolute-" + (this.position))
},
computedStyle: function computedStyle () {
return {
margin: ((this.offset[1]) + "px " + (this.offset[0]) + "px")
}
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-carousel-control absolute',
style: this.computedStyle,
'class': this.computedClass
}, this.$slots.default)
}
}
var QChatMessage = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"q-message",class:{ 'q-message-sent': _vm.sent, 'q-message-received': !_vm.sent }},[(_vm.label)?_c('p',{staticClass:"q-message-label text-center",domProps:{"innerHTML":_vm._s(_vm.label)}}):_vm._e(),_vm._v(" "),_c('div',{staticClass:"q-message-container row items-end no-wrap"},[(_vm.hasAvatarSlot())?_vm._t("avatar"):_vm._e(),_vm._v(" "),(_vm.avatar && !_vm.hasAvatarSlot())?_c('img',{staticClass:"q-message-avatar",attrs:{"src":_vm.avatar}}):_vm._e(),_vm._v(" "),_c('div',{class:_vm.sizeClass},[(_vm.name)?_c('div',{staticClass:"q-message-name",domProps:{"innerHTML":_vm._s(_vm.name)}}):_vm._e(),_vm._v(" "),(_vm.text)?_vm._l((_vm.text),function(msg,index){return _c('div',{key:index,staticClass:"q-message-text",class:_vm.messageClass},[_c('span',{staticClass:"q-message-text-content",class:_vm.textClass},[_c('div',{domProps:{"innerHTML":_vm._s(msg)}}),_vm._v(" "),(_vm.stamp)?_c('div',{staticClass:"q-message-stamp",domProps:{"innerHTML":_vm._s(_vm.stamp)}}):_vm._e()])])}):_vm._e(),_vm._v(" "),(_vm.hasDefaultSlot())?_c('div',{staticClass:"q-message-text",class:_vm.messageClass},[_c('span',{staticClass:"q-message-text-content",class:_vm.textClass},[_vm._t("default"),_vm._v(" "),(_vm.stamp)?_c('div',{staticClass:"q-message-stamp",domProps:{"innerHTML":_vm._s(_vm.stamp)}}):_vm._e()],2)]):_vm._e()],2)],2)])},staticRenderFns: [],
name: 'q-chat-message',
props: {
sent: Boolean,
label: String,
bgColor: String,
textColor: String,
name: String,
avatar: String,
text: Array,
stamp: String,
size: String
},
computed: {
textClass: function textClass () {
if (this.textColor) {
return ("text-" + (this.textColor))
}
},
messageClass: function messageClass () {
if (this.bgColor) {
return ("text-" + (this.bgColor))
}
},
sizeClass: function sizeClass () {
if (this.size) {
return ("col-" + (this.size))
}
}
},
methods: {
hasDefaultSlot: function hasDefaultSlot () {
return Boolean(this.$slots['default'])
},
hasAvatarSlot: function hasAvatarSlot () {
return Boolean(this.$slots['avatar'])
}
}
}
function getDirection$1 (mod) {
if (Object.keys(mod).length === 0) {
return {
left: true, right: true, up: true, down: true, horizontal: true, vertical: true
}
}
var dir = {};['left', 'right', 'up', 'down', 'horizontal', 'vertical'].forEach(function (direction) {
if (mod[direction]) {
dir[direction] = true;
}
});
if (dir.horizontal) {
dir.left = dir.right = true;
}
if (dir.vertical) {
dir.up = dir.down = true;
}
if (dir.left || dir.right) {
dir.horizontal = true;
}
if (dir.up || dir.down) {
dir.vertical = true;
}
return dir
}
function updateClasses$1 (el, dir) {
el.classList.add('q-touch');
if (dir.horizontal && !dir.vertical) {
el.classList.add('q-touch-y');
el.classList.remove('q-touch-x');
}
else if (!dir.horizontal && dir.vertical) {
el.classList.add('q-touch-x');
el.classList.remove('q-touch-y');
}
}
var TouchSwipe = {
name: 'touch-swipe',
bind: function bind (el, binding) {
var mouse = !binding.modifiers.nomouse;
var ctx = {
handler: binding.value,
direction: getDirection$1(binding.modifiers),
start: function start (evt) {
var pos = position(evt);
ctx.event = {
x: pos.left,
y: pos.top,
time: new Date().getTime(),
detected: false,
prevent: ctx.direction.horizontal && ctx.direction.vertical
};
if (mouse) {
document.addEventListener('mousemove', ctx.move);
document.addEventListener('mouseup', ctx.end);
}
},
move: function move (evt) {
var
pos = position(evt),
distX = pos.left - ctx.event.x,
distY = pos.top - ctx.event.y;
if (ctx.event.prevent) {
evt.preventDefault();
return
}
if (ctx.event.detected) {
return
}
ctx.event.detected = true;
if (ctx.direction.horizontal && !ctx.direction.vertical) {
if (Math.abs(distX) > Math.abs(distY)) {
evt.preventDefault();
ctx.event.prevent = true;
}
}
else {
if (Math.abs(distX) < Math.abs(distY)) {
evt.preventDefault();
ctx.event.prevent = true;
}
}
},
end: function end (evt) {
if (mouse) {
document.removeEventListener('mousemove', ctx.move);
document.removeEventListener('mouseup', ctx.end);
}
var
direction,
pos = position(evt),
distX = pos.left - ctx.event.x,
distY = pos.top - ctx.event.y;
if (distX !== 0 || distY !== 0) {
if (Math.abs(distX) >= Math.abs(distY)) {
direction = distX < 0 ? 'left' : 'right';
}
else {
direction = distY < 0 ? 'up' : 'down';
}
if (ctx.direction[direction]) {
ctx.handler({
evt: evt,
direction: direction,
duration: new Date().getTime() - ctx.event.time,
distance: {
x: Math.abs(distX),
y: Math.abs(distY)
}
});
}
}
}
};
el.__qtouchswipe = ctx;
updateClasses$1(el, ctx.direction);
if (mouse) {
el.addEventListener('mousedown', ctx.start);
}
el.addEventListener('touchstart', ctx.start);
el.addEventListener('touchmove', ctx.move);
el.addEventListener('touchend', ctx.end);
},
update: function update (el, binding) {
if (binding.oldValue !== binding.value) {
el.__qtouchswipe.handler = binding.value;
}
},
unbind: function unbind (el, binding) {
var ctx = el.__qtouchswipe;
el.removeEventListener('mousedown', ctx.start);
el.removeEventListener('touchstart', ctx.start);
el.removeEventListener('touchmove', ctx.move);
el.removeEventListener('touchend', ctx.end);
delete el.__qtouchswipe;
}
}
var CheckboxMixin = {
directives: {
TouchSwipe: TouchSwipe
},
props: {
val: {},
trueValue: { default: true },
falseValue: { default: false }
},
computed: {
isTrue: function isTrue () {
return this.modelIsArray
? this.index > -1
: this.value === this.trueValue
},
isFalse: function isFalse () {
return this.modelIsArray
? this.index === -1
: this.value === this.falseValue
},
index: function index () {
if (this.modelIsArray) {
return this.value.indexOf(this.val)
}
},
modelIsArray: function modelIsArray () {
return Array.isArray(this.value)
}
},
methods: {
toggle: function toggle (evt, blur) {
if ( blur === void 0 ) blur = true;
if (this.disable) {
return
}
if (evt) {
stopAndPrevent(evt);
}
if (blur) {
this.$el.blur();
}
var val;
if (this.modelIsArray) {
if (this.isTrue) {
val = this.value.slice();
val.splice(this.index, 1);
}
else {
val = this.value.concat(this.val);
}
}
else if (this.isTrue) {
val = this.toggleIndeterminate ? this.indeterminateValue : this.falseValue;
}
else if (this.isFalse) {
val = this.trueValue;
}
else {
val = this.falseValue;
}
this.__update(val);
}
}
}
var OptionMixin = {
props: {
value: {
required: true
},
label: String,
leftLabel: Boolean,
color: {
type: String,
default: 'primary'
},
keepColor: Boolean,
dark: Boolean,
disable: Boolean,
noFocus: Boolean,
checkedIcon: String,
uncheckedIcon: String
},
computed: {
classes: function classes () {
return [
this.$options._componentTag,
{
disabled: this.disable,
reverse: this.leftLabel,
'q-focusable': this.focusable
}
]
},
innerClasses: function innerClasses () {
if (this.isTrue || this.isIndeterminate) {
return ['active', ("text-" + (this.color))]
}
else {
var color = this.keepColor
? this.color
: (this.dark ? 'light' : 'dark');
return ("text-" + color)
}
},
focusable: function focusable () {
return !this.noFocus && !this.disable
},
tabindex: function tabindex () {
return this.focusable ? 0 : -1
}
},
methods: {
__update: function __update (value) {
var this$1 = this;
var ref = this.$refs.ripple;
if (ref) {
ref.classList.add('active');
setTimeout(function () {
ref.classList.remove('active');
}, 10);
}
this.$emit('input', value);
this.$nextTick(function () {
if (JSON.stringify(value) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', value);
}
});
},
__onKeydown: function __onKeydown (evt) {
var key = getEventKey(evt);
if (key === 13 /* enter */ || key === 32 /* spacebar */) {
this.toggle(evt, false);
}
}
},
render: function render (h) {
var this$1 = this;
return h('div', {
staticClass: 'q-option cursor-pointer no-outline row inline no-wrap items-center',
'class': this.classes,
attrs: { tabindex: this.tabindex },
on: {
click: this.toggle,
focus: function () { this$1.$emit('focus'); },
blur: function () { this$1.$emit('blur'); },
keydown: this.__onKeydown
},
directives: this.$options._componentTag === 'q-toggle'
? [{
name: 'touch-swipe',
modifiers: { horizontal: true },
value: this.__swipe
}]
: null
}, [
h('div', {
staticClass: 'q-option-inner relative-position',
'class': this.innerClasses
}, [
h('input', {
attrs: { type: 'checkbox' },
on: { change: this.toggle }
}),
h('div', { staticClass: 'q-focus-helper' }),
this.__getContent(h)
]),
this.label
? h('span', { staticClass: 'q-option-label', domProps: { innerHTML: this.label } })
: null,
this.$slots.default
])
}
}
var QCheckbox = {
name: 'q-checkbox',
mixins: [CheckboxMixin, OptionMixin],
props: {
toggleIndeterminate: Boolean,
indeterminateValue: { default: null },
indeterminateIcon: String
},
computed: {
isIndeterminate: function isIndeterminate () {
return this.value === void 0 || this.value === this.indeterminateValue
},
checkedStyle: function checkedStyle () {
return this.isTrue
? {transition: 'opacity 0ms cubic-bezier(0.23, 1, 0.32, 1) 0ms, transform 800ms cubic-bezier(0.23, 1, 0.32, 1) 0ms', opacity: 1, transform: 'scale(1)'}
: {transition: 'opacity 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms, transform 0ms cubic-bezier(0.23, 1, 0.32, 1) 450ms', opacity: 0, transform: 'scale(0)'}
},
indeterminateStyle: function indeterminateStyle () {
return this.isIndeterminate
? {transition: 'opacity 0ms cubic-bezier(0.23, 1, 0.32, 1) 0ms, transform 800ms cubic-bezier(0.23, 1, 0.32, 1) 0ms', opacity: 1, transform: 'scale(1)'}
: {transition: 'opacity 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms, transform 0ms cubic-bezier(0.23, 1, 0.32, 1) 450ms', opacity: 0, transform: 'scale(0)'}
},
uncheckedStyle: function uncheckedStyle () {
return this.isFalse
? {opacity: 1}
: {transition: 'opacity 650ms cubic-bezier(0.23, 1, 0.32, 1) 150ms', opacity: 0}
}
},
methods: {
__getContent: function __getContent (h) {
return [
h(QIcon, {
staticClass: 'q-checkbox-icon cursor-pointer',
props: { name: this.uncheckedIcon || this.$q.icon.checkbox.unchecked["mat"] },
style: this.uncheckedStyle
}),
h(QIcon, {
staticClass: 'q-checkbox-icon cursor-pointer absolute-full',
props: { name: this.indeterminateIcon || this.$q.icon.checkbox.indeterminate["mat"] },
style: this.indeterminateStyle
}),
h(QIcon, {
staticClass: 'q-checkbox-icon cursor-pointer absolute-full',
props: { name: this.checkedIcon || this.$q.icon.checkbox.checked["mat"] },
style: this.checkedStyle
}),
h('div', { ref: 'ripple', staticClass: 'q-radial-ripple' })
]
}
}
}
var QChip = {
name: 'q-chip',
props: {
small: Boolean,
tag: Boolean,
square: Boolean,
floating: Boolean,
pointing: {
type: String,
validator: function (v) { return ['up', 'right', 'down', 'left'].includes(v); }
},
color: String,
textColor: String,
icon: String,
iconRight: String,
avatar: String,
closable: Boolean,
detail: Boolean
},
computed: {
classes: function classes () {
var cls = [{
tag: this.tag,
square: this.square,
floating: this.floating,
pointing: this.pointing,
small: this.small || this.floating
}];
this.pointing && cls.push(("pointing-" + (this.pointing)));
if (this.color) {
cls.push(("bg-" + (this.color)));
!this.textColor && cls.push("text-white");
}
if (this.textColor) {
cls.push(("text-" + (this.textColor)));
}
return cls
}
},
methods: {
__onClick: function __onClick (e) {
this.$emit('click', e);
},
__onMouseDown: function __onMouseDown (e) {
this.$emit('focus', e);
},
__onKeydown: function __onKeydown (evt) {
var key = getEventKey(evt);
if (this.closable && (key === 13 /* enter */ || key === 32 /* spacebar */)) {
this.$emit('hide');
}
}
},
render: function render (h) {
var this$1 = this;
return h('div', {
staticClass: 'q-chip row no-wrap inline items-center',
'class': this.classes,
on: {
mousedown: this.__onMouseDown,
touchstart: this.__onMouseDown,
click: this.__onClick,
keydown: this.__onKeydown
}
}, [
this.icon || this.avatar
? h('div', {
staticClass: 'q-chip-side chip-left row flex-center',
'class': { 'chip-detail': this.detail }
}, [
this.icon
? h(QIcon, { props: { name: this.icon } })
: (this.avatar ? h('img', { domProps: { src: this.avatar } }) : null)
])
: null,
h('div', { staticClass: 'q-chip-main' }, [
this.$slots.default
]),
this.iconRight
? h(QIcon, {
props: { name: this.iconRight },
staticClass: 'on-right'
})
: null,
this.closable
? h('div', { staticClass: 'q-chip-side chip-right row flex-center' }, [
h(QIcon, {
props: { name: this.$q.icon.chip.close },
staticClass: 'cursor-pointer',
nativeOn: {
click: function (e) {
e && e.stopPropagation();
this$1.$emit('hide');
}
}
})
])
: null
])
}
}
var marginal = {
type: Array,
validator: function (v) { return v.every(function (i) { return 'icon' in i; }); }
};
var align = {
left: 'start',
center: 'center',
right: 'end'
};
var FrameMixin = {
components: {
QIcon: QIcon
},
props: {
prefix: String,
suffix: String,
stackLabel: String,
floatLabel: String,
error: Boolean,
warning: Boolean,
disable: Boolean,
color: {
type: String,
default: 'primary'
},
dark: Boolean,
before: marginal,
after: marginal,
inverted: Boolean,
hideUnderline: Boolean,
align: {
type: String,
default: 'left',
validator: function (v) { return ['left', 'center', 'right'].includes(v); }
},
clearValue: {
default: null
}
},
computed: {
labelIsAbove: function labelIsAbove () {
return this.focused || this.length || this.additionalLength || this.stackLabel
},
alignClass: function alignClass () {
return ("justify-" + (align[this.align]))
},
editable: function editable () {
return !this.disable && !this.readonly
}
},
methods: {
clear: function clear (evt) {
if (!this.editable) {
return
}
stopAndPrevent(evt);
var val = this.clearValue;
if (this.__setModel) {
this.__setModel(val, true);
}
else {
this.$emit('input', val);
}
this.$emit('clear', val);
}
}
}
var InputMixin = {
props: {
autofocus: [Boolean, String],
name: String,
maxLength: [Number, String],
maxHeight: Number,
placeholder: String,
loading: Boolean
},
data: function data () {
return {
focused: false,
timer: null,
isNumberError: false
}
},
computed: {
inputPlaceholder: function inputPlaceholder () {
if ((!this.floatLabel && !this.stackLabel) || this.labelIsAbove) {
return this.placeholder
}
}
},
methods: {
focus: function focus () {
if (!this.disable) {
this.$refs.input.focus();
}
},
blur: function blur () {
this.$refs.input.blur();
},
select: function select () {
this.$refs.input.select();
},
__onFocus: function __onFocus (e) {
clearTimeout(this.timer);
this.focused = true;
this.$emit('focus', e);
},
__onInputBlur: function __onInputBlur (e) {
var this$1 = this;
clearTimeout(this.timer);
this.timer = setTimeout(function () {
this$1.__onBlur(e);
}, 200);
},
__onBlur: function __onBlur (e) {
var this$1 = this;
this.focused = false;
this.$emit('blur', e);
var isNumberError = this.isNumber && this.isNumberError;
var value = isNumberError ? null : this.model;
if (isNumberError) {
this.$emit('input', value);
}
this.$nextTick(function () {
if (JSON.stringify(value) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', value);
}
});
},
__onKeydown: function __onKeydown (e) {
this.$emit('keydown', e);
},
__onKeyup: function __onKeyup (e) {
this.$emit('keyup', e);
},
__onClick: function __onClick (e) {
this.focus();
this.$emit('click', e);
}
},
mounted: function mounted () {
var this$1 = this;
this.$nextTick(function () {
var input = this$1.$refs.input;
if (this$1.autofocus && input) {
input.focus();
if (this$1.autofocus === 'select') {
input.select();
}
}
});
},
beforeDestroy: function beforeDestroy () {
clearTimeout(this.timer);
}
}
var FieldParentMixin = {
inject: {
field: {
from: '__field',
default: null
}
},
beforeMount: function beforeMount () {
if (this.field) {
this.field.__registerInput(this);
}
},
beforeDestroy: function beforeDestroy () {
if (this.field) {
this.field.__unregisterInput();
}
}
}
var QInputFrame = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"q-if row no-wrap items-center relative-position",class:_vm.classes,attrs:{"tabindex":_vm.focusable && !_vm.disable ? 0 : -1},on:{"click":_vm.__onClick}},[(_vm.before)?_vm._l((_vm.before),function(item){return _c('q-icon',{key:("b" + (item.icon)),staticClass:"q-if-control q-if-control-before",class:{hidden: _vm.__additionalHidden(item, _vm.hasError, _vm.hasWarning, _vm.length)},attrs:{"name":item.icon},nativeOn:{"mousedown":function($event){_vm.__onMouseDown($event);},"touchstart":function($event){_vm.__onMouseDown($event);},"click":function($event){_vm.__baHandler($event, item);}}})}):_vm._e(),_vm._v(" "),_c('div',{staticClass:"q-if-inner col row no-wrap items-center relative-position"},[(_vm.hasLabel)?_c('div',{staticClass:"q-if-label ellipsis full-width absolute self-start",class:{'q-if-label-above': _vm.labelIsAbove},domProps:{"innerHTML":_vm._s(_vm.label)}}):_vm._e(),_vm._v(" "),(_vm.prefix)?_c('span',{staticClass:"q-if-addon q-if-addon-left",class:_vm.addonClass,domProps:{"innerHTML":_vm._s(_vm.prefix)}}):_vm._e(),_vm._v(" "),_vm._t("default"),_vm._v(" "),(_vm.suffix)?_c('span',{staticClass:"q-if-addon q-if-addon-right",class:_vm.addonClass,domProps:{"innerHTML":_vm._s(_vm.suffix)}}):_vm._e()],2),_vm._v(" "),_vm._t("after"),_vm._v(" "),(_vm.after)?_vm._l((_vm.after),function(item){return _c('q-icon',{key:("a" + (item.icon)),staticClass:"q-if-control",class:{hidden: _vm.__additionalHidden(item, _vm.hasError, _vm.hasWarning, _vm.length)},attrs:{"name":item.icon},nativeOn:{"mousedown":function($event){_vm.__onMouseDown($event);},"touchstart":function($event){_vm.__onMouseDown($event);},"click":function($event){_vm.__baHandler($event, item);}}})}):_vm._e()],2)},staticRenderFns: [],
name: 'q-input-frame',
mixins: [FrameMixin, FieldParentMixin],
props: {
topAddons: Boolean,
focused: Boolean,
length: Number,
focusable: Boolean,
additionalLength: Boolean
},
computed: {
hasStackLabel: function hasStackLabel () {
return typeof this.stackLabel === 'string' && this.stackLabel.length > 0
},
hasLabel: function hasLabel () {
return this.hasStackLabel || (typeof this.floatLabel === 'string' && this.floatLabel.length > 0)
},
label: function label () {
return this.hasStackLabel ? this.stackLabel : this.floatLabel
},
addonClass: function addonClass () {
return {
'q-if-addon-visible': !this.hasLabel || this.labelIsAbove,
'self-start': this.topAddons
}
},
classes: function classes () {
var cls = [{
'q-if-has-label': this.label,
'q-if-focused': this.focused,
'q-if-error': this.hasError,
'q-if-warning': this.hasWarning,
'q-if-disabled': this.disable,
'q-if-focusable': this.focusable && !this.disable,
'q-if-inverted': this.inverted,
'q-if-dark': this.dark || this.inverted,
'q-if-hide-underline': this.hideUnderline
}];
var color = this.hasError ? 'negative' : this.hasWarning ? 'warning' : this.color;
if (this.inverted) {
cls.push(("bg-" + color));
cls.push("text-white");
}
else {
cls.push(("text-" + color));
}
return cls
},
hasError: function hasError () {
return !!((this.field && this.field.error) || this.error)
},
hasWarning: function hasWarning () {
// error is the higher priority
return !!(!this.hasError && ((this.field && this.field.warning) || this.warning))
}
},
methods: {
__onClick: function __onClick (e) {
this.$emit('click', e);
},
__onMouseDown: function __onMouseDown (e) {
var this$1 = this;
this.$nextTick(function () { return this$1.$emit('focus', e); });
},
__additionalHidden: function __additionalHidden (item, hasError, hasWarning, length) {
if (item.condition !== void 0) {
return item.condition === false
}
return (
(item.content !== void 0 && !item.content === (length > 0)) ||
(item.error !== void 0 && !item.error === hasError) ||
(item.warning !== void 0 && !item.warning === hasWarning)
)
},
__baHandler: function __baHandler (evt, item) {
if (!item.allowPropagation) {
evt.stopPropagation();
}
if (item.handler) {
item.handler(evt);
}
}
}
}
var QChipsInput = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('q-input-frame',{staticClass:"q-chips-input",attrs:{"prefix":_vm.prefix,"suffix":_vm.suffix,"stack-label":_vm.stackLabel,"float-label":_vm.floatLabel,"error":_vm.error,"warning":_vm.warning,"disable":_vm.disable,"inverted":_vm.inverted,"dark":_vm.dark,"hide-underline":_vm.hideUnderline,"before":_vm.before,"after":_vm.after,"color":_vm.computedColor,"focused":_vm.focused,"length":_vm.length,"additional-length":_vm.input.length > 0},on:{"click":_vm.__onClick}},[_c('div',{staticClass:"col row items-center group q-input-chips"},[_vm._l((_vm.model),function(label,index){return _c('q-chip',{key:(label + "#" + index),attrs:{"small":"","closable":_vm.editable,"color":_vm.computedChipColor,"text-color":_vm.computedChipTextColor,"tabindex":_vm.editable && _vm.focused ? 0 : -1},on:{"focus":_vm.__clearTimer,"hide":function($event){_vm.remove(index);}},nativeOn:{"blur":function($event){_vm.__onInputBlur($event);},"focus":function($event){_vm.__clearTimer($event);}}},[_vm._v(" "+_vm._s(label)+" ")])}),_vm._v(" "),_c('input',{directives:[{name:"model",rawName:"v-model",value:(_vm.input),expression:"input"}],ref:"input",staticClass:"col q-input-target",class:[("text-" + (_vm.align))],attrs:{"name":_vm.name,"placeholder":_vm.inputPlaceholder,"disabled":_vm.disable,"readonly":_vm.readonly,"max-length":_vm.maxLength},domProps:{"value":(_vm.input)},on:{"focus":_vm.__onFocus,"blur":_vm.__onInputBlur,"keydown":_vm.__handleKey,"keyup":_vm.__onKeyup,"input":function($event){if($event.target.composing){ return; }_vm.input=$event.target.value;}}})],2),_vm._v(" "),(_vm.editable)?_c('q-icon',{staticClass:"q-if-control self-end",class:{invisible: !_vm.input.length},attrs:{"slot":"after","name":_vm.computedAddIcon},nativeOn:{"mousedown":function($event){_vm.__clearTimer($event);},"touchstart":function($event){_vm.__clearTimer($event);},"click":function($event){_vm.add();}},slot:"after"}):_vm._e()],1)},staticRenderFns: [],
name: 'q-chips-input',
mixins: [FrameMixin, InputMixin],
components: {
QInputFrame: QInputFrame,
QChip: QChip
},
props: {
value: {
type: Array,
required: true
},
frameColor: String,
readonly: Boolean,
addIcon: String
},
data: function data () {
return {
input: '',
model: [].concat( this.value )
}
},
watch: {
value: function value (v) {
if (Array.isArray(v)) {
this.model = [].concat( v );
}
else {
this.model = [];
}
}
},
computed: {
length: function length () {
return this.model
? this.model.length
: 0
},
computedAddIcon: function computedAddIcon () {
return this.addIcon || this.$q.icon.chipsInput.add
},
computedColor: function computedColor () {
return this.inverted ? this.frameColor || this.color : this.color
},
computedChipColor: function computedChipColor () {
if (this.inverted) {
if (this.frameColor) {
return this.color
}
return this.dark !== false ? 'white' : null
}
return this.color
},
computedChipTextColor: function computedChipTextColor () {
if (this.inverted) {
return this.frameColor || this.color
}
return this.dark !== false ? 'white' : null
}
},
methods: {
add: function add (value) {
if ( value === void 0 ) value = this.input;
clearTimeout(this.timer);
this.focus();
if (this.editable && value) {
this.model.push(value);
this.$emit('input', this.model);
this.input = '';
}
},
remove: function remove (index) {
clearTimeout(this.timer);
this.focus();
if (this.editable && index >= 0 && index < this.length) {
this.model.splice(index, 1);
this.$emit('input', this.model);
}
},
__clearTimer: function __clearTimer () {
var this$1 = this;
this.$nextTick(function () { return clearTimeout(this$1.timer); });
},
__handleKey: function __handleKey (e) {
// ENTER key
if (e.which === 13 || e.keyCode === 13) {
e.preventDefault();
this.add();
}
// Backspace key
else if (e.which === 8 || e.keyCode === 8) {
if (!this.input.length && this.length) {
this.remove(this.length - 1);
}
}
else {
this.__onKeydown(e);
}
},
__onClick: function __onClick () {
this.focus();
}
}
}
function getHeight (el, style$$1) {
var initial = {
visibility: el.style.visibility,
maxHeight: el.style.maxHeight
};
css(el, {
visibility: 'hidden',
maxHeight: ''
});
var height$$1 = style$$1.height;
css(el, initial);
return parseFloat(height$$1)
}
function parseSize (padding) {
return padding.split(' ').map(function (t) {
var unit = t.match(/[a-zA-Z]+/) || '';
if (unit) {
unit = unit[0];
}
return [parseFloat(t), unit]
})
}
function toggleSlide (el, showing, done) {
var store = el.__qslidetoggle || {};
function anim () {
store.uid = start({
to: showing ? 100 : 0,
from: store.pos !== null ? store.pos : showing ? 0 : 100,
apply: function apply (pos) {
store.pos = pos;
css(el, {
maxHeight: ((store.height * pos / 100) + "px"),
padding: store.padding ? store.padding.map(function (t) { return (t[0] * pos / 100) + t[1]; }).join(' ') : '',
margin: store.margin ? store.margin.map(function (t) { return (t[0] * pos / 100) + t[1]; }).join(' ') : ''
});
},
done: function done$1 () {
store.uid = null;
store.pos = null;
done();
css(el, store.css);
}
});
el.__qslidetoggle = store;
}
if (store.uid) {
stop(store.uid);
return anim()
}
store.css = {
overflowY: el.style.overflowY,
maxHeight: el.style.maxHeight,
padding: el.style.padding,
margin: el.style.margin
};
var style$$1 = window.getComputedStyle(el);
if (style$$1.padding && style$$1.padding !== '0px') {
store.padding = parseSize(style$$1.padding);
}
if (style$$1.margin && style$$1.margin !== '0px') {
store.margin = parseSize(style$$1.margin);
}
store.height = getHeight(el, style$$1);
store.pos = null;
el.style.overflowY = 'hidden';
anim();
}
var QSlideTransition = {
name: 'q-slide-transition',
props: {
appear: Boolean
},
render: function render (h) {
return h('transition', {
props: {
mode: 'out-in',
css: false,
appear: this.appear
},
on: {
enter: function enter (el, done) {
toggleSlide(el, true, done);
},
leave: function leave (el, done) {
toggleSlide(el, false, done);
}
}
}, this.$slots.default)
}
}
var eventName = 'q:collapsible:close';
var QCollapsible = {
name: 'q-collapsible',
mixins: [ModelToggleMixin],
modelToggle: {
history: false
},
directives: {
Ripple: Ripple
},
props: {
disable: Boolean,
popup: Boolean,
indent: Boolean,
group: String,
iconToggle: Boolean,
separator: Boolean,
insetSeparator: Boolean,
noRipple: Boolean,
collapseIcon: String,
opened: Boolean,
dense: Boolean,
sparse: Boolean,
multiline: Boolean,
icon: String,
rightIcon: String,
image: String,
rightImage: String,
avatar: String,
rightAvatar: String,
letter: String,
rightLetter: String,
label: String,
sublabel: String,
labelLines: [String, Number],
sublabelLines: [String, Number],
headerStyle: [Array, String, Object],
headerClass: [Array, String, Object]
},
computed: {
cfg: function cfg () {
return {
link: !this.iconToggle,
dark: this.dark,
dense: this.dense,
sparse: this.sparse,
multiline: this.multiline,
icon: this.icon,
rightIcon: this.rightIcon,
image: this.image,
rightImage: this.rightImage,
avatar: this.avatar,
rightAvatar: this.rightAvatar,
letter: this.letter,
rightLetter: this.rightLetter,
label: this.label,
sublabel: this.sublabel,
labelLines: this.labelLines,
sublabelLines: this.sublabelLines
}
},
hasRipple: function hasRipple () {
return "mat" === 'mat' && !this.noRipple && !this.disable
},
classes: function classes () {
return {
'q-collapsible-opened': this.popup && this.showing,
'q-collapsible-closed': this.popup && !this.showing,
'q-item-separator': this.separator,
'q-item-inset-separator': this.insetSeparator,
disabled: this.disable
}
}
},
watch: {
showing: function showing (val) {
if (val && this.group) {
this.$root.$emit(eventName, this);
}
}
},
methods: {
__toggleItem: function __toggleItem () {
if (!this.iconToggle) {
this.toggle();
}
},
__toggleIcon: function __toggleIcon (e) {
if (this.iconToggle) {
e && e.stopPropagation();
this.toggle();
}
},
__eventHandler: function __eventHandler (comp) {
if (this.group && this !== comp && comp.group === this.group) {
this.hide();
}
},
__getToggleSide: function __getToggleSide (h, slot) {
return [
h(QItemTile, {
slot: slot ? 'right' : undefined,
staticClass: 'cursor-pointer transition-generic relative-position',
'class': {
'rotate-180': this.showing,
invisible: this.disable
},
nativeOn: {
click: this.__toggleIcon
},
props: { icon: this.collapseIcon || this.$q.icon.collapsible.icon },
directives: this.iconToggle && this.hasRipple
? [{ name: 'ripple' }]
: null
})
]
},
__getItemProps: function __getItemProps (wrapper) {
return {
props: wrapper
? { cfg: this.cfg }
: { link: !this.iconToggle },
style: this.headerStyle,
'class': this.headerClass,
nativeOn: {
click: this.__toggleItem
},
directives: this.hasRipple && !this.iconToggle
? [{ name: 'ripple' }]
: null
}
}
},
created: function created () {
this.$root.$on(eventName, this.__eventHandler);
if (this.opened || this.value) {
this.show();
}
},
beforeDestroy: function beforeDestroy () {
this.$root.$off(eventName, this.__eventHandler);
},
render: function render (h) {
return h('div', {
staticClass: 'q-collapsible q-item-division relative-position',
'class': this.classes
}, [
h('div', {
staticClass: 'q-collapsible-inner'
}, [
this.$slots.header
? h(QItem, this.__getItemProps(), [
this.$slots.header,
h(QItemSide, { props: { right: true }, staticClass: 'relative-position' }, this.__getToggleSide(h))
])
: h(QItemWrapper, this.__getItemProps(true), this.__getToggleSide(h, true)),
h(QSlideTransition, [
h('div', {
directives: [{ name: 'show', value: this.showing }]
}, [
h('div', {
staticClass: 'q-collapsible-sub-item relative-position',
'class': { indent: this.indent }
}, [
this.$slots.default
])
])
])
])
])
}
}
var DisplayModeMixin = {
props: {
popover: Boolean,
modal: Boolean
},
computed: {
isPopover: function isPopover () {
// Explicit popover / modal choice
if (this.popover) { return true }
if (this.modal) { return false }
// Automatically determine the default popover or modal behavior
return this.$q.platform.is.desktop && !this.$q.platform.within.iframe
}
}
}
function getPercentage (event, dragging) {
return between((position(event).left - dragging.left) / dragging.width, 0, 1)
}
function notDivides (res, decimals) {
var number = decimals
? parseFloat(res.toFixed(decimals))
: res;
return number !== parseInt(number, 10)
}
function getModel (percentage, min, max, step, decimals) {
var
model = min + percentage * (max - min),
modulo = (model - min) % step;
model += (Math.abs(modulo) >= step / 2 ? (modulo < 0 ? -1 : 1) * step : 0) - modulo;
if (decimals) {
model = parseFloat(model.toFixed(decimals));
}
return between(model, min, max)
}
var SliderMixin = {
directives: {
TouchPan: TouchPan
},
props: {
min: {
type: Number,
default: 1
},
max: {
type: Number,
default: 5
},
step: {
type: Number,
default: 1
},
decimals: Number,
snap: Boolean,
markers: Boolean,
label: Boolean,
labelAlways: Boolean,
square: Boolean,
color: String,
fillHandleAlways: Boolean,
error: Boolean,
readonly: Boolean,
disable: Boolean
},
data: function data () {
return {
clickDisabled: false
}
},
computed: {
editable: function editable () {
return !this.disable && !this.readonly
},
classes: function classes () {
var cls = {
disabled: this.disable,
readonly: this.readonly,
'label-always': this.labelAlways,
'has-error': this.error
};
if (!this.error && this.color) {
cls[("text-" + (this.color))] = true;
}
return cls
},
markersLen: function markersLen () {
return (this.max - this.min) / this.step + 1
},
labelColor: function labelColor () {
return this.error
? 'negative'
: this.color || 'primary'
},
computedDecimals: function computedDecimals () {
return this.decimals !== void 0 ? this.decimals || 0 : (String(this.step).trim('0').split('.')[1] || '').length
}
},
methods: {
__pan: function __pan (event) {
var this$1 = this;
if (event.isFinal) {
this.clickDisabled = true;
this.$nextTick(function () {
this$1.clickDisabled = false;
});
this.__end(event.evt);
}
else if (event.isFirst) {
this.__setActive(event.evt);
}
else if (this.dragging) {
this.__update(event.evt);
}
},
__click: function __click (event) {
if (this.clickDisabled) {
return
}
this.__setActive(event);
this.__end(event);
},
__getMarkers: function __getMarkers (h) {
var this$1 = this;
if (!this.markers) {
return
}
var markers = [];
for (var i = 0; i < this.markersLen; i++) {
markers.push(h('div', {
staticClass: 'q-slider-mark',
key: ("marker" + i),
style: {
left: ((i * 100 * this$1.step / (this$1.max - this$1.min)) + "%")
}
}));
}
return markers
}
},
created: function created () {
this.__validateProps();
},
render: function render (h) {
return h('div', {
staticClass: 'q-slider non-selectable',
'class': this.classes,
on: this.editable ? { click: this.__click } : null,
directives: this.editable
? [{
name: 'touch-pan',
modifiers: { horizontal: true },
value: this.__pan
}]
: null
}, [
h('div', {
ref: 'handle',
staticClass: 'q-slider-handle-container'
}, [
h('div', { staticClass: 'q-slider-track' }),
this.__getMarkers(h)
].concat(this.__getContent(h)))
])
}
};
var QSlider = {
name: 'q-slider',
mixins: [SliderMixin],
props: {
value: {
type: Number,
required: true
},
labelValue: String
},
data: function data () {
return {
model: this.value,
dragging: false,
currentPercentage: (this.value - this.min) / (this.max - this.min)
}
},
computed: {
percentage: function percentage () {
if (this.snap) {
return (this.model - this.min) / (this.max - this.min) * 100 + '%'
}
return 100 * this.currentPercentage + '%'
},
displayValue: function displayValue () {
return this.labelValue !== void 0
? this.labelValue
: this.model
}
},
watch: {
value: function value (value$1) {
if (this.dragging) {
return
}
if (value$1 < this.min) {
this.model = this.min;
}
else if (value$1 > this.max) {
this.model = this.max;
}
else {
this.model = value$1;
}
this.currentPercentage = (this.model - this.min) / (this.max - this.min);
},
min: function min (value) {
if (this.model < value) {
this.model = value;
return
}
this.$nextTick(this.__validateProps);
},
max: function max (value) {
if (this.model > value) {
this.model = value;
return
}
this.$nextTick(this.__validateProps);
},
step: function step () {
this.$nextTick(this.__validateProps);
}
},
methods: {
__setActive: function __setActive (event) {
var container = this.$refs.handle;
this.dragging = {
left: container.getBoundingClientRect().left,
width: container.offsetWidth
};
this.__update(event);
},
__update: function __update (event) {
var
percentage = getPercentage(event, this.dragging),
model = getModel(percentage, this.min, this.max, this.step, this.computedDecimals);
this.currentPercentage = percentage;
this.model = model;
this.$emit('input', model);
},
__end: function __end () {
var this$1 = this;
this.dragging = false;
this.currentPercentage = (this.model - this.min) / (this.max - this.min);
this.$nextTick(function () {
if (JSON.stringify(this$1.model) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', this$1.model);
}
this$1.$emit('dragend', this$1.model);
});
},
__validateProps: function __validateProps () {
if (this.min >= this.max) {
console.error('Range error: min >= max', this.$el, this.min, this.max);
}
else if (notDivides((this.max - this.min) / this.step, this.computedDecimals)) {
console.error('Range error: step must be a divisor of max - min', this.min, this.max, this.step, this.computedDecimals);
}
},
__getContent: function __getContent (h) {
return [
h('div', {
staticClass: 'q-slider-track active-track',
style: { width: this.percentage },
'class': {
'no-transition': this.dragging,
'handle-at-minimum': this.model === this.min
}
}),
h('div', {
staticClass: 'q-slider-handle',
style: {
left: this.percentage,
borderRadius: this.square ? '0' : '50%'
},
'class': {
dragging: this.dragging,
'handle-at-minimum': !this.fillHandleAlways && this.model === this.min
}
}, [
this.label || this.labelAlways
? h(QChip, {
staticClass: 'q-slider-label no-pointer-events',
'class': { 'label-always': this.labelAlways },
props: {
pointing: 'down',
square: true,
color: this.labelColor
}
}, [ this.displayValue ])
: null,
h('div', { staticClass: 'q-slider-ring' })
])
]
}
}
}
function throttle (fn, limit) {
if ( limit === void 0 ) limit = 250;
var wait = false;
return function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
if (wait) {
return
}
wait = true;
fn.apply(this, args);
setTimeout(function () {
wait = false;
}, limit);
}
}
function clone (data) {
var s = JSON.stringify(data);
if (s) {
return JSON.parse(s)
}
}
function rgbToHex (ref) {
var r = ref.r;
var g = ref.g;
var b = ref.b;
var a = ref.a;
var alpha = a !== void 0;
r = Math.round(r);
g = Math.round(g);
b = Math.round(b);
if (
r > 255 ||
g > 255 ||
b > 255 ||
(alpha && a > 100)
) {
throw new TypeError('Expected 3 numbers below 256 (and optionally one below 100)')
}
a = alpha
? (Math.round(255 * a / 100) | 1 << 8).toString(16).slice(1)
: '';
return '#' + ((b | g << 8 | r << 16) | 1 << 24).toString(16).slice(1) + a
}
function hexToRgb (hex) {
if (typeof hex !== 'string') {
throw new TypeError('Expected a string')
}
hex = hex.replace(/^#/, '');
if (hex.length === 3) {
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
}
else if (hex.length === 4) {
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2] + hex[3] + hex[3];
}
var num = parseInt(hex, 16);
return hex.length > 6
? {r: num >> 24 & 255, g: num >> 16 & 255, b: num >> 8 & 255, a: Math.round((num & 255) / 2.55)}
: {r: num >> 16, g: num >> 8 & 255, b: num & 255}
}
function hsvToRgb (ref) {
var h = ref.h;
var s = ref.s;
var v = ref.v;
var a = ref.a;
var r, g, b, i, f, p, q, t;
s = s / 100;
v = v / 100;
h = h / 360;
i = Math.floor(h * 6);
f = h * 6 - i;
p = v * (1 - s);
q = v * (1 - f * s);
t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0:
r = v;
g = t;
b = p;
break
case 1:
r = q;
g = v;
b = p;
break
case 2:
r = p;
g = v;
b = t;
break
case 3:
r = p;
g = q;
b = v;
break
case 4:
r = t;
g = p;
b = v;
break
case 5:
r = v;
g = p;
b = q;
break
}
return {
r: Math.round(r * 255),
g: Math.round(g * 255),
b: Math.round(b * 255),
a: a
}
}
function rgbToHsv (ref) {
var r = ref.r;
var g = ref.g;
var b = ref.b;
var a = ref.a;
var
max = Math.max(r, g, b), min = Math.min(r, g, b),
d = max - min,
h,
s = (max === 0 ? 0 : d / max),
v = max / 255;
switch (max) {
case min:
h = 0;
break
case r:
h = (g - b) + d * (g < b ? 6 : 0);
h /= 6 * d;
break
case g:
h = (b - r) + d * 2;
h /= 6 * d;
break
case b:
h = (r - g) + d * 4;
h /= 6 * d;
break
}
return {
h: Math.round(h * 360),
s: Math.round(s * 100),
v: Math.round(v * 100),
a: a
}
}
var colors = Object.freeze({
rgbToHex: rgbToHex,
hexToRgb: hexToRgb,
hsvToRgb: hsvToRgb,
rgbToHsv: rgbToHsv
});
var QColorPicker = {
name: 'q-color-picker',
mixins: [FieldParentMixin],
directives: {
TouchPan: TouchPan
},
props: {
value: {
type: [String, Object],
required: true
},
color: {
type: String,
default: 'primary'
},
disable: Boolean,
readonly: Boolean
},
data: function data () {
return {
view: !this.value || typeof this.value === 'string' ? 'hex' : 'rgb',
model: this.__parseModel(this.value),
inputError: {
hex: false,
r: false,
g: false,
b: false
}
}
},
watch: {
value: {
handler: function handler (v) {
var model = this.__parseModel(v);
if (model.hex !== this.model.hex) {
this.model = model;
}
},
deep: true
}
},
computed: {
isHex: function isHex () {
return typeof this.value === 'string'
},
isRgb: function isRgb () {
return !this.isHex
},
editable: function editable () {
return !this.disable && !this.readonly
},
hasAlpha: function hasAlpha () {
return this.isHex
? this.value.length > 7
: this.value.a !== void 0
},
swatchStyle: function swatchStyle () {
return {
backgroundColor: ("rgba(" + (this.model.r) + "," + (this.model.g) + "," + (this.model.b) + "," + (this.model.a / 100) + ")")
}
},
saturationStyle: function saturationStyle () {
return {
background: ("hsl(" + (this.model.h) + ",100%,50%)")
}
},
saturationPointerStyle: function saturationPointerStyle () {
return {
top: ((101 - this.model.v) + "%"),
left: ((this.model.s) + "%")
}
},
inputsArray: function inputsArray () {
var inp = ['r', 'g', 'b'];
if (this.hasAlpha) {
inp.push('a');
}
return inp
},
rgbColor: function rgbColor () {
return ("rgb(" + (this.model.r) + "," + (this.model.g) + "," + (this.model.b) + ")")
}
},
created: function created () {
this.__saturationChange = throttle(this.__saturationChange, 20);
},
render: function render (h) {
return h('div', {
staticClass: 'q-color',
'class': { disabled: this.disable }
}, [
this.__getSaturation(h),
this.__getSliders(h),
this.__getInputs(h)
])
},
methods: {
__getSaturation: function __getSaturation (h) {
return h('div', {
ref: 'saturation',
staticClass: 'q-color-saturation non-selectable relative-position overflow-hidden cursor-pointer',
style: this.saturationStyle,
'class': { readonly: !this.editable },
on: this.editable
? { click: this.__saturationClick }
: null,
directives: this.editable
? [{
name: 'touch-pan',
value: this.__saturationPan
}]
: null
}, [
h('div', { staticClass: 'q-color-saturation-white absolute-full' }),
h('div', { staticClass: 'q-color-saturation-black absolute-full' }),
h('div', {
staticClass: 'absolute',
style: this.saturationPointerStyle
}, [
h('div', { staticClass: 'q-color-saturation-circle' })
])
])
},
__getSliders: function __getSliders (h) {
var this$1 = this;
return h('div', {
staticClass: 'q-color-sliders row items-center'
}, [
h('div', {
staticClass: 'q-color-swatch q-mt-sm q-ml-sm q-mb-sm non-selectable overflow-hidden',
style: this.swatchStyle
}),
h('div', { staticClass: 'col q-pa-sm' }, [
h('div', { staticClass: 'q-color-hue non-selectable' }, [
h(QSlider, {
props: {
value: this.model.h,
color: 'white',
min: 0,
max: 360,
fillHandleAlways: true,
readonly: !this.editable
},
on: {
input: this.__onHueChange,
dragend: function (val) { return this$1.__onHueChange(val, true); }
}
})
]),
this.hasAlpha
? h('div', { staticClass: 'q-color-alpha non-selectable' }, [
h(QSlider, {
props: {
value: this.model.a,
color: 'white',
min: 0,
max: 100,
fillHandleAlways: true,
readonly: !this.editable
},
on: {
input: function (value) { return this$1.__onNumericChange({ target: { value: value } }, 'a', 100); },
dragend: function (value) { return this$1.__onNumericChange({ target: { value: value } }, 'a', 100, true); }
}
})
])
: null
])
])
},
__getNumericInputs: function __getNumericInputs (h) {
var this$1 = this;
return this.inputsArray.map(function (type) {
var max = type === 'a' ? 100 : 255;
return h('div', { staticClass: 'col q-color-padding' }, [
h('input', {
attrs: {
type: 'number',
min: 0,
max: max,
readonly: !this$1.editable
},
staticClass: 'full-width text-center q-no-input-spinner',
domProps: {
value: Math.round(this$1.model[type])
},
on: {
input: function (evt) {
this$1.__onNumericChange(evt, type, max);
},
blur: function (evt) {
this$1.__onNumericChange(evt, type, max, true);
}
}
}),
h('div', { staticClass: 'q-color-label text-center uppercase' }, [
type
])
])
})
},
__getInputs: function __getInputs (h) {
var this$1 = this;
var inputs = this.view === 'hex'
? [
h('div', { staticClass: 'col' }, [
h('input', {
domProps: { value: this.model.hex },
attrs: {
readonly: !this.editable,
tabindex: this.editable ? 0 : -1
},
on: {
input: this.__onHexChange,
blur: function (evt) { return this$1.__onHexChange(evt, true); }
},
staticClass: 'full-width text-center uppercase'
}),
h('div', { staticClass: 'q-color-label text-center' }, [
("HEX" + (this.hasAlpha ? ' / A' : ''))
])
])
]
: this.__getNumericInputs(h);
return h('div', {
staticClass: 'q-color-inputs row items-center q-px-sm q-pb-sm'
}, [
h('div', { staticClass: 'col q-mr-sm row no-wrap' }, inputs),
h('div', [
h(QBtn, {
props: {
flat: true,
color: 'grey-7'
},
on: {
click: this.__nextInputView
},
staticClass: 'q-pa-none'
}, [
h('svg', {
attrs: {
viewBox: '0 0 24 24'
},
style: {width: '24px', height: '24px'}
}, [
h('path', {
attrs: {
fill: 'currentColor',
d: 'M12,18.17L8.83,15L7.42,16.41L12,21L16.59,16.41L15.17,15M12,5.83L15.17,9L16.58,7.59L12,3L7.41,7.59L8.83,9L12,5.83Z'
}
})
])
])
])
])
},
__onSaturationChange: function __onSaturationChange (left, top, change) {
var
panel = this.$refs.saturation,
width = panel.clientWidth,
height = panel.clientHeight,
rect = panel.getBoundingClientRect(),
x = Math.min(width, Math.max(0, left - rect.left)),
y = Math.min(height, Math.max(0, top - rect.top)),
s = Math.round(100 * x / width),
v = Math.round(100 * Math.max(0, Math.min(1, -(y / height) + 1))),
rgb = hsvToRgb({
h: this.model.h,
s: s,
v: v,
a: this.hasAlpha ? this.model.a : void 0
});
this.model.s = s;
this.model.v = v;
this.__update(rgb, rgbToHex(rgb), change);
},
__onHueChange: function __onHueChange (h, change) {
h = Math.round(h);
var val = hsvToRgb({
h: h,
s: this.model.s,
v: this.model.v,
a: this.hasAlpha ? this.model.a : void 0
});
this.model.h = h;
this.__update(val, rgbToHex(val), change);
},
__onNumericChange: function __onNumericChange (evt, type, max, change) {
var val = Number(evt.target.value);
if (isNaN(val)) {
return
}
val = Math.floor(val);
if (val < 0 || val > max) {
if (change) {
this.$forceUpdate();
}
return
}
var rgb = {
r: type === 'r' ? val : this.model.r,
g: type === 'g' ? val : this.model.g,
b: type === 'b' ? val : this.model.b,
a: this.hasAlpha
? (type === 'a' ? val : this.model.a)
: void 0
};
if (type !== 'a') {
var hsv = rgbToHsv(rgb);
this.model.h = hsv.h;
this.model.s = hsv.s;
this.model.v = hsv.v;
}
this.__update(rgb, rgbToHex(rgb), change);
},
__onHexChange: function __onHexChange (evt, change) {
var
hex = evt.target.value,
len = hex.length,
edges = this.hasAlpha ? [5, 9] : [4, 7];
if (len !== edges[0] && len !== edges[1]) {
if (change) {
this.$forceUpdate();
}
return
}
var
rgb = hexToRgb(hex),
hsv = rgbToHsv(rgb);
this.model.h = hsv.h;
this.model.s = hsv.s;
this.model.v = hsv.v;
this.__update(rgb, hex, change);
},
__update: function __update (rgb, hex, change) {
var this$1 = this;
var value = this.isHex ? hex : rgb;
// update internally
this.model.hex = hex;
this.model.r = rgb.r;
this.model.g = rgb.g;
this.model.b = rgb.b;
if (this.hasAlpha) {
this.model.a = rgb.a;
}
// emit new value
this.$emit('input', value);
this.$nextTick(function () {
if (change && JSON.stringify(value) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', value);
}
});
},
__nextInputView: function __nextInputView () {
this.view = this.view === 'hex' ? 'rgba' : 'hex';
},
__parseModel: function __parseModel (v) {
var model;
if (typeof v === 'string') {
model = hexToRgb(v);
model.hex = v;
}
else {
model = clone(v);
model.hex = rgbToHex(v);
}
return extend({ a: 100 }, model, rgbToHsv(model))
},
__saturationPan: function __saturationPan (evt) {
if (evt.isFinal) {
this.__dragStop(evt);
}
else if (evt.isFirst) {
this.__dragStart(evt);
}
else {
this.__dragMove(evt);
}
},
__dragStart: function __dragStart (event) {
stopAndPrevent(event.evt);
this.saturationDragging = true;
this.__saturationChange(event);
},
__dragMove: function __dragMove (event) {
if (!this.saturationDragging) {
return
}
stopAndPrevent(event.evt);
this.__saturationChange(event);
},
__dragStop: function __dragStop (event) {
var this$1 = this;
stopAndPrevent(event.evt);
setTimeout(function () {
this$1.saturationDragging = false;
}, 100);
this.__onSaturationChange(
event.position.left,
event.position.top,
true
);
},
__saturationChange: function __saturationChange (evt) {
this.__onSaturationChange(
evt.position.left,
evt.position.top
);
},
__saturationClick: function __saturationClick (evt) {
if (this.saturationDragging) {
return
}
this.__onSaturationChange(
evt.pageX - window.pageXOffset,
evt.pageY - window.pageYOffset,
true
);
}
}
}
var contentCss = {
maxWidth: '95vw',
maxHeight: '98vh'
};
var QColor = {
name: 'q-color',
mixins: [FrameMixin, DisplayModeMixin],
props: {
value: {
required: true
},
color: {
type: String,
default: 'primary'
},
defaultSelection: {
type: [String, Object],
default: '#000000'
},
displayValue: String,
placeholder: String,
clearable: Boolean,
okLabel: String,
cancelLabel: String,
disable: Boolean,
readonly: Boolean
},
data: function data () {
var data = this.isPopover ? {} : {
transition: 'q-modal'
};
data.focused = false;
data.model = clone(this.value || this.defaultSelection);
return data
},
computed: {
actualValue: function actualValue () {
if (this.displayValue) {
return this.displayValue
}
if (!this.value) {
return this.placeholder || ''
}
if (this.value) {
return typeof this.value === 'string'
? this.value
: ("rgb" + (this.value.a !== void 0 ? 'a' : '') + "(" + (this.value.r) + "," + (this.value.g) + "," + (this.value.b) + (this.value.a !== void 0 ? ("," + (this.value.a / 100)) : '') + ")")
}
}
},
methods: {
toggle: function toggle () {
this[this.$refs.popup.showing ? 'hide' : 'show']();
},
show: function show () {
if (!this.disable) {
if (!this.focused) {
this.__setModel(this.value);
}
return this.$refs.popup.show()
}
},
hide: function hide () {
this.focused = false;
return this.$refs.popup.hide()
},
__handleKey: function __handleKey (e) {
// ENTER key
if (e.which === 13 || e.keyCode === 13) {
this.show();
}
// Backspace key
else if (e.which === 8 || e.keyCode === 8) {
if (this.editable && this.clearable && this.actualValue.length) {
this.clear();
}
}
},
__onFocus: function __onFocus () {
if (this.focused) {
return
}
this.__setModel(this.value);
this.focused = true;
this.$emit('focus');
},
__onBlur: function __onBlur (e) {
var this$1 = this;
this.__onHide();
setTimeout(function () {
var el = document.activeElement;
if (el !== document.body && !this$1.$refs.popup.$el.contains(el)) {
this$1.hide();
}
}, 1);
},
__onHide: function __onHide () {
this.focused = false;
this.$emit('blur');
if (this.isPopover && !this.$refs.popup.showing) {
this.__update(true);
}
},
__setModel: function __setModel (val, forceUpdate) {
this.model = clone(val || this.defaultSelection);
if (forceUpdate || (this.isPopover && this.$refs.popup.showing)) {
this.__update();
}
},
__update: function __update (change) {
var this$1 = this;
this.$nextTick(function () {
this$1.$emit('input', this$1.model);
this$1.$nextTick(function () {
if (change && JSON.stringify(this$1.model) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', this$1.model);
}
});
});
},
__getPicker: function __getPicker (h, modal) {
var this$1 = this;
var child = [
h(QColorPicker, {
staticClass: ("no-border" + (modal ? ' full-width' : '')),
props: extend({
color: this.color,
value: this.model,
disable: this.disable,
readonly: this.readonly
}, this.$attrs),
on: {
input: function (v) { return this$1.$nextTick(function () { return this$1.__setModel(v); }); }
}
})
];
if (modal) {
child['push'](h('div', {
staticClass: 'modal-buttons modal-buttons-top row full-width'
}, [
h('div', { staticClass: 'col' }),
h(QBtn, {
props: {
color: this.color,
flat: true,
label: this.cancelLabel || this.$q.i18n.label.cancel,
waitForRipple: true,
dense: true
},
on: { click: this.hide }
}),
this.editable
? h(QBtn, {
props: {
color: this.color,
flat: true,
label: this.okLabel || this.$q.i18n.label.set,
waitForRipple: true,
dense: true
},
on: {
click: function () {
this$1.hide();
this$1.__update(true);
}
}
})
: null
]));
}
return child
}
},
render: function render (h) {
return h(QInputFrame, {
props: {
prefix: this.prefix,
suffix: this.suffix,
stackLabel: this.stackLabel,
floatLabel: this.floatLabel,
error: this.error,
warning: this.warning,
disable: this.disable,
inverted: this.inverted,
dark: this.dark,
hideUnderline: this.hideUnderline,
before: this.before,
after: this.after,
color: this.color,
focused: this.focused,
focusable: true,
length: this.actualValue.length
},
nativeOn: {
click: this.toggle,
focus: this.__onFocus,
blur: this.__onBlur,
keydown: this.__handleKey
}
}, [
h('div', {
staticClass: 'col row items-center q-input-target',
'class': this.alignClass,
domProps: {
innerHTML: this.actualValue
}
}),
this.isPopover
? h(QPopover, {
ref: 'popup',
props: {
offset: [0, 10],
disable: this.disable,
anchorClick: false,
maxHeight: '100vh'
},
on: {
show: this.__onFocus,
hide: this.__onHide
}
}, this.__getPicker(h))
: h(QModal, {
ref: 'popup',
staticClass: 'with-backdrop',
props: {
contentCss: contentCss,
minimized: "mat" === 'mat',
position: null,
transition: this.transition
},
on: {
show: this.__onFocus,
hide: this.__onHide
}
}, this.__getPicker(h, true)),
this.editable && this.clearable && this.actualValue.length
? h('q-icon', {
slot: 'after',
props: { name: this.$q.icon.input.clear },
nativeOn: { click: this.clear },
staticClass: 'q-if-control'
})
: null,
h('q-icon', {
slot: 'after',
props: { name: this.$q.icon.input.dropdown },
staticClass: 'q-if-control'
})
])
}
}
var ContextMenuDesktop = {
name: 'q-context-menu',
components: {
QPopover: QPopover
},
props: {
disable: Boolean
},
render: function render (h) {
var this$1 = this;
return h(QPopover, {
ref: 'popover',
props: {
anchorClick: false
},
on: {
show: function () { this$1.$emit('show'); },
hide: function () { this$1.$emit('hide'); }
}
}, this.$slots.default)
},
methods: {
hide: function hide () {
return this.$refs.popover.hide()
},
__show: function __show (evt) {
var this$1 = this;
if (!evt || this.disable) {
return
}
this.hide();
stopAndPrevent(evt);
/*
Opening with a timeout for
Firefox workaround
*/
setTimeout(function () {
this$1.$refs.popover.show(evt);
}, 100);
}
},
mounted: function mounted () {
this.target = this.$refs.popover.$el.parentNode;
this.target.addEventListener('contextmenu', this.__show);
this.target.addEventListener('click', this.hide);
},
beforeDestroy: function beforeDestroy () {
this.target.removeEventListener('contexmenu', this.__show);
this.target.removeEventListener('click', this.hide);
}
}
var ContextMenuMobile = {
name: 'q-context-menu',
props: {
disable: Boolean
},
methods: {
hide: function hide () {
this.target.classList.remove('non-selectable');
return this.$refs.dialog.hide()
},
__show: function __show () {
if (!this.disable && this.$refs.dialog) {
this.$refs.dialog.show();
}
},
__touchStartHandler: function __touchStartHandler (evt) {
var this$1 = this;
this.target.classList.add('non-selectable');
this.touchTimer = setTimeout(function () {
stopAndPrevent(evt);
setTimeout(function () {
this$1.__cleanup();
this$1.__show();
}, 10);
}, 600);
},
__cleanup: function __cleanup () {
this.target.classList.remove('non-selectable');
clearTimeout(this.touchTimer);
}
},
render: function render (h) {
var this$1 = this;
return h(QModal, {
ref: 'dialog',
props: {
minimized: true
},
on: {
show: function () { this$1.$emit('show'); },
hide: function () { this$1.$emit('hide'); }
}
}, this.$slots.default)
},
mounted: function mounted () {
var this$1 = this;
this.$nextTick(function () {
this$1.target = this$1.$el.parentNode;
this$1.target.addEventListener('touchstart', this$1.__touchStartHandler)
;['touchcancel', 'touchmove', 'touchend'].forEach(function (evt) {
this$1.target.addEventListener(evt, this$1.__cleanup);
});
});
},
beforeDestroy: function beforeDestroy () {
var this$1 = this;
this.target.removeEventListener('touchstart', this.__touchStartHandler)
;['touchcancel', 'touchmove', 'touchend'].forEach(function (evt) {
this$1.target.removeEventListener(evt, this$1.__cleanup);
});
}
}
var QContextMenu = {
name: 'q-context-menu',
functional: true,
render: function render (h, ctx) {
return h(
Platform.is.mobile ? ContextMenuMobile : ContextMenuDesktop,
ctx.data,
ctx.children
)
}
}
var modelValidator = function (v) {
var type = typeof v;
return (
v === null || v === undefined ||
type === 'number' || type === 'string' ||
isDate(v)
)
};
var inline = {
value: {
validator: modelValidator,
required: true
},
type: {
type: String,
default: 'date',
validator: function validator (value) {
return ['date', 'time', 'datetime'].includes(value)
}
},
color: {
type: String,
default: 'primary'
},
min: {
validator: modelValidator,
default: null
},
max: {
validator: modelValidator,
default: null
},
firstDayOfWeek: Number,
format24h: {
type: [Boolean, Number],
default: 0,
validator: function (v) { return [true, false, 0].includes(v); }
},
defaultView: {
type: String,
validator: function (v) { return ['year', 'month', 'day', 'hour', 'minute'].includes(v); }
}
};
var input = {
format: String,
placeholder: String,
clearable: Boolean,
okLabel: String,
cancelLabel: String,
defaultSelection: {
type: [String, Number, Date],
default: null
},
displayValue: String,
disable: Boolean,
readonly: Boolean
};
/* eslint no-fallthrough: 0 */
var MILLISECONDS_IN_DAY = 86400000;
var MILLISECONDS_IN_HOUR = 3600000;
var MILLISECONDS_IN_MINUTE = 60000;
var token = /\[((?:[^\]\\]|\\]|\\)*)\]|d{1,4}|M{1,4}|m{1,2}|w{1,2}|Qo|Do|D{1,4}|YY(?:YY)?|H{1,2}|h{1,2}|s{1,2}|S{1,3}|Z{1,2}|a{1,2}|[AQExX]/g;
function formatTimezone (offset, delimeter) {
if ( delimeter === void 0 ) delimeter = '';
var
sign = offset > 0 ? '-' : '+',
absOffset = Math.abs(offset),
hours = Math.floor(absOffset / 60),
minutes = absOffset % 60;
return sign + pad(hours) + delimeter + pad(minutes)
}
function setMonth (date, newMonth /* 1-based */) {
var
test = new Date(date.getFullYear(), newMonth, 0, 0, 0, 0, 0),
days = test.getDate();
date.setMonth(newMonth - 1, Math.min(days, date.getDate()));
}
function getChange (date, mod, add) {
var
t = new Date(date),
sign = (add ? 1 : -1);
Object.keys(mod).forEach(function (key) {
if (key === 'month') {
setMonth(t, t.getMonth() + 1 + sign * mod.month);
return
}
var op = key === 'year'
? 'FullYear'
: capitalize(key === 'days' ? 'date' : key);
t[("set" + op)](t[("get" + op)]() + sign * mod[key]);
});
return t
}
function isValid (date) {
var t = Date.parse(date);
return isNaN(t) === false
}
function buildDate (mod, utc) {
return adjustDate(new Date(), mod, utc)
}
function getDayOfWeek (date) {
var dow = new Date(date).getDay();
return dow === 0 ? 7 : dow
}
function getWeekOfYear (date) {
// Remove time components of date
var thursday = new Date(date.getFullYear(), date.getMonth(), date.getDate());
// Change date to Thursday same week
thursday.setDate(thursday.getDate() - ((thursday.getDay() + 6) % 7) + 3);
// Take January 4th as it is always in week 1 (see ISO 8601)
var firstThursday = new Date(thursday.getFullYear(), 0, 4);
// Change date to Thursday same week
firstThursday.setDate(firstThursday.getDate() - ((firstThursday.getDay() + 6) % 7) + 3);
// Check if daylight-saving-time-switch occurred and correct for it
var ds = thursday.getTimezoneOffset() - firstThursday.getTimezoneOffset();
thursday.setHours(thursday.getHours() - ds);
// Number of weeks between target Thursday and first Thursday
var weekDiff = (thursday - firstThursday) / (MILLISECONDS_IN_DAY * 7);
return 1 + Math.floor(weekDiff)
}
function isBetweenDates (date, from, to) {
var
d1 = new Date(from).getTime(),
d2 = new Date(to).getTime(),
cur = new Date(date).getTime();
return cur > d1 && cur < d2
}
function addToDate (date, mod) {
return getChange(date, mod, true)
}
function subtractFromDate (date, mod) {
return getChange(date, mod, false)
}
function adjustDate (date, mod, utc) {
var
t = new Date(date),
prefix = "set" + (utc ? 'UTC' : '');
Object.keys(mod).forEach(function (key) {
if (key === 'month') {
setMonth(t, mod.month);
return
}
var op = key === 'year'
? 'FullYear'
: key.charAt(0).toUpperCase() + key.slice(1);
t[("" + prefix + op)](mod[key]);
});
return t
}
function startOfDate (date, unit) {
var t = new Date(date);
switch (unit) {
case 'year':
t.setMonth(0);
case 'month':
t.setDate(1);
case 'day':
t.setHours(0);
case 'hour':
t.setMinutes(0);
case 'minute':
t.setSeconds(0);
case 'second':
t.setMilliseconds(0);
}
return t
}
function endOfDate (date, unit) {
var t = new Date(date);
switch (unit) {
case 'year':
t.setMonth(11);
case 'month':
t.setDate(daysInMonth(date));
case 'day':
t.setHours(23);
case 'hour':
t.setMinutes(59);
case 'minute':
t.setSeconds(59);
case 'second':
t.setMilliseconds(59);
}
return t
}
function getMaxDate (date) {
var args = [], len = arguments.length - 1;
while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ];
var t = new Date(date);
args.forEach(function (d) {
t = Math.max(t, new Date(d));
});
return t
}
function getMinDate (date) {
var args = [], len = arguments.length - 1;
while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ];
var t = new Date(date);
args.forEach(function (d) {
t = Math.min(t, new Date(d));
});
return t
}
function getDiff (t, sub, interval) {
return (
(t.getTime() - t.getTimezoneOffset() * MILLISECONDS_IN_MINUTE) -
(sub.getTime() - sub.getTimezoneOffset() * MILLISECONDS_IN_MINUTE)
) / interval
}
function getDateDiff (date, subtract, unit) {
if ( unit === void 0 ) unit = 'days';
var
t = new Date(date),
sub = new Date(subtract);
switch (unit) {
case 'years':
return (t.getFullYear() - sub.getFullYear())
case 'months':
return (t.getFullYear() - sub.getFullYear()) * 12 + t.getMonth() - sub.getMonth()
case 'days':
return getDiff(startOfDate(t, 'day'), startOfDate(sub, 'day'), MILLISECONDS_IN_DAY)
case 'hours':
return getDiff(startOfDate(t, 'hour'), startOfDate(sub, 'hour'), MILLISECONDS_IN_HOUR)
case 'minutes':
return getDiff(startOfDate(t, 'minute'), startOfDate(sub, 'minute'), MILLISECONDS_IN_MINUTE)
case 'seconds':
return getDiff(startOfDate(t, 'second'), startOfDate(sub, 'second'), 1000)
}
}
function getDayOfYear (date) {
return getDateDiff(date, startOfDate(date, 'year'), 'days') + 1
}
function convertDateToFormat (date, example) {
if (!date) {
return
}
if (isDate(example)) {
return date
}
if (typeof example === 'number') {
return date.getTime()
}
return formatDate(date)
}
function getDateBetween (date, min, max) {
var t = new Date(date);
if (min) {
var low = new Date(min);
if (t < low) {
return low
}
}
if (max) {
var high = new Date(max);
if (t > high) {
return high
}
}
return t
}
function isSameDate (date, date2, unit) {
var
t = new Date(date),
d = new Date(date2);
if (unit === void 0) {
return t.getTime() === d.getTime()
}
switch (unit) {
case 'second':
if (t.getUTCSeconds() !== d.getUTCSeconds()) {
return false
}
case 'minute': // intentional fall-through
if (t.getUTCMinutes() !== d.getUTCMinutes()) {
return false
}
case 'hour': // intentional fall-through
if (t.getUTCHours() !== d.getUTCHours()) {
return false
}
case 'day': // intentional fall-through
if (t.getUTCDate() !== d.getUTCDate()) {
return false
}
case 'month': // intentional fall-through
if (t.getUTCMonth() !== d.getUTCMonth()) {
return false
}
case 'year': // intentional fall-through
if (t.getUTCFullYear() !== d.getUTCFullYear()) {
return false
}
break
default:
throw new Error(("date isSameDate unknown unit " + unit))
}
return true
}
function daysInMonth (date) {
return (new Date(date.getFullYear(), date.getMonth() + 1, 0)).getDate()
}
function getOrdinal (n) {
if (n >= 11 && n <= 13) {
return (n + "th")
}
switch (n % 10) {
case 1: return (n + "st")
case 2: return (n + "nd")
case 3: return (n + "rd")
}
return (n + "th")
}
var formatter = {
// Year: 00, 01, ..., 99
YY: function YY (date) {
return pad(date.getFullYear(), 4).substr(2)
},
// Year: 1900, 1901, ..., 2099
YYYY: function YYYY (date) {
return pad(date.getFullYear(), 4)
},
// Month: 1, 2, ..., 12
M: function M (date) {
return date.getMonth() + 1
},
// Month: 01, 02, ..., 12
MM: function MM (date) {
return pad(date.getMonth() + 1)
},
// Month Short Name: Jan, Feb, ...
MMM: function MMM (date) {
return i18n.lang.date.monthsShort[date.getMonth()]
},
// Month Name: January, February, ...
MMMM: function MMMM (date) {
return i18n.lang.date.months[date.getMonth()]
},
// Quarter: 1, 2, 3, 4
Q: function Q (date) {
return Math.ceil((date.getMonth() + 1) / 3)
},
// Quarter: 1st, 2nd, 3rd, 4th
Qo: function Qo (date) {
return getOrdinal(this.Q(date))
},
// Day of month: 1, 2, ..., 31
D: function D (date) {
return date.getDate()
},
// Day of month: 1st, 2nd, ..., 31st
Do: function Do (date) {
return getOrdinal(date.getDate())
},
// Day of month: 01, 02, ..., 31
DD: function DD (date) {
return pad(date.getDate())
},
// Day of year: 1, 2, ..., 366
DDD: function DDD (date) {
return getDayOfYear(date)
},
// Day of year: 001, 002, ..., 366
DDDD: function DDDD (date) {
return pad(getDayOfYear(date), 3)
},
// Day of week: 0, 1, ..., 6
d: function d (date) {
return date.getDay()
},
// Day of week: Su, Mo, ...
dd: function dd (date) {
return this.dddd(date).slice(0, 2)
},
// Day of week: Sun, Mon, ...
ddd: function ddd (date) {
return i18n.lang.date.daysShort[date.getDay()]
},
// Day of week: Sunday, Monday, ...
dddd: function dddd (date) {
return i18n.lang.date.days[date.getDay()]
},
// Day of ISO week: 1, 2, ..., 7
E: function E (date) {
return date.getDay() || 7
},
// Week of Year: 1 2 ... 52 53
w: function w (date) {
return getWeekOfYear(date)
},
// Week of Year: 01 02 ... 52 53
ww: function ww (date) {
return pad(getWeekOfYear(date))
},
// Hour: 0, 1, ... 23
H: function H (date) {
return date.getHours()
},
// Hour: 00, 01, ..., 23
HH: function HH (date) {
return pad(date.getHours())
},
// Hour: 1, 2, ..., 12
h: function h (date) {
var hours = date.getHours();
if (hours === 0) {
return 12
}
if (hours > 12) {
return hours % 12
}
return hours
},
// Hour: 01, 02, ..., 12
hh: function hh (date) {
return pad(this.h(date))
},
// Minute: 0, 1, ..., 59
m: function m (date) {
return date.getMinutes()
},
// Minute: 00, 01, ..., 59
mm: function mm (date) {
return pad(date.getMinutes())
},
// Second: 0, 1, ..., 59
s: function s (date) {
return date.getSeconds()
},
// Second: 00, 01, ..., 59
ss: function ss (date) {
return pad(date.getSeconds())
},
// 1/10 of second: 0, 1, ..., 9
S: function S (date) {
return Math.floor(date.getMilliseconds() / 100)
},
// 1/100 of second: 00, 01, ..., 99
SS: function SS (date) {
return pad(Math.floor(date.getMilliseconds() / 10))
},
// Millisecond: 000, 001, ..., 999
SSS: function SSS (date) {
return pad(date.getMilliseconds(), 3)
},
// Meridiem: AM, PM
A: function A (date) {
return this.H(date) < 12 ? 'AM' : 'PM'
},
// Meridiem: am, pm
a: function a (date) {
return this.H(date) < 12 ? 'am' : 'pm'
},
// Meridiem: a.m., p.m
aa: function aa (date) {
return this.H(date) < 12 ? 'a.m.' : 'p.m.'
},
// Timezone: -01:00, +00:00, ... +12:00
Z: function Z (date) {
return formatTimezone(date.getTimezoneOffset(), ':')
},
// Timezone: -0100, +0000, ... +1200
ZZ: function ZZ (date) {
return formatTimezone(date.getTimezoneOffset())
},
// Seconds timestamp: 512969520
X: function X (date) {
return Math.floor(date.getTime() / 1000)
},
// Milliseconds timestamp: 512969520900
x: function x (date) {
return date.getTime()
}
};
function formatDate (val, mask) {
if ( mask === void 0 ) mask = 'YYYY-MM-DDTHH:mm:ss.SSSZ';
if (val !== 0 && !val) {
return
}
var date = new Date(val);
return mask.replace(token, function (match, text) {
if (match in formatter) {
return formatter[match](date)
}
return text === void 0
? match
: text.split('\\]').join(']')
})
}
function matchFormat (format) {
if ( format === void 0 ) format = '';
return format.match(token)
}
var date = Object.freeze({
isValid: isValid,
buildDate: buildDate,
getDayOfWeek: getDayOfWeek,
getWeekOfYear: getWeekOfYear,
isBetweenDates: isBetweenDates,
addToDate: addToDate,
subtractFromDate: subtractFromDate,
adjustDate: adjustDate,
startOfDate: startOfDate,
endOfDate: endOfDate,
getMaxDate: getMaxDate,
getMinDate: getMinDate,
getDateDiff: getDateDiff,
getDayOfYear: getDayOfYear,
convertDateToFormat: convertDateToFormat,
getDateBetween: getDateBetween,
isSameDate: isSameDate,
daysInMonth: daysInMonth,
formatter: formatter,
formatDate: formatDate,
matchFormat: matchFormat
});
var DateMixin = {
props: inline,
computed: {
model: {
get: function get () {
var date = isValid(this.value)
? new Date(this.value)
: (this.defaultSelection ? new Date(this.defaultSelection) : startOfDate(new Date(), 'day'));
return getDateBetween(
date,
this.pmin,
this.pmax
)
},
set: function set (val) {
var this$1 = this;
var date = getDateBetween(val, this.pmin, this.pmax);
var value = convertDateToFormat(date, this.value);
this.$emit('input', value);
this.$nextTick(function () {
if (!isSameDate(value, this$1.value)) {
this$1.$emit('change', value);
}
});
}
},
pmin: function pmin () {
return this.min ? new Date(this.min) : null
},
pmax: function pmax () {
return this.max ? new Date(this.max) : null
},
typeHasDate: function typeHasDate () {
return this.type === 'date' || this.type === 'datetime'
},
typeHasTime: function typeHasTime () {
return this.type === 'time' || this.type === 'datetime'
},
year: function year () {
return this.model.getFullYear()
},
month: function month () {
return this.model.getMonth() + 1
},
day: function day () {
return this.model.getDate()
},
minute: function minute () {
return this.model.getMinutes()
},
yearInterval: function yearInterval () {
var
min = this.pmin !== null ? this.pmin.getFullYear() : 1950,
max = this.pmax !== null ? this.pmax.getFullYear() : 2050;
return Math.max(1, max - min + 1)
},
yearMin: function yearMin () {
return this.pmin !== null ? this.pmin.getFullYear() - 1 : 1949
},
monthInterval: function monthInterval () {
var
min = this.pmin !== null && this.pmin.getFullYear() === this.model.getFullYear() ? this.pmin.getMonth() : 0,
max = this.pmax !== null && this.pmax.getFullYear() === this.model.getFullYear() ? this.pmax.getMonth() : 11;
return Math.max(1, max - min + 1)
},
monthMin: function monthMin () {
return this.pmin !== null && this.pmin.getFullYear() === this.model.getFullYear()
? this.pmin.getMonth()
: 0
},
daysInMonth: function daysInMonth$$1 () {
return (new Date(this.model.getFullYear(), this.model.getMonth() + 1, 0)).getDate()
},
editable: function editable () {
return !this.disable && !this.readonly
}
},
methods: {
toggleAmPm: function toggleAmPm () {
if (!this.editable) {
return
}
var
hour = this.model.getHours(),
offset = this.am ? 12 : -12;
this.model = new Date(this.model.setHours(hour + offset));
},
__parseTypeValue: function __parseTypeValue (type, value) {
if (type === 'month') {
return between(value, 1, 12)
}
if (type === 'date') {
return between(value, 1, this.daysInMonth)
}
if (type === 'year') {
var
min = this.pmin ? this.pmin.getFullYear() : 1950,
max = this.pmax ? this.pmax.getFullYear() : 2050;
return between(value, min, max)
}
if (type === 'hour') {
return between(value, 0, 23)
}
if (type === 'minute') {
return between(value, 0, 59)
}
}
}
}
function convertToAmPm (hour) {
return hour === 0 ? 12 : (hour >= 13 ? hour - 12 : hour)
}
var QDatetimePicker = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"q-datetime inline row",class:_vm.classes},[_c('div',{staticClass:"q-datetime-header column col-xs-12 col-md-4 justify-center"},[(_vm.typeHasDate)?_c('div',[_c('div',{staticClass:"q-datetime-weekdaystring col-12"},[_vm._v(_vm._s(_vm.weekDayString))]),_vm._v(" "),_c('div',{staticClass:"q-datetime-datestring row flex-center"},[_c('span',{staticClass:"q-datetime-link small col-auto col-md-12",class:{active: _vm.view === 'month'},on:{"click":function($event){_vm.view = 'month';}}},[_vm._v(" "+_vm._s(_vm.monthString)+" ")]),_vm._v(" "),_c('span',{staticClass:"q-datetime-link col-auto col-md-12",class:{active: _vm.view === 'day'},on:{"click":function($event){_vm.view = 'day';}}},[_vm._v(" "+_vm._s(_vm.day)+" ")]),_vm._v(" "),_c('span',{staticClass:"q-datetime-link small col-auto col-md-12",class:{active: _vm.view === 'year'},on:{"click":function($event){_vm.view = 'year';}}},[_vm._v(" "+_vm._s(_vm.year)+" ")])])]):_vm._e(),_vm._v(" "),(_vm.typeHasTime)?_c('div',{staticClass:"q-datetime-time row flex-center"},[_c('div',{staticClass:"q-datetime-clockstring col-auto col-md-12"},[_c('span',{staticClass:"q-datetime-link col-auto col-md-12",class:{active: _vm.view === 'hour'},on:{"click":function($event){_vm.view = 'hour';}}},[_vm._v(" "+_vm._s(_vm.__pad(_vm.hour, ' '))+" ")]),_vm._v(" "),_c('span',{staticStyle:{"opacity":"0.6"}},[_vm._v(":")]),_vm._v(" "),_c('span',{staticClass:"q-datetime-link col-auto col-md-12",class:{active: _vm.view === 'minute'},on:{"click":function($event){_vm.view = 'minute';}}},[_vm._v(" "+_vm._s(_vm.__pad(_vm.minute))+" ")])]),_vm._v(" "),(!_vm.computedFormat24h)?_c('div',{staticClass:"q-datetime-ampm column col-auto col-md-12 justify-around"},[_c('div',{staticClass:"q-datetime-link",class:{active: _vm.am},on:{"click":function($event){_vm.toggleAmPm();}}},[_vm._v("AM")]),_vm._v(" "),_c('div',{staticClass:"q-datetime-link",class:{active: !_vm.am},on:{"click":function($event){_vm.toggleAmPm();}}},[_vm._v("PM")])]):_vm._e()]):_vm._e()]),_vm._v(" "),_c('div',{staticClass:"q-datetime-content col-xs-12 col-md-8 column"},[_c('div',{ref:"selector",staticClass:"q-datetime-selector auto row flex-center"},[(_vm.view === 'year')?_c('div',{staticClass:"q-datetime-view-year full-width full-height"},_vm._l((_vm.yearInterval),function(n){return _c('q-btn',{key:("yi" + n),staticClass:"q-datetime-btn full-width",class:{active: n + _vm.yearMin === _vm.year},attrs:{"flat":""},on:{"click":function($event){_vm.setYear(n + _vm.yearMin);}}},[_vm._v(" "+_vm._s(n + _vm.yearMin)+" ")])})):_vm._e(),_vm._v(" "),(_vm.view === 'month')?_c('div',{staticClass:"q-datetime-view-month full-width full-height"},_vm._l((_vm.monthInterval),function(index){return _c('q-btn',{key:("mi" + index),staticClass:"q-datetime-btn full-width",class:{active: _vm.month === index + _vm.monthMin},attrs:{"flat":""},on:{"click":function($event){_vm.setMonth(index + _vm.monthMin, true);}}},[_vm._v(" "+_vm._s(_vm.$q.i18n.date.months[index + _vm.monthMin - 1])+" ")])})):_vm._e(),_vm._v(" "),(_vm.view === 'day')?_c('div',{staticClass:"q-datetime-view-day"},[_c('div',{staticClass:"row items-center content-center"},[_c('q-btn',{attrs:{"round":"","dense":"","flat":"","color":_vm.color,"disabled":_vm.beforeMinDays,"icon":_vm.$q.icon.datetime.arrowLeft,"repeatTimeout":_vm.__getRepeatEasing()},on:{"click":function($event){_vm.setMonth(_vm.month - 1);}}}),_vm._v(" "),_c('div',{staticClass:"col q-datetime-dark"},[_vm._v(" "+_vm._s(_vm.monthStamp)+" ")]),_vm._v(" "),_c('q-btn',{attrs:{"round":"","dense":"","flat":"","color":_vm.color,"disabled":_vm.afterMaxDays,"icon":_vm.$q.icon.datetime.arrowRight,"repeatTimeout":_vm.__getRepeatEasing()},on:{"click":function($event){_vm.setMonth(_vm.month + 1);}}})],1),_vm._v(" "),_c('div',{staticClass:"q-datetime-weekdays row items-center justify-start"},_vm._l((_vm.headerDayNames),function(day){return _c('div',{key:("dh" + day)},[_vm._v(_vm._s(day))])})),_vm._v(" "),_c('div',{staticClass:"q-datetime-days row wrap items-center justify-start content-center"},[_vm._l((_vm.fillerDays),function(fillerDay){return _c('div',{key:("fd" + fillerDay),staticClass:"q-datetime-fillerday"})}),_vm._v(" "),(_vm.min)?_vm._l((_vm.beforeMinDays),function(fillerDay){return _c('div',{key:("fb" + fillerDay),staticClass:"row items-center content-center justify-center disabled"},[_vm._v(" "+_vm._s(fillerDay)+" ")])}):_vm._e(),_vm._v(" "),_vm._l((_vm.daysInterval),function(monthDay){return _c('div',{key:("md" + monthDay),staticClass:"row items-center content-center justify-center cursor-pointer",class:{ 'q-datetime-day-active': monthDay === _vm.day, 'q-datetime-day-today': monthDay === _vm.today },on:{"click":function($event){_vm.setDay(monthDay);}}},[_c('span',[_vm._v(_vm._s(monthDay))])])}),_vm._v(" "),(_vm.max)?_vm._l((_vm.afterMaxDays),function(fillerDay){return _c('div',{key:("fa" + fillerDay),staticClass:"row items-center content-center justify-center disabled"},[_vm._v(" "+_vm._s(fillerDay + _vm.maxDay)+" ")])}):_vm._e()],2)]):_vm._e(),_vm._v(" "),(_vm.view === 'hour' || _vm.view === 'minute')?_c('div',{ref:"clock",staticClass:"column items-center content-center justify-center"},[(_vm.view === 'hour')?_c('div',{staticClass:"q-datetime-clock cursor-pointer",on:{"mousedown":_vm.__dragStart,"mousemove":_vm.__dragMove,"mouseup":_vm.__dragStop,"touchstart":_vm.__dragStart,"touchmove":_vm.__dragMove,"touchend":_vm.__dragStop}},[_c('div',{staticClass:"q-datetime-clock-circle full-width full-height"},[_c('div',{staticClass:"q-datetime-clock-center"}),_vm._v(" "),_c('div',{staticClass:"q-datetime-clock-pointer",style:(_vm.clockPointerStyle)},[_c('span')]),_vm._v(" "),(_vm.computedFormat24h)?_c('div',_vm._l((24),function(n){return _c('div',{key:("hi" + n),staticClass:"q-datetime-clock-position fmt24",class:[("q-datetime-clock-pos-" + (n-1)), (n - 1) === _vm.hour ? 'active' : '']},[_c('span',[_vm._v(_vm._s(n - 1))])])})):_c('div',_vm._l((12),function(n){return _c('div',{key:("hi" + n),staticClass:"q-datetime-clock-position",class:['q-datetime-clock-pos-' + n, n === _vm.hour ? 'active' : '']},[_c('span',[_vm._v(_vm._s(n))])])}))])]):_vm._e(),_vm._v(" "),(_vm.view === 'minute')?_c('div',{staticClass:"q-datetime-clock cursor-pointer",on:{"mousedown":_vm.__dragStart,"mousemove":_vm.__dragMove,"mouseup":_vm.__dragStop,"touchstart":_vm.__dragStart,"touchmove":_vm.__dragMove,"touchend":_vm.__dragStop}},[_c('div',{staticClass:"q-datetime-clock-circle full-width full-height"},[_c('div',{staticClass:"q-datetime-clock-center"}),_vm._v(" "),_c('div',{staticClass:"q-datetime-clock-pointer",style:(_vm.clockPointerStyle)},[_c('span')]),_vm._v(" "),_vm._l((12),function(n){return _c('div',{key:("mi" + n),staticClass:"q-datetime-clock-position",class:['q-datetime-clock-pos-' + (n - 1), (n - 1) * 5 === _vm.minute ? 'active' : '']},[_c('span',[_vm._v(_vm._s((n - 1) * 5))])])})],2)]):_vm._e()]):_vm._e()]),_vm._v(" "),_vm._t("default")],2)])},staticRenderFns: [],
name: 'q-datetime-picker',
mixins: [DateMixin, FieldParentMixin],
props: {
defaultSelection: [String, Number, Date],
disable: Boolean,
readonly: Boolean
},
components: {
QBtn: QBtn
},
directives: {
Ripple: Ripple
},
data: function data () {
return {
view: this.__calcView(this.defaultView),
dragging: false,
centerClockPos: 0
}
},
watch: {
value: function value (val) {
if (!val) {
this.view = ['date', 'datetime'].includes(this.type) ? 'day' : 'hour';
}
},
view: function view () {
this.__scrollView();
}
},
computed: {
classes: function classes () {
var cls = [];
if (this.disable) {
cls.push('disabled');
}
if (this.readonly) {
cls.push('readonly');
}
if (this.color) {
cls.push(("text-" + (this.color)));
}
return cls
},
computedFormat24h: function computedFormat24h () {
return this.format24h !== 0
? this.format24h
: this.$q.i18n.date.format24h
},
computedFirstDayOfWeek: function computedFirstDayOfWeek () {
return this.firstDayOfWeek !== void 0
? this.firstDayOfWeek
: this.$q.i18n.date.firstDayOfWeek
},
headerDayNames: function headerDayNames () {
var
days = this.$q.i18n.date.daysShort,
first = this.computedFirstDayOfWeek;
return first > 0
? days.slice(first, 7).concat(days.slice(0, first))
: days
},
monthString: function monthString () {
return ("" + (this.$q.i18n.date.monthsShort[this.month - 1]))
},
monthStamp: function monthStamp () {
return ((this.$q.i18n.date.months[this.month - 1]) + " " + (this.year))
},
weekDayString: function weekDayString () {
return this.$q.i18n.date.days[this.model.getDay()]
},
fillerDays: function fillerDays () {
var days = (new Date(this.model.getFullYear(), this.model.getMonth(), 1).getDay() - this.computedFirstDayOfWeek);
if (days < 0) {
days += 7;
}
return days
},
beforeMinDays: function beforeMinDays () {
if (this.pmin === null || !isSameDate(this.pmin, this.model, 'month')) {
return false
}
return this.pmin.getDate() - 1
},
afterMaxDays: function afterMaxDays () {
if (this.pmax === null || !isSameDate(this.pmax, this.model, 'month')) {
return false
}
return this.daysInMonth - this.maxDay
},
maxDay: function maxDay () {
return this.pmax !== null ? this.pmax.getDate() : this.daysInMonth
},
daysInterval: function daysInterval () {
var after = this.pmax === null || this.afterMaxDays === false ? 0 : this.afterMaxDays;
if (this.beforeMinDays || after) {
var min = this.beforeMinDays ? this.beforeMinDays + 1 : 1;
return Array.apply(null, {length: this.daysInMonth - min - after + 1}).map(function (day, index) {
return index + min
})
}
return this.daysInMonth
},
hour: function hour () {
var h = this.model.getHours();
return this.computedFormat24h
? h
: convertToAmPm(h)
},
minute: function minute () {
return this.model.getMinutes()
},
am: function am () {
return this.model.getHours() <= 11
},
clockPointerStyle: function clockPointerStyle () {
var
divider = this.view === 'minute' ? 60 : (this.computedFormat24h ? 24 : 12),
degrees = Math.round((this.view === 'minute' ? this.minute : this.hour) * (360 / divider)) - 180;
return cssTransform(("rotate(" + degrees + "deg)"))
},
today: function today () {
var today = new Date();
return isSameDate(today, this.model, 'month')
? today.getDate()
: -1
}
},
methods: {
/* date */
setYear: function setYear (value) {
if (this.editable) {
this.view = 'day';
this.model = new Date(this.model.setFullYear(this.__parseTypeValue('year', value)));
}
},
setMonth: function setMonth (value) {
if (this.editable) {
this.view = 'day';
this.model = adjustDate(this.model, {month: value});
}
},
setDay: function setDay (value) {
if (this.editable) {
this.model = new Date(this.model.setDate(this.__parseTypeValue('date', value)));
if (this.type === 'date') {
this.$emit('canClose');
}
else {
this.view = 'hour';
}
}
},
setHour: function setHour (value) {
if (!this.editable) {
return
}
value = this.__parseTypeValue('hour', value);
if (!this.computedFormat24h && value < 12 && !this.am) {
value += 12;
}
this.model = new Date(this.model.setHours(value));
},
setMinute: function setMinute (value) {
if (!this.editable) {
return
}
this.model = new Date(this.model.setMinutes(this.__parseTypeValue('minute', value)));
},
setView: function setView (view) {
this.view = this.__calcView(view);
},
/* helpers */
__calcView: function __calcView (view) {
switch (this.type) {
case 'time':
return ['hour', 'minute'].includes(view) ? view : 'hour'
case 'date':
return ['year', 'month', 'day'].includes(view) ? view : 'day'
default:
return ['year', 'month', 'day', 'hour', 'minute'].includes(view) ? view : 'day'
}
},
__pad: function __pad (unit, filler) {
return (unit < 10 ? filler || '0' : '') + unit
},
__scrollView: function __scrollView () {
if (this.view !== 'year' && this.view !== 'month') {
return
}
var
el = this.$refs.selector,
rows = this.view === 'year' ? this.year - this.yearMin : this.month - this.monthMin;
this.$nextTick(function () {
el.scrollTop = rows * height(el.children[0].children[0]) - height(el) / 2.5;
});
},
__dragStart: function __dragStart (ev) {
stopAndPrevent(ev);
var
clock = this.$refs.clock,
clockOffset = offset(clock);
this.centerClockPos = {
top: clockOffset.top + height(clock) / 2,
left: clockOffset.left + width(clock) / 2
};
this.dragging = true;
this.__updateClock(ev);
},
__dragMove: function __dragMove (ev) {
if (!this.dragging) {
return
}
stopAndPrevent(ev);
this.__updateClock(ev);
},
__dragStop: function __dragStop (ev) {
stopAndPrevent(ev);
this.dragging = false;
if (this.view === 'minute') {
this.$emit('canClose');
}
else {
this.view = 'minute';
}
},
__updateClock: function __updateClock (ev) {
var
pos = position(ev),
height$$1 = Math.abs(pos.top - this.centerClockPos.top),
distance = Math.sqrt(
Math.pow(Math.abs(pos.top - this.centerClockPos.top), 2) +
Math.pow(Math.abs(pos.left - this.centerClockPos.left), 2)
),
angle = Math.asin(height$$1 / distance) * (180 / Math.PI);
if (pos.top < this.centerClockPos.top) {
angle = this.centerClockPos.left < pos.left ? 90 - angle : 270 + angle;
}
else {
angle = this.centerClockPos.left < pos.left ? angle + 90 : 270 - angle;
}
if (this.view === 'hour') {
this.setHour(Math.round(angle / (this.computedFormat24h ? 15 : 30)));
}
else {
this.setMinute(Math.round(angle / 6));
}
},
__getRepeatEasing: function __getRepeatEasing (from, step, to) {
if ( from === void 0 ) from = 300;
if ( step === void 0 ) step = 10;
if ( to === void 0 ) to = 100;
return function (cnt) { return cnt ? Math.max(to, from - cnt * cnt * step) : 100; }
}
},
mounted: function mounted () {
this.__scrollView();
}
}
var contentCss$1 = {
maxWidth: '95vw',
maxHeight: '98vh'
};
var QDatetime = {
name: 'q-datetime',
mixins: [FrameMixin, DisplayModeMixin],
props: extend(
input,
inline
),
data: function data () {
var data = this.isPopover ? {} : {
transition: 'q-modal'
};
data.focused = false;
data.model = clone(isValid(this.value) ? this.value : this.defaultSelection);
return data
},
computed: {
actualValue: function actualValue () {
if (this.displayValue) {
return this.displayValue
}
if (!isValid(this.value)) {
return this.placeholder || ''
}
var format;
if (this.format) {
format = this.format;
}
else if (this.type === 'date') {
format = 'YYYY-MM-DD';
}
else if (this.type === 'time') {
format = 'HH:mm';
}
else {
format = 'YYYY-MM-DD HH:mm:ss';
}
return formatDate(this.value, format, /* for reactiveness */ this.$q.i18n.date)
}
},
methods: {
toggle: function toggle () {
this[this.$refs.popup.showing ? 'hide' : 'show']();
},
show: function show () {
if (!this.disable) {
if (!this.focused) {
this.__setModel(this.value);
}
return this.$refs.popup.show()
}
},
hide: function hide () {
this.focused = false;
return this.$refs.popup.hide()
},
__handleKey: function __handleKey (e) {
// ENTER key
if (e.which === 13 || e.keyCode === 13) {
this.show();
}
// Backspace key
else if (e.which === 8 || e.keyCode === 8) {
if (this.editable && this.clearable && this.actualValue.length) {
this.clear();
}
}
},
__onFocus: function __onFocus () {
if (this.defaultView) {
var target = this.$refs.target;
if (target.view !== this.defaultView) {
target.setView(this.defaultView);
}
else {
target.__scrollView();
}
}
if (this.focused) {
return
}
this.__setModel(this.value);
this.focused = true;
this.$emit('focus');
},
__onBlur: function __onBlur (e) {
var this$1 = this;
this.__onHide();
setTimeout(function () {
var el = document.activeElement;
if (el !== document.body && !this$1.$refs.popup.$el.contains(el)) {
this$1.hide();
}
}, 1);
},
__onHide: function __onHide () {
this.focused = false;
this.$emit('blur');
if (this.isPopover && !this.$refs.popup.showing) {
this.__update(true);
}
},
__setModel: function __setModel (val, forceUpdate) {
this.model = clone(isValid(val) ? val : this.defaultSelection);
if (forceUpdate || (this.isPopover && this.$refs.popup.showing)) {
this.__update();
}
},
__update: function __update (change) {
var this$1 = this;
this.$nextTick(function () {
this$1.$emit('input', this$1.model);
this$1.$nextTick(function () {
if (change && !isSameDate(this$1.model, this$1.value)) {
this$1.$emit('change', this$1.model);
}
});
});
},
__getPicker: function __getPicker (h, modal) {
var this$1 = this;
return [
h(QDatetimePicker, {
ref: 'target',
staticClass: "no-border",
props: {
type: this.type,
min: this.min,
max: this.max,
format24h: this.format24h,
firstDayOfWeek: this.firstDayOfWeek,
defaultView: this.defaultView,
color: this.color,
value: this.model,
disable: this.disable,
readonly: this.readonly
},
on: {
input: function (v) { return this$1.$nextTick(function () { return this$1.__setModel(v); }); },
canClose: function () {
if (this$1.isPopover) {
this$1.hide();
}
}
}
}, [
modal
? h('div', {
staticClass: 'modal-buttons modal-buttons-top row full-width'
}, [
h('div', { staticClass: 'col' }),
h(QBtn, {
props: {
color: this.color,
flat: true,
label: this.cancelLabel || this.$q.i18n.label.cancel,
waitForRipple: true
},
on: { click: this.hide }
}),
this.editable
? h(QBtn, {
props: {
color: this.color,
flat: true,
label: this.okLabel || this.$q.i18n.label.set,
waitForRipple: true
},
on: {
click: function () {
this$1.hide();
this$1.__update(true);
}
}
})
: null
])
: null
])
]
}
},
render: function render (h) {
return h(QInputFrame, {
props: {
prefix: this.prefix,
suffix: this.suffix,
stackLabel: this.stackLabel,
floatLabel: this.floatLabel,
error: this.error,
warning: this.warning,
disable: this.disable,
inverted: this.inverted,
dark: this.dark,
hideUnderline: this.hideUnderline,
before: this.before,
after: this.after,
color: this.color,
focused: this.focused,
focusable: true,
length: this.actualValue.length
},
nativeOn: {
click: this.toggle,
focus: this.__onFocus,
blur: this.__onBlur,
keydown: this.__handleKey
}
}, [
h('div', {
staticClass: 'col row items-center q-input-target',
'class': this.alignClass,
domProps: {
innerHTML: this.actualValue
}
}),
this.isPopover
? h(QPopover, {
ref: 'popup',
props: {
offset: [0, 10],
disable: this.disable,
anchorClick: false,
maxHeight: '100vh'
},
on: {
show: this.__onFocus,
hide: this.__onHide
}
}, this.__getPicker(h))
: h(QModal, {
ref: 'popup',
staticClass: 'with-backdrop',
props: {
contentCss: contentCss$1,
minimized: "mat" === 'mat',
position: null,
transition: this.transition
},
on: {
show: this.__onFocus,
hide: this.__onHide
}
}, this.__getPicker(h, true)),
this.editable && this.clearable && this.actualValue.length
? h('q-icon', {
slot: 'after',
props: { name: this.$q.icon.input.clear },
nativeOn: { click: this.clear },
staticClass: 'q-if-control'
})
: null,
h('q-icon', {
slot: 'after',
props: { name: this.$q.icon.input.dropdown },
staticClass: 'q-if-control'
})
])
}
}
var inputTypes = [
'text', 'textarea', 'email',
'tel', 'file', 'number',
'password', 'url', 'time', 'date'
]
var QResizeObservable = {
name: 'q-resize-observable',
methods: {
onResize: function onResize () {
var size = {
width: this.parent.offsetWidth,
height: this.parent.offsetHeight
};
if (size.width === this.size.width && size.height === this.size.height) {
return
}
this.size = size;
this.$emit('resize', this.size);
}
},
render: function render (h) {
return h('div', {
staticClass: 'absolute-full overflow-hidden invisible',
style: 'z-index: -1;'
})
},
mounted: function mounted () {
var this$1 = this;
var
object = document.createElement('object'),
onIE = this.$q.platform.is.ie;
this.parent = this.$el.parentNode;
this.size = { width: -1, height: -1 };
this.onResize = debounce(this.onResize, 100);
this.onResize();
this.object = object;
object.setAttribute('style', 'display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; pointer-events: none; z-index: -1;');
object.onload = function () {
object.contentDocument.defaultView.addEventListener('resize', this$1.onResize);
};
object.type = 'text/html';
if (onIE) {
this.$el.appendChild(object);
}
object.data = 'about:blank';
if (!onIE) {
this.$el.appendChild(object);
}
},
beforeDestroy: function beforeDestroy () {
if (this.object && this.object.onload) {
if (!this.$q.platform.is.ie && this.object.contentDocument) {
this.object.contentDocument.defaultView.removeEventListener('resize', this.onResize);
}
delete this.object.onload;
}
}
}
var QScrollObservable = {
name: 'q-scroll-observable',
render: function render () {},
data: function data () {
return {
pos: 0,
dir: 'down',
dirChanged: false,
dirChangePos: 0
}
},
methods: {
getPosition: function getPosition () {
return {
position: this.pos,
direction: this.dir,
directionChanged: this.dirChanged,
inflexionPosition: this.dirChangePos
}
},
trigger: function trigger () {
if (!this.timer) {
this.timer = window.requestAnimationFrame(this.emit);
}
},
emit: function emit () {
var
pos = Math.max(0, getScrollPosition(this.target)),
delta = pos - this.pos,
dir = delta < 0 ? 'up' : 'down';
this.dirChanged = this.dir !== dir;
if (this.dirChanged) {
this.dir = dir;
this.dirChangePos = this.pos;
}
this.timer = null;
this.pos = pos;
this.$emit('scroll', this.getPosition());
}
},
mounted: function mounted () {
this.target = getScrollTarget(this.$el.parentNode);
this.target.addEventListener('scroll', this.trigger);
this.trigger();
},
beforeDestroy: function beforeDestroy () {
this.target.removeEventListener('scroll', this.trigger);
}
}
var QWindowResizeObservable = {
name: 'q-window-resize-observable',
render: function render () {},
methods: {
trigger: function trigger () {
if (!this.timer) {
this.timer = window.requestAnimationFrame(this.emit);
}
},
emit: function emit () {
this.timer = null;
this.$emit('resize', viewport());
}
},
created: function created () {
this.emit();
},
mounted: function mounted () {
window.addEventListener('resize', this.trigger);
},
beforeDestroy: function beforeDestroy () {
window.removeEventListener('resize', this.trigger);
}
}
var QInput = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('q-input-frame',{staticClass:"q-input",attrs:{"prefix":_vm.prefix,"suffix":_vm.suffix,"stack-label":_vm.stackLabel,"float-label":_vm.floatLabel,"error":_vm.error,"warning":_vm.warning,"disable":_vm.disable,"inverted":_vm.inverted,"dark":_vm.dark,"hide-underline":_vm.hideUnderline,"before":_vm.before,"after":_vm.after,"color":_vm.color,"focused":_vm.focused,"length":_vm.length,"top-addons":_vm.isTextarea},on:{"click":_vm.__onClick,"focus":_vm.__onFocus}},[_vm._t("before"),_vm._v(" "),(_vm.isTextarea)?[_c('div',{staticClass:"col row relative-position"},[_c('q-resize-observable',{on:{"resize":function($event){_vm.__updateArea();}}}),_vm._v(" "),_c('textarea',_vm._b({ref:"shadow",staticClass:"col q-input-target q-input-shadow absolute-top",domProps:{"value":_vm.model}},'textarea',_vm.$attrs,false)),_vm._v(" "),_c('textarea',_vm._b({ref:"input",staticClass:"col q-input-target q-input-area",attrs:{"name":_vm.name,"placeholder":_vm.inputPlaceholder,"disabled":_vm.disable,"readonly":_vm.readonly,"maxlength":_vm.maxLength},domProps:{"value":_vm.model},on:{"input":_vm.__set,"focus":_vm.__onFocus,"blur":_vm.__onInputBlur,"keydown":_vm.__onKeydown,"keyup":_vm.__onKeyup}},'textarea',_vm.$attrs,false))],1)]:_c('input',_vm._b({ref:"input",staticClass:"col q-input-target q-no-input-spinner",class:[("text-" + (_vm.align))],attrs:{"name":_vm.name,"placeholder":_vm.inputPlaceholder,"disabled":_vm.disable,"readonly":_vm.readonly,"maxlength":_vm.maxLength,"step":_vm.computedStep,"type":_vm.inputType},domProps:{"value":_vm.model},on:{"input":_vm.__set,"focus":_vm.__onFocus,"blur":_vm.__onInputBlur,"keydown":_vm.__onKeydown,"keyup":_vm.__onKeyup}},'input',_vm.$attrs,false)),_vm._v(" "),(_vm.isPassword && !_vm.noPassToggle && _vm.length)?_c('q-icon',{staticClass:"q-if-control",attrs:{"slot":"after","name":_vm.$q.icon.input[_vm.showPass ? 'showPass' : 'hidePass']},nativeOn:{"mousedown":function($event){_vm.__clearTimer($event);},"touchstart":function($event){_vm.__clearTimer($event);},"click":function($event){_vm.togglePass($event);}},slot:"after"}):_vm._e(),_vm._v(" "),(_vm.keyboardToggle)?_c('q-icon',{staticClass:"q-if-control",attrs:{"slot":"after","name":_vm.$q.icon.input[_vm.showNumber ? 'showNumber' : 'hideNumber']},nativeOn:{"mousedown":function($event){_vm.__clearTimer($event);},"touchstart":function($event){_vm.__clearTimer($event);},"click":function($event){_vm.toggleNumber($event);}},slot:"after"}):_vm._e(),_vm._v(" "),(_vm.editable && _vm.clearable && _vm.length)?_c('q-icon',{staticClass:"q-if-control",attrs:{"slot":"after","name":_vm.$q.icon.input.clear},nativeOn:{"mousedown":function($event){_vm.__clearTimer($event);},"touchstart":function($event){_vm.__clearTimer($event);},"click":function($event){_vm.clear($event);}},slot:"after"}):_vm._e(),_vm._v(" "),(_vm.isLoading)?_c('q-spinner',{staticClass:"q-if-control",attrs:{"slot":"after","size":"24px"},slot:"after"}):_vm._e(),_vm._v(" "),_vm._t("after"),_vm._v(" "),_vm._t("default")],2)},staticRenderFns: [],
name: 'q-input',
mixins: [FrameMixin, InputMixin],
components: {
QInputFrame: QInputFrame,
QSpinner: QSpinner,
QResizeObservable: QResizeObservable
},
props: {
value: { required: true },
type: {
type: String,
default: 'text',
validator: function (t) { return inputTypes.includes(t); }
},
clearable: Boolean,
noPassToggle: Boolean,
numericKeyboardToggle: Boolean,
readonly: Boolean,
decimals: Number,
step: Number,
upperCase: Boolean
},
data: function data () {
var this$1 = this;
return {
showPass: false,
showNumber: true,
model: this.value,
shadow: {
val: this.model,
set: this.__set,
loading: false,
hasFocus: function () {
return document.activeElement === this$1.$refs.input
},
register: function () {
this$1.watcher = this$1.$watch('model', function (val) {
this$1.shadow.val = val;
});
},
unregister: function () {
this$1.watcher();
},
getEl: function () {
return this$1.$refs.input
}
}
}
},
watch: {
value: function value (v) {
this.model = v;
this.isNumberError = false;
}
},
provide: function provide () {
return {
__input: this.shadow
}
},
computed: {
isNumber: function isNumber () {
return this.type === 'number'
},
isPassword: function isPassword () {
return this.type === 'password'
},
isTextarea: function isTextarea () {
return this.type === 'textarea'
},
isLoading: function isLoading () {
return this.loading || this.shadow.loading
},
pattern: function pattern () {
if (this.isNumber) {
return this.$attrs.pattern || '[0-9]*'
}
},
keyboardToggle: function keyboardToggle () {
return this.$q.platform.is.mobile &&
this.isNumber &&
this.numericKeyboardToggle &&
length
},
inputType: function inputType () {
if (this.isPassword) {
return this.showPass ? 'text' : 'password'
}
return this.isNumber
? (this.showNumber ? 'number' : 'text')
: this.type
},
length: function length () {
return this.model !== null && this.model !== undefined
? ('' + this.model).length
: 0
},
computedStep: function computedStep () {
return this.step || (this.decimals ? Math.pow( 10, -this.decimals ) : 'any')
}
},
methods: {
togglePass: function togglePass () {
this.showPass = !this.showPass;
clearTimeout(this.timer);
this.focus();
},
toggleNumber: function toggleNumber () {
this.showNumber = !this.showNumber;
clearTimeout(this.timer);
this.focus();
},
__clearTimer: function __clearTimer () {
var this$1 = this;
this.$nextTick(function () { return clearTimeout(this$1.timer); });
},
__setModel: function __setModel (val) {
clearTimeout(this.timer);
this.focus();
this.__set(val || (this.isNumber ? null : ''), true);
},
__set: function __set (e, force) {
var val = e && e.target ? e.target.value : e;
if (this.isNumber) {
var forcedValue = val;
val = parseFloat(val);
if (isNaN(val)) {
this.isNumberError = true;
if (force) {
this.$emit('input', forcedValue);
}
return
}
this.isNumberError = false;
if (Number.isInteger(this.decimals)) {
val = parseFloat(val.toFixed(this.decimals));
}
}
else if (this.upperCase) {
val = val.toUpperCase();
}
this.$emit('input', val);
this.model = val;
},
__updateArea: function __updateArea () {
var shadow = this.$refs.shadow;
if (shadow) {
var h = shadow.scrollHeight;
var max = this.maxHeight || h;
this.$refs.input.style.minHeight = (between(h, 19, max)) + "px";
}
}
},
mounted: function mounted () {
this.__updateArea = frameDebounce(this.__updateArea);
if (this.isTextarea) {
this.__updateArea();
this.watcher = this.$watch('model', this.__updateArea);
}
},
beforeDestroy: function beforeDestroy () {
if (this.watcher !== void 0) {
this.watcher();
}
}
}
var QRadio = {
name: 'q-radio',
mixins: [OptionMixin],
props: {
val: {
required: true
}
},
computed: {
isTrue: function isTrue () {
return this.value === this.val
}
},
methods: {
toggle: function toggle (evt, blur) {
if ( blur === void 0 ) blur = true;
if (this.disable) {
return
}
if (evt) {
stopAndPrevent(evt);
}
if (blur) {
this.$el.blur();
}
if (!this.isTrue) {
this.__update(this.val);
}
},
__getContent: function __getContent (h) {
return [
h(QIcon, {
staticClass: 'q-radio-unchecked cursor-pointer absolute-full',
props: {
name: this.uncheckedIcon || this.$q.icon.radio.unchecked["mat"]
}
}),
h(QIcon, {
staticClass: 'q-radio-checked cursor-pointer absolute-full',
props: {
name: this.checkedIcon || this.$q.icon.radio.checked["mat"]
}
}),
h('div', { ref: 'ripple', staticClass: 'q-radial-ripple' })
]
}
}
}
var QToggle = {
name: 'q-toggle',
mixins: [CheckboxMixin, OptionMixin],
props: {
icon: String
},
computed: {
currentIcon: function currentIcon () {
return (this.isActive ? this.checkedIcon : this.uncheckedIcon) || this.icon
},
iconColor: function iconColor () {
return this.isTrue ? 'white' : 'dark'
},
baseClass: function baseClass () {
}
},
methods: {
__swipe: function __swipe (evt) {
if (evt.direction === 'left') {
if (this.isTrue) {
this.toggle();
}
}
else if (evt.direction === 'right') {
if (this.isFalse) {
this.toggle();
}
}
},
__getContent: function __getContent (h) {
return [
h('div', { staticClass: 'q-toggle-base', 'class': this.baseClass }),
h('div', { staticClass: 'q-toggle-handle row flex-center' }, [
this.currentIcon
? h(QIcon, {
staticClass: 'q-toggle-icon',
props: { name: this.currentIcon, color: this.iconColor }
})
: null,
h('div', { ref: 'ripple', staticClass: 'q-radial-ripple' })
])
]
}
}
}
var QOptionGroup = {
name: 'q-option-group',
mixins: [FieldParentMixin],
components: {
QRadio: QRadio,
QCheckbox: QCheckbox,
QToggle: QToggle
},
props: {
value: {
required: true
},
type: {
default: 'radio',
validator: function (v) { return ['radio', 'checkbox', 'toggle'].includes(v); }
},
color: String,
keepColor: Boolean,
dark: Boolean,
options: {
type: Array,
validator: function validator (opts) {
return opts.every(function (opt) { return 'value' in opt && 'label' in opt; })
}
},
leftLabel: Boolean,
inline: Boolean,
disable: Boolean
},
computed: {
component: function component () {
return ("q-" + (this.type))
},
model: function model () {
return Array.isArray(this.value) ? this.value.slice() : this.value
},
length: function length () {
return this.value
? (this.type === 'radio' ? 1 : this.value.length)
: 0
},
__needsBorder: function __needsBorder () {
return true
}
},
methods: {
__onFocus: function __onFocus () {
this.$emit('focus');
},
__onBlur: function __onBlur () {
this.$emit('blur');
},
__update: function __update (value) {
var this$1 = this;
this.$emit('input', value);
this.$nextTick(function () {
if (JSON.stringify(value) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', value);
}
});
}
},
created: function created () {
var isArray = Array.isArray(this.value);
if (this.type === 'radio') {
if (isArray) {
console.error('q-option-group: model should not be array');
}
}
else if (!isArray) {
console.error('q-option-group: model should be array in your case');
}
},
render: function render (h) {
var this$1 = this;
return h(
'div',
{
staticClass: 'q-option-group group',
'class': { 'q-option-group-inline-opts': this.inline }
},
this.options.map(
function (opt) { return h('div', [
h(this$1.component, {
props: {
value: this$1.value,
val: opt.value,
disable: this$1.disable || opt.disable,
label: opt.label,
leftLabel: opt.leftLabel,
color: opt.color || this$1.color,
checkedIcon: opt.checkedIcon,
uncheckedIcon: opt.uncheckedIcon,
dark: opt.dark || this$1.dark,
keepColor: opt.keepColor || this$1.keepColor
},
on: {
input: this$1.__update,
focus: this$1.__onFocus,
blur: this$1.__onBlur
}
})
]); }
)
)
}
}
var QDialog = {
name: 'q-dialog',
props: {
value: Boolean,
title: String,
message: String,
prompt: Object,
options: Object,
ok: {
type: [String, Boolean],
default: true
},
cancel: [String, Boolean],
stackButtons: Boolean,
preventClose: Boolean,
position: String,
color: {
type: String,
default: 'primary'
}
},
render: function render (h) {
var this$1 = this;
var
child = [],
title = this.$slots.title || this.title,
msg = this.$slots.message || this.message;
if (title) {
child.push(
h('div', {
staticClass: 'modal-header'
}, [ title ])
);
}
if (msg) {
child.push(
h('div', {
staticClass: 'modal-body modal-message modal-scroll'
}, [ msg ])
);
}
if (this.hasForm || this.$slots.body) {
child.push(
h(
'div',
{ staticClass: 'modal-body modal-scroll' },
this.hasForm
? (this.prompt ? this.__getPrompt(h) : this.__getOptions(h))
: [ this.$slots.body ]
)
);
}
if (this.$scopedSlots.buttons) {
child.push(
h('div', {
staticClass: 'modal-buttons',
'class': this.buttonClass
}, [
this.$scopedSlots.buttons({
ok: this.__onOk,
cancel: this.__onCancel
})
])
);
}
else if (this.ok || this.cancel) {
child.push(this.__getButtons(h));
}
return h(QModal, {
ref: 'modal',
props: {
value: this.value,
minimized: true,
noBackdropDismiss: this.preventClose,
noEscDismiss: this.preventClose,
position: this.position
},
on: {
input: function (val) {
this$1.$emit('input', val);
},
show: function () {
this$1.$emit('show');
if (!this$1.$q.platform.is.desktop) {
return
}
var node = this$1.prompt
? this$1.$refs.modal.$el.getElementsByTagName('INPUT')
: this$1.$refs.modal.$el.getElementsByClassName('q-option');
if (node.length) {
node[0].focus();
return
}
node = this$1.$refs.modal.$el.getElementsByTagName('BUTTON');
if (node.length) {
node[node.length - 1].focus();
}
},
hide: function () {
this$1.$emit('hide');
},
dismiss: function () {
this$1.$emit('cancel');
},
'escape-key': function () {
this$1.hide().then(function () {
this$1.$emit('escape-key');
this$1.$emit('cancel');
});
}
}
}, child)
},
computed: {
hasForm: function hasForm () {
return this.prompt || this.options
},
okLabel: function okLabel () {
return this.ok === true
? this.$q.i18n.label.ok
: this.ok
},
cancelLabel: function cancelLabel () {
return this.cancel === true
? this.$q.i18n.label.cancel
: this.cancel
},
buttonClass: function buttonClass () {
return this.stackButtons
? 'column'
: 'row'
}
},
methods: {
show: function show () {
return this.$refs.modal.show()
},
hide: function hide () {
var this$1 = this;
var data;
return this.$refs.modal.hide().then(function () {
if (this$1.hasForm) {
data = clone(this$1.__getData());
}
return data
})
},
__getPrompt: function __getPrompt (h) {
var this$1 = this;
return [
h(QInput, {
style: 'margin-bottom: 10px',
props: {
value: this.prompt.model,
type: this.prompt.type || 'text',
color: this.color,
noPassToggle: true
},
on: {
change: function (v) { this$1.prompt.model = v; }
}
})
]
},
__getOptions: function __getOptions (h) {
var this$1 = this;
return [
h(QOptionGroup, {
props: {
value: this.options.model,
type: this.options.type,
color: this.color,
inline: this.options.inline,
options: this.options.items
},
on: {
change: function (v) { this$1.options.model = v; }
}
})
]
},
__getButtons: function __getButtons (h) {
var child = [];
if (this.cancel) {
child.push(h(QBtn, {
props: { color: this.color, flat: true, label: this.cancelLabel, waitForRipple: true },
on: { click: this.__onCancel }
}));
}
if (this.ok) {
child.push(h(QBtn, {
props: { color: this.color, flat: true, label: this.okLabel, waitForRipple: true },
on: { click: this.__onOk }
}));
}
return h('div', {
staticClass: 'modal-buttons',
'class': this.buttonClass
}, child)
},
__onOk: function __onOk () {
var this$1 = this;
return this.hide().then(function (data) {
this$1.$emit('ok', data);
})
},
__onCancel: function __onCancel () {
var this$1 = this;
return this.hide().then(function () {
this$1.$emit('cancel');
})
},
__getData: function __getData () {
if (this.prompt) {
return this.prompt.model
}
if (this.options) {
return this.options.model
}
}
}
}
var QTooltip = {
name: 'q-tooltip',
mixins: [ModelToggleMixin],
props: {
anchor: {
type: String,
default: 'top middle',
validator: positionValidator
},
self: {
type: String,
default: 'bottom middle',
validator: positionValidator
},
offset: {
type: Array,
validator: offsetValidator
},
delay: {
type: Number,
default: 0
},
maxHeight: String,
disable: Boolean
},
watch: {
$route: function $route () {
this.hide();
}
},
computed: {
anchorOrigin: function anchorOrigin () {
return parsePosition(this.anchor)
},
selfOrigin: function selfOrigin () {
return parsePosition(this.self)
},
transformCSS: function transformCSS () {
return getTransformProperties({
selfOrigin: this.selfOrigin
})
}
},
methods: {
__show: function __show () {
clearTimeout(this.timer);
document.body.appendChild(this.$el);
this.scrollTarget = getScrollTarget(this.anchorEl);
this.scrollTarget.addEventListener('scroll', this.hide);
window.addEventListener('resize', this.__debouncedUpdatePosition);
if (this.$q.platform.is.mobile) {
document.body.addEventListener('click', this.hide, true);
}
this.__updatePosition();
this.showPromise && this.showPromiseResolve();
},
__hide: function __hide () {
clearTimeout(this.timer);
this.scrollTarget.removeEventListener('scroll', this.hide);
window.removeEventListener('resize', this.__debouncedUpdatePosition);
document.body.removeChild(this.$el);
if (this.$q.platform.is.mobile) {
document.body.removeEventListener('click', this.hide, true);
}
this.hidePromise && this.hidePromiseResolve();
},
__updatePosition: function __updatePosition () {
setPosition({
el: this.$el,
offset: this.offset,
anchorEl: this.anchorEl,
anchorOrigin: this.anchorOrigin,
selfOrigin: this.selfOrigin,
maxHeight: this.maxHeight
});
},
__delayShow: function __delayShow () {
clearTimeout(this.timer);
this.timer = setTimeout(this.show, this.delay);
},
__delayHide: function __delayHide () {
clearTimeout(this.timer);
this.hide();
}
},
render: function render (h) {
return h('span', {
staticClass: 'q-tooltip animate-scale',
style: this.transformCSS
}, [ this.$slots.default ])
},
created: function created () {
var this$1 = this;
this.__debouncedUpdatePosition = debounce(function () {
this$1.__updatePosition();
}, 70);
},
mounted: function mounted () {
var this$1 = this;
this.$nextTick(function () {
/*
The following is intentional.
Fixes a bug in Chrome regarding offsetHeight by requiring browser
to calculate this before removing from DOM and using it for first time.
*/
this$1.$el.offsetHeight; // eslint-disable-line
this$1.anchorEl = this$1.$el.parentNode;
this$1.anchorEl.removeChild(this$1.$el);
if (this$1.anchorEl.classList.contains('q-btn-inner')) {
this$1.anchorEl = this$1.anchorEl.parentNode;
}
if (this$1.$q.platform.is.mobile) {
this$1.anchorEl.addEventListener('click', this$1.show);
}
else {
this$1.anchorEl.addEventListener('mouseenter', this$1.__delayShow);
this$1.anchorEl.addEventListener('focus', this$1.__delayShow);
this$1.anchorEl.addEventListener('mouseleave', this$1.__delayHide);
this$1.anchorEl.addEventListener('blur', this$1.__delayHide);
}
if (this$1.value) {
this$1.show();
}
});
},
beforeDestroy: function beforeDestroy () {
clearTimeout(this.timer);
if (!this.anchorEl) {
return
}
if (this.$q.platform.is.mobile) {
this.anchorEl.removeEventListener('click', this.show);
}
else {
this.anchorEl.removeEventListener('mouseenter', this.__delayShow);
this.anchorEl.removeEventListener('focus', this.__delayShow);
this.anchorEl.removeEventListener('mouseleave', this.__delayHide);
this.anchorEl.removeEventListener('blur', this.__delayHide);
}
}
}
function run (e, btn, vm) {
if (btn.handler) {
btn.handler(e, vm, vm.caret);
}
else {
vm.runCmd(btn.cmd, btn.param);
}
}
function getBtn (h, vm, btn, clickHandler, active) {
if ( active === void 0 ) active = false;
var
toggled = active || (btn.type === 'toggle'
? (btn.toggled ? btn.toggled(vm) : btn.cmd && vm.caret.is(btn.cmd, btn.param))
: false),
child = [],
events = {
click: function click (e) {
clickHandler && clickHandler();
run(e, btn, vm);
}
};
if (btn.tip && vm.$q.platform.is.desktop) {
var Key = btn.key
? h('div', [h('small', ("(CTRL + " + (String.fromCharCode(btn.key)) + ")"))])
: null;
child.push(h(QTooltip, { props: {delay: 1000} }, [
h('div', { domProps: { innerHTML: btn.tip } }),
Key
]));
}
return h(QBtn, {
props: extend({
icon: btn.icon,
color: toggled ? btn.toggleColor || vm.toolbarToggleColor : btn.color || vm.toolbarColor,
textColor: toggled && (vm.toolbarFlat || vm.toolbarOutline) ? null : btn.textColor || vm.toolbarTextColor,
label: btn.label,
disable: btn.disable ? (typeof btn.disable === 'function' ? btn.disable(vm) : true) : false
}, vm.buttonProps),
on: events
}, child)
}
function getDropdown (h, vm, btn) {
var
label = btn.label,
icon = btn.icon,
noIcons = btn.list === 'no-icons',
onlyIcons = btn.list === 'only-icons',
Items;
function closeDropdown () {
Dropdown.componentInstance.hide();
}
if (onlyIcons) {
Items = btn.options.map(function (btn) {
var active = btn.type === void 0
? vm.caret.is(btn.cmd, btn.param)
: false;
if (active) {
label = btn.tip;
icon = btn.icon;
}
return getBtn(h, vm, btn, closeDropdown, active)
});
Items = [
h(
QBtnGroup,
{
props: vm.buttonProps,
staticClass: 'relative-position q-editor-toolbar-padding',
'class': vm.toolbarBackgroundClass,
style: { borderRadius: '0' }
},
Items
)
];
}
else {
Items = btn.options.map(function (btn) {
var disable = btn.disable ? btn.disable(vm) : false;
var active = btn.type === void 0
? vm.caret.is(btn.cmd, btn.param)
: false;
if (active) {
label = btn.tip;
icon = btn.icon;
}
return h(
QItem,
{
props: { active: active, link: !disable },
'class': { disabled: disable },
nativeOn: {
click: function click (e) {
if (disable) { return }
closeDropdown();
vm.$refs.content.focus();
vm.caret.restore();
run(e, btn, vm);
}
}
},
[
noIcons ? '' : h(QItemSide, {props: {icon: btn.icon}}),
h(QItemMain, {
props: {
label: btn.htmlTip || btn.tip
}
})
]
)
});
Items = [
h(QList, {
props: { separator: true },
'class': [vm.toolbarBackgroundClass, vm.toolbarTextColor ? ("text-" + (vm.toolbarTextColor)) : '']
}, [ Items ])
];
}
var highlight = btn.highlight && label !== btn.label;
var Dropdown = h(
QBtnDropdown,
{
props: extend({
noCaps: true,
noWrap: true,
color: highlight ? vm.toolbarToggleColor : vm.toolbarColor,
textColor: highlight && (vm.toolbarFlat || vm.toolbarOutline) ? null : vm.toolbarTextColor,
label: btn.fixedLabel ? btn.label : label,
icon: btn.fixedIcon ? btn.icon : icon
}, vm.buttonProps)
},
Items
);
return Dropdown
}
function getToolbar (h, vm) {
if (vm.caret) {
return vm.buttons.map(function (group) { return h(
QBtnGroup,
{ props: vm.buttonProps, staticClass: 'items-center relative-position' },
group.map(function (btn) {
if (btn.type === 'slot') {
return vm.$slots[btn.slot]
}
if (btn.type === 'dropdown') {
return getDropdown(h, vm, btn)
}
return getBtn(h, vm, btn)
})
); })
}
}
function getFonts (defaultFont, defaultFontLabel, defaultFontIcon, fonts) {
if ( fonts === void 0 ) fonts = {};
var aliases = Object.keys(fonts);
if (aliases.length === 0) {
return {}
}
var def = {
default_font: {
cmd: 'fontName',
param: defaultFont,
icon: defaultFontIcon,
tip: defaultFontLabel
}
};
aliases.forEach(function (alias) {
var name = fonts[alias];
def[alias] = {
cmd: 'fontName',
param: name,
icon: defaultFontIcon,
tip: name,
htmlTip: ("<font face=\"" + name + "\">" + name + "</font>")
};
});
return def
}
function getLinkEditor (h, vm) {
if (vm.caret) {
var color = vm.toolbarColor || vm.toolbarTextColor;
var link = vm.editLinkUrl;
var updateLink = function () {
vm.caret.restore();
if (link !== vm.editLinkUrl) {
document.execCommand('createLink', false, link === '' ? ' ' : link);
}
vm.editLinkUrl = null;
};
return [
h('div', { staticClass: 'q-mx-xs', 'class': ("text-" + color) }, [((vm.$q.i18n.editor.url) + ": ")]),
h(QInput, {
key: 'qedt_btm_input',
staticClass: 'q-ma-none q-pa-none col q-editor-input',
props: {
value: link,
color: color,
autofocus: true,
hideUnderline: true
},
on: {
input: function (val) { link = val; },
keyup: function (event) {
switch (event.keyCode) {
case 13: // enter
return updateLink()
case 27: // escape
vm.caret.restore();
vm.editLinkUrl = null;
break
}
}
}
}),
h(QBtnGroup, {
key: 'qedt_btm_grp',
props: vm.buttonProps
}, [
h(QBtn, {
key: 'qedt_btm_rem',
attrs: {
tabindex: -1
},
props: extend({
label: vm.$q.i18n.label.remove,
noCaps: true
}, vm.buttonProps),
on: {
click: function () {
vm.caret.restore();
document.execCommand('unlink');
vm.editLinkUrl = null;
}
}
}),
h(QBtn, {
key: 'qedt_btm_upd',
props: extend({
label: vm.$q.i18n.label.update,
noCaps: true
}, vm.buttonProps),
on: {
click: updateLink
}
})
])
]
}
}
function getBlockElement (el, parent) {
if (parent && el === parent) {
return null
}
var
style = window.getComputedStyle
? window.getComputedStyle(el)
: el.currentStyle,
display = style.display;
if (display === 'block' || display === 'table') {
return el
}
return getBlockElement(el.parentNode)
}
function isChildOf (el, parent) {
if (!el) {
return false
}
while ((el = el.parentNode)) {
if (el === document.body) {
return false
}
if (el === parent) {
return true
}
}
return false
}
var urlRegex = /^https?:\/\//;
var Caret = function Caret (el, vm) {
this.el = el;
this.vm = vm;
};
var prototypeAccessors = { selection: { configurable: true },hasSelection: { configurable: true },range: { configurable: true },parent: { configurable: true },blockParent: { configurable: true } };
prototypeAccessors.selection.get = function () {
if (!this.el) {
return
}
var sel = document.getSelection();
// only when the selection in element
if (isChildOf(sel.anchorNode, this.el) && isChildOf(sel.focusNode, this.el)) {
return sel
}
};
prototypeAccessors.hasSelection.get = function () {
return this.selection
? this.selection.toString().length > 0
: null
};
prototypeAccessors.range.get = function () {
var sel = this.selection;
if (!sel) {
return
}
return sel.rangeCount
? sel.getRangeAt(0)
: null
};
prototypeAccessors.parent.get = function () {
var range = this.range;
if (!range) {
return
}
var node = range.startContainer;
return node.nodeType === document.ELEMENT_NODE
? node
: node.parentNode
};
prototypeAccessors.blockParent.get = function () {
var parent = this.parent;
if (!parent) {
return
}
return getBlockElement(parent, this.el)
};
Caret.prototype.save = function save (range) {
if ( range === void 0 ) range = this.range;
this._range = range;
};
Caret.prototype.restore = function restore (range) {
if ( range === void 0 ) range = this._range;
var
r = document.createRange(),
sel = document.getSelection();
if (range) {
r.setStart(range.startContainer, range.startOffset);
r.setEnd(range.endContainer, range.endOffset);
sel.removeAllRanges();
sel.addRange(r);
}
else {
sel.selectAllChildren(this.el);
sel.collapseToEnd();
}
};
Caret.prototype.hasParent = function hasParent (name, spanLevel) {
var el = spanLevel
? this.parent
: this.blockParent;
return el
? el.nodeName.toLowerCase() === name.toLowerCase()
: false
};
Caret.prototype.hasParents = function hasParents (list) {
var el = this.parent;
return el
? list.includes(el.nodeName.toLowerCase())
: false
};
Caret.prototype.is = function is (cmd, param) {
switch (cmd) {
case 'formatBlock':
if (param === 'DIV' && this.parent === this.el) {
return true
}
return this.hasParent(param, param === 'PRE')
case 'link':
return this.hasParent('A', true)
case 'fontSize':
return document.queryCommandValue(cmd) === param
case 'fontName':
var res = document.queryCommandValue(cmd);
return res === ("\"" + param + "\"") || res === param
case 'fullscreen':
return this.vm.inFullscreen
default:
var state = document.queryCommandState(cmd);
return param ? state === param : state
}
};
Caret.prototype.getParentAttribute = function getParentAttribute (attrib) {
if (this.parent) {
return this.parent.getAttribute(attrib)
}
};
Caret.prototype.can = function can (name) {
if (name === 'outdent') {
return this.hasParents(['blockquote', 'li'])
}
if (name === 'indent') {
var parentName = this.parent ? this.parent.nodeName.toLowerCase() : false;
if (parentName === 'blockquote') {
return false
}
if (parentName === 'li') {
var previousEl = this.parent.previousSibling;
return previousEl && previousEl.nodeName.toLowerCase() === 'li'
}
return false
}
};
Caret.prototype.apply = function apply (cmd, param, done) {
if ( done === void 0 ) done = function () {};
if (cmd === 'formatBlock') {
if (['BLOCKQUOTE', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'PRE'].includes(param) && this.is(cmd, param)) {
cmd = 'outdent';
param = null;
}
}
else if (cmd === 'print') {
done();
var win = window.open();
win.document.write(("\n <!doctype html>\n <html>\n <head>\n <title>Print - " + (document.title) + "</title>\n </head>\n <body>\n <div>" + (this.el.innerHTML) + "</div>\n </body>\n </html>\n "));
win.print();
win.close();
return
}
else if (cmd === 'link') {
var link = this.getParentAttribute('href');
if (!link) {
var selection = this.selectWord(this.selection);
var url = selection ? selection.toString() : '';
if (!url.length) {
return
}
this.vm.editLinkUrl = urlRegex.test(url) ? url : ("https://" + url);
document.execCommand('createLink', false, this.vm.editLinkUrl);
}
else {
this.vm.editLinkUrl = link;
}
this.range.selectNodeContents(this.parent);
this.save();
return
}
else if (cmd === 'fullscreen') {
this.vm.toggleFullscreen();
done();
return
}
document.execCommand(cmd, false, param);
done();
};
Caret.prototype.selectWord = function selectWord (sel) {
if (!sel.isCollapsed) {
return sel
}
// Detect if selection is backwards
var range = document.createRange();
range.setStart(sel.anchorNode, sel.anchorOffset);
range.setEnd(sel.focusNode, sel.focusOffset);
var direction = range.collapsed ? ['backward', 'forward'] : ['forward', 'backward'];
range.detach();
// modify() works on the focus of the selection
var
endNode = sel.focusNode,
endOffset = sel.focusOffset;
sel.collapse(sel.anchorNode, sel.anchorOffset);
sel.modify('move', direction[0], 'character');
sel.modify('move', direction[1], 'word');
sel.extend(endNode, endOffset);
sel.modify('extend', direction[1], 'character');
sel.modify('extend', direction[0], 'word');
return sel
};
Object.defineProperties( Caret.prototype, prototypeAccessors );
var QEditor = {
name: 'q-editor',
mixins: [FullscreenMixin],
props: {
value: {
type: String,
required: true
},
readonly: Boolean,
disable: Boolean,
minHeight: {
type: String,
default: '10rem'
},
maxHeight: String,
height: String,
definitions: Object,
fonts: Object,
toolbar: {
type: Array,
validator: function (v) { return v.length === 0 || v.every(function (group) { return group.length; }); },
default: function default$1 () {
return [
['left', 'center', 'right', 'justify'],
['bold', 'italic', 'underline', 'strike'],
['undo', 'redo']
]
}
},
toolbarColor: String,
toolbarTextColor: String,
toolbarToggleColor: {
type: String,
default: 'primary'
},
toolbarBg: {
type: String,
default: 'grey-3'
},
toolbarFlat: Boolean,
toolbarOutline: Boolean,
toolbarPush: Boolean,
toolbarRounded: Boolean,
contentStyle: Object,
contentClass: [Object, Array, String]
},
computed: {
editable: function editable () {
return !this.readonly && !this.disable
},
hasToolbar: function hasToolbar () {
return this.toolbar && this.toolbar.length > 0
},
toolbarBackgroundClass: function toolbarBackgroundClass () {
if (this.toolbarBg) {
return ("bg-" + (this.toolbarBg))
}
},
buttonProps: function buttonProps () {
return {
outline: this.toolbarOutline,
flat: this.toolbarFlat,
push: this.toolbarPush,
rounded: this.toolbarRounded,
dense: true,
color: this.toolbarColor,
disable: !this.editable
}
},
buttonDef: function buttonDef () {
var
e = this.$q.i18n.editor,
i = this.$q.icon.editor;
return {
bold: {cmd: 'bold', icon: i.bold, tip: e.bold, key: 66},
italic: {cmd: 'italic', icon: i.italic, tip: e.italic, key: 73},
strike: {cmd: 'strikeThrough', icon: i.strikethrough, tip: e.strikethrough, key: 83},
underline: {cmd: 'underline', icon: i.underline, tip: e.underline, key: 85},
unordered: {cmd: 'insertUnorderedList', icon: i.unorderedList, tip: e.unorderedList},
ordered: {cmd: 'insertOrderedList', icon: i.orderedList, tip: e.orderedList},
subscript: {cmd: 'subscript', icon: i.subscript, tip: e.subscript, htmlTip: 'x<subscript>2</subscript>'},
superscript: {cmd: 'superscript', icon: i.superscript, tip: e.superscript, htmlTip: 'x<superscript>2</superscript>'},
link: {cmd: 'link', icon: i.hyperlink, tip: e.hyperlink, key: 76},
fullscreen: {cmd: 'fullscreen', icon: i.toggleFullscreen, tip: e.toggleFullscreen, key: 70},
quote: {cmd: 'formatBlock', param: 'BLOCKQUOTE', icon: i.quote, tip: e.quote, key: 81},
left: {cmd: 'justifyLeft', icon: i.left, tip: e.left},
center: {cmd: 'justifyCenter', icon: i.center, tip: e.center},
right: {cmd: 'justifyRight', icon: i.right, tip: e.right},
justify: {cmd: 'justifyFull', icon: i.justify, tip: e.justify},
print: {type: 'no-state', cmd: 'print', icon: i.print, tip: e.print, key: 80},
outdent: {type: 'no-state', disable: function (vm) { return vm.caret && !vm.caret.can('outdent'); }, cmd: 'outdent', icon: i.outdent, tip: e.outdent},
indent: {type: 'no-state', disable: function (vm) { return vm.caret && !vm.caret.can('indent'); }, cmd: 'indent', icon: i.indent, tip: e.indent},
removeFormat: {type: 'no-state', cmd: 'removeFormat', icon: i.removeFormat, tip: e.removeFormat},
hr: {type: 'no-state', cmd: 'insertHorizontalRule', icon: i.hr, tip: e.hr},
undo: {type: 'no-state', cmd: 'undo', icon: i.undo, tip: e.undo, key: 90},
redo: {type: 'no-state', cmd: 'redo', icon: i.redo, tip: e.redo, key: 89},
h1: {cmd: 'formatBlock', param: 'H1', icon: i.header, tip: e.header1, htmlTip: ("<h1 class=\"q-ma-none\">" + (e.header1) + "</h1>")},
h2: {cmd: 'formatBlock', param: 'H2', icon: i.header, tip: e.header2, htmlTip: ("<h2 class=\"q-ma-none\">" + (e.header2) + "</h2>")},
h3: {cmd: 'formatBlock', param: 'H3', icon: i.header, tip: e.header3, htmlTip: ("<h3 class=\"q-ma-none\">" + (e.header3) + "</h3>")},
h4: {cmd: 'formatBlock', param: 'H4', icon: i.header, tip: e.header4, htmlTip: ("<h4 class=\"q-ma-none\">" + (e.header4) + "</h4>")},
h5: {cmd: 'formatBlock', param: 'H5', icon: i.header, tip: e.header5, htmlTip: ("<h5 class=\"q-ma-none\">" + (e.header5) + "</h5>")},
h6: {cmd: 'formatBlock', param: 'H6', icon: i.header, tip: e.header6, htmlTip: ("<h6 class=\"q-ma-none\">" + (e.header6) + "</h6>")},
p: {cmd: 'formatBlock', param: 'DIV', icon: i.header, tip: e.paragraph},
code: {cmd: 'formatBlock', param: 'PRE', icon: i.code, tip: ("<code>" + (e.code) + "</code>")},
'size-1': {cmd: 'fontSize', param: '1', icon: i.size, tip: e.size1, htmlTip: ("<font size=\"1\">" + (e.size1) + "</font>")},
'size-2': {cmd: 'fontSize', param: '2', icon: i.size, tip: e.size2, htmlTip: ("<font size=\"2\">" + (e.size2) + "</font>")},
'size-3': {cmd: 'fontSize', param: '3', icon: i.size, tip: e.size3, htmlTip: ("<font size=\"3\">" + (e.size3) + "</font>")},
'size-4': {cmd: 'fontSize', param: '4', icon: i.size, tip: e.size4, htmlTip: ("<font size=\"4\">" + (e.size4) + "</font>")},
'size-5': {cmd: 'fontSize', param: '5', icon: i.size, tip: e.size5, htmlTip: ("<font size=\"5\">" + (e.size5) + "</font>")},
'size-6': {cmd: 'fontSize', param: '6', icon: i.size, tip: e.size6, htmlTip: ("<font size=\"6\">" + (e.size6) + "</font>")},
'size-7': {cmd: 'fontSize', param: '7', icon: i.size, tip: e.size7, htmlTip: ("<font size=\"7\">" + (e.size7) + "</font>")}
}
},
buttons: function buttons () {
var this$1 = this;
var userDef = this.definitions || {};
var def = this.definitions || this.fonts
? extend(
true,
{},
this.buttonDef,
userDef,
getFonts(
this.defaultFont,
this.$q.i18n.editor.defaultFont,
this.$q.icon.editor.font,
this.fonts
)
)
: this.buttonDef;
return this.toolbar.map(
function (group) { return group.map(function (token) {
if (token.options) {
return {
type: 'dropdown',
icon: token.icon,
label: token.label,
fixedLabel: token.fixedLabel,
fixedIcon: token.fixedIcon,
highlight: token.highlight,
list: token.list,
options: token.options.map(function (item) { return def[item]; })
}
}
var obj = def[token];
if (obj) {
return obj.type === 'no-state' || (userDef[token] && (
obj.cmd === void 0 || (this$1.buttonDef[obj.cmd] && this$1.buttonDef[obj.cmd].type === 'no-state')
))
? obj
: extend(true, { type: 'toggle' }, obj)
}
else {
return {
type: 'slot',
slot: token
}
}
}); }
)
},
keys: function keys () {
var
k = {},
add = function (btn) {
if (btn.key) {
k[btn.key] = {
cmd: btn.cmd,
param: btn.param
};
}
};
this.buttons.forEach(function (group) {
group.forEach(function (token) {
if (token.options) {
token.options.forEach(add);
}
else {
add(token);
}
});
});
return k
}
},
data: function data () {
return {
editWatcher: true,
editLinkUrl: null
}
},
watch: {
value: function value (v) {
if (this.editWatcher) {
this.$refs.content.innerHTML = v;
}
else {
this.editWatcher = true;
}
}
},
methods: {
onInput: function onInput (e) {
if (this.editWatcher) {
this.editWatcher = false;
this.$emit('input', this.$refs.content.innerHTML);
}
},
onKeydown: function onKeydown (e) {
var key = getEventKey(e);
if (!e.ctrlKey) {
this.refreshToolbar();
return
}
var target = this.keys[key];
if (target !== void 0) {
var cmd = target.cmd;
var param = target.param;
stopAndPrevent(e);
this.runCmd(cmd, param, false);
}
},
runCmd: function runCmd (cmd, param, update) {
var this$1 = this;
if ( update === void 0 ) update = true;
this.focus();
this.caret.apply(cmd, param, function () {
this$1.focus();
if (update) {
this$1.refreshToolbar();
}
});
},
refreshToolbar: function refreshToolbar () {
var this$1 = this;
setTimeout(function () {
this$1.editLinkUrl = null;
this$1.$forceUpdate();
}, 1);
},
focus: function focus () {
this.$refs.content.focus();
},
getContentEl: function getContentEl () {
return this.$refs.content
}
},
created: function created () {
document.execCommand('defaultParagraphSeparator', false, 'div');
this.defaultFont = window.getComputedStyle(document.body).fontFamily;
},
mounted: function mounted () {
var this$1 = this;
this.$nextTick(function () {
this$1.caret = new Caret(this$1.$refs.content, this$1);
this$1.$refs.content.innerHTML = this$1.value;
this$1.$nextTick(this$1.refreshToolbar);
});
},
render: function render (h) {
var this$1 = this;
var toolbars;
if (this.hasToolbar) {
var toolbarConfig = {
staticClass: "q-editor-toolbar row no-wrap scroll",
'class': [
{ 'q-editor-toolbar-separator': !this.toolbarOutline && !this.toolbarPush },
this.toolbarBackgroundClass
]
};
toolbars = [];
toolbars.push(h('div', extend({key: 'qedt_top'}, toolbarConfig), [
h('div', { staticClass: 'row no-wrap q-editor-toolbar-padding fit items-center' }, getToolbar(h, this))
]));
if (this.editLinkUrl !== null) {
toolbars.push(h('div', extend({key: 'qedt_btm'}, toolbarConfig), [
h('div', { staticClass: 'row no-wrap q-editor-toolbar-padding fit items-center' }, getLinkEditor(h, this))
]));
}
toolbars = h('div', toolbars);
}
return h(
'div',
{
staticClass: 'q-editor',
style: {
height: this.inFullscreen ? '100vh' : null
},
'class': {
disabled: this.disable,
fullscreen: this.inFullscreen,
column: this.inFullscreen
}
},
[
toolbars,
h(
'div',
{
ref: 'content',
staticClass: "q-editor-content",
style: this.inFullscreen
? this.contentStyle
: [{ minHeight: this.minHeight, height: this.height, maxHeight: this.maxHeight }, this.contentStyle],
class: [
this.contentClass,
{ col: this.inFullscreen, 'overflow-auto': this.inFullscreen }
],
attrs: { contenteditable: this.editable },
on: {
input: this.onInput,
keydown: this.onKeydown,
click: this.refreshToolbar,
blur: function () {
this$1.caret.save();
}
}
}
)
]
)
}
}
var FabMixin = {
props: {
outline: Boolean,
push: Boolean,
flat: Boolean,
color: String,
textColor: String,
glossy: Boolean
}
}
var QFab = {
name: 'q-fab',
mixins: [FabMixin, ModelToggleMixin],
provide: function provide () {
return {
__qFabClose: this.hide
}
},
props: {
icon: String,
activeIcon: String,
direction: {
type: String,
default: 'right'
}
},
watch: {
$route: function $route () {
this.hide();
}
},
created: function created () {
if (this.value) {
this.show();
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-fab z-fab row inline justify-center',
'class': {
'q-fab-opened': this.showing
}
}, [
h(QBtn, {
props: {
fab: true,
outline: this.outline,
push: this.push,
flat: this.flat,
color: this.color,
textColor: this.textColor,
glossy: this.glossy
},
on: {
click: this.toggle
}
}, [
this.$slots.tooltip,
h(QIcon, {
staticClass: 'q-fab-icon absolute-full',
props: { name: this.icon || this.$q.icon.fab.icon }
}),
h(QIcon, {
staticClass: 'q-fab-active-icon absolute-full',
props: { name: this.activeIcon || this.$q.icon.fab.activeIcon }
})
]),
h('div', {
staticClass: 'q-fab-actions flex no-wrap inline items-center',
'class': ("q-fab-" + (this.direction))
}, [
this.$slots.default
])
])
}
}
var QFabAction = {
name: 'q-fab-action',
mixins: [FabMixin],
inject: {
__qFabClose: {
default: function default$1 () {
console.error('QFabAction needs to be child of QFab');
}
}
},
props: {
icon: {
type: String,
required: true
}
},
methods: {
click: function click (e) {
var this$1 = this;
this.__qFabClose().then(function () {
this$1.$emit('click', e);
});
}
},
render: function render (h) {
return h(QBtn, {
props: {
fabMini: true,
outline: this.outline,
push: this.push,
flat: this.flat,
color: this.color,
textColor: this.textColor,
glossy: this.glossy,
icon: this.icon
},
on: {
click: this.click
}
}, [
this.$slots.default
])
}
}
var QField = {
name: 'q-field',
props: {
inset: {
type: String,
validator: function (v) { return ['icon', 'label', 'full'].includes(v); }
},
label: String,
count: {
type: [Number, Boolean],
default: false
},
error: Boolean,
errorLabel: String,
warning: Boolean,
warningLabel: String,
helper: String,
icon: String,
dark: Boolean,
orientation: {
type: String,
validator: function (v) { return ['vertical', 'horizontal'].includes(v); }
},
labelWidth: {
type: [Number, String],
default: 5,
validator: function validator (val) {
var v = parseInt(val, 10);
return v > 0 && v < 13
}
}
},
data: function data () {
return {
input: {}
}
},
computed: {
hasError: function hasError () {
return this.input.error || this.error
},
hasWarning: function hasWarning () {
return !this.hasError && (this.input.warning || this.warning)
},
hasBottom: function hasBottom () {
return (this.hasError && this.errorLabel) ||
(this.hasWarning && this.warningLabel) ||
this.helper ||
this.count
},
hasLabel: function hasLabel () {
return this.label || this.$slots.label || ['label', 'full'].includes(this.inset)
},
childHasLabel: function childHasLabel () {
return this.input.floatLabel || this.input.stackLabel
},
isDark: function isDark () {
return this.input.dark || this.dark
},
insetIcon: function insetIcon () {
return ['icon', 'full'].includes(this.inset)
},
hasNoInput: function hasNoInput () {
return !this.input.$options || this.input.__needsBorder
},
counter: function counter () {
if (this.count) {
var length = this.input.length || '0';
return Number.isInteger(this.count)
? (length + " / " + (this.count))
: length
}
},
classes: function classes () {
return {
'q-field-responsive': !this.isVertical && !this.isHorizontal,
'q-field-vertical': this.isVertical,
'q-field-horizontal': this.isHorizontal,
'q-field-floating': this.childHasLabel,
'q-field-no-label': !this.label && !this.$slots.label,
'q-field-with-error': this.hasError,
'q-field-with-warning': this.hasWarning,
'q-field-dark': this.isDark
}
},
computedLabelWidth: function computedLabelWidth () {
return parseInt(this.labelWidth, 10)
},
isVertical: function isVertical () {
return this.orientation === 'vertical' || this.computedLabelWidth === 12
},
isHorizontal: function isHorizontal () {
return this.orientation === 'horizontal'
},
labelClasses: function labelClasses () {
return this.isVertical
? "col-12"
: (this.isHorizontal ? ("col-" + (this.labelWidth)) : ("col-xs-12 col-sm-" + (this.labelWidth)))
},
inputClasses: function inputClasses () {
return this.isVertical
? "col-xs-12"
: (this.isHorizontal ? 'col' : 'col-xs-12 col-sm')
}
},
provide: function provide () {
return {
__field: this
}
},
methods: {
__registerInput: function __registerInput (vm) {
this.input = vm;
},
__unregisterInput: function __unregisterInput () {
this.input = {};
},
__getBottomContent: function __getBottomContent (h) {
if (this.hasError && this.errorLabel) {
return h('div', { staticClass: 'q-field-error col' }, this.errorLabel)
}
if (this.hasWarning && this.warningLabel) {
return h('div', { staticClass: 'q-field-warning col' }, this.warningLabel)
}
if (this.helper) {
return h('div', { staticClass: 'q-field-helper col' }, this.helper)
}
return h('div', { staticClass: 'col' })
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-field row no-wrap items-start',
'class': this.classes
}, [
this.icon
? h(QIcon, {
props: { name: this.icon },
staticClass: 'q-field-icon q-field-margin'
})
: (this.insetIcon ? h('div', { staticClass: 'q-field-icon' }) : null),
h('div', { staticClass: 'row col' }, [
this.hasLabel
? h('div', {
staticClass: 'q-field-label q-field-margin',
'class': this.labelClasses
}, [
h('div', { staticClass: 'q-field-label-inner row items-center' }, [
this.label,
this.$slots.label
])
])
: null,
h('div', {
staticClass: 'q-field-content',
'class': this.inputClasses
}, [
this.$slots.default,
this.hasBottom
? h('div', {
staticClass: 'q-field-bottom row no-wrap',
'class': { 'q-field-no-input': this.hasNoInput }
}, [
this.__getBottomContent(h),
this.counter
? h('div', { staticClass: 'q-field-counter col-auto' }, [ this.counter ])
: null
])
: null
])
])
])
}
}
var QFieldReset = {
name: 'q-field-reset',
provide: function provide () {
return {
__field: undefined
}
},
render: function render (h) {
return h('div', [
this.$slots.default
])
}
}
var QInfiniteScroll = {
name: 'q-infinite-scroll',
props: {
handler: {
type: Function,
required: true
},
inline: Boolean,
offset: {
type: Number,
default: 0
}
},
data: function data () {
return {
index: 0,
fetching: false,
working: true
}
},
methods: {
poll: function poll () {
if (this.fetching || !this.working) {
return
}
var
containerHeight = height(this.scrollContainer),
containerBottom = offset(this.scrollContainer).top + containerHeight,
triggerPosition = offset(this.element).top + height(this.element) - (this.offset || containerHeight);
if (triggerPosition < containerBottom) {
this.loadMore();
}
},
loadMore: function loadMore () {
var this$1 = this;
if (this.fetching || !this.working) {
return
}
this.index++;
this.fetching = true;
this.handler(this.index, function (stopLoading) {
this$1.fetching = false;
if (stopLoading) {
this$1.stop();
return
}
if (this$1.element.closest('body')) {
this$1.poll();
}
});
},
reset: function reset () {
this.index = 0;
},
resume: function resume () {
this.working = true;
this.scrollContainer.addEventListener('scroll', this.poll);
this.poll();
},
stop: function stop () {
this.working = false;
this.scrollContainer.removeEventListener('scroll', this.poll);
}
},
mounted: function mounted () {
var this$1 = this;
this.$nextTick(function () {
this$1.poll = debounce(this$1.poll, 50);
this$1.element = this$1.$refs.content;
this$1.scrollContainer = this$1.inline ? this$1.$el : getScrollTarget(this$1.$el);
if (this$1.working) {
this$1.scrollContainer.addEventListener('scroll', this$1.poll);
}
this$1.poll();
});
},
beforeDestroy: function beforeDestroy () {
this.scrollContainer.removeEventListener('scroll', this.poll);
},
render: function render (h) {
return h('div', { staticClass: 'q-infinite-scroll' }, [
h('div', {
ref: 'content',
staticClass: 'q-infinite-scroll-content'
}, [ this.$slots.default ]),
h('div', {
staticClass: 'q-infinite-scroll-message',
directives: [{
name: 'show',
value: this.fetching
}]
}, [
this.$slots.message
])
])
}
}
var QInnerLoading = {
name: 'q-inner-loading',
props: {
dark: Boolean,
visible: Boolean,
size: {
type: [String, Number],
default: 42
},
color: String
},
render: function render (h) {
if (!this.visible) {
return
}
return h('div', {
staticClass: 'q-inner-loading animate-fade absolute-full column flex-center',
'class': { dark: this.dark }
}, [
this.$slots.default ||
h(QSpinner, {
props: {
size: this.size,
color: this.color
}
})
])
}
}
var QKnob = {
name: 'q-knob',
directives: {
TouchPan: TouchPan
},
props: {
value: {
type: Number,
required: true
},
min: {
type: Number,
default: 0
},
max: {
type: Number,
default: 100
},
color: String,
trackColor: {
type: String,
default: 'grey-3'
},
lineWidth: {
type: String,
default: '6px'
},
size: {
type: String,
default: '100px'
},
step: {
type: Number,
default: 1
},
decimals: Number,
disable: Boolean,
readonly: Boolean
},
computed: {
classes: function classes () {
var cls = [];
if (this.disable) {
cls.push('disabled');
}
if (!this.readonly) {
cls.push('cursor-pointer');
}
if (this.color) {
cls.push(("text-" + (this.color)));
}
return cls
},
svgStyle: function svgStyle () {
return {
'stroke-dasharray': '295.31px, 295.31px',
'stroke-dashoffset': (295.31 * (1.0 - (this.model - this.min) / (this.max - this.min))) + 'px',
'transition': this.dragging ? '' : 'stroke-dashoffset 0.6s ease 0s, stroke 0.6s ease'
}
},
editable: function editable () {
return !this.disable && !this.readonly
},
computedDecimals: function computedDecimals () {
return this.decimals !== void 0 ? this.decimals || 0 : (String(this.step).trim('0').split('.')[1] || '').length
}
},
data: function data () {
return {
model: this.value,
dragging: false
}
},
watch: {
value: function value (value$1) {
var this$1 = this;
if (value$1 < this.min) {
this.$emit('input', this.min);
this.model = this.min;
this.$nextTick(function () {
if (this$1.model !== this$1.value) {
this$1.$emit('change', this$1.model);
}
});
}
else if (value$1 > this.max) {
this.$emit('input', this.max);
this.model = this.max;
this.$nextTick(function () {
if (this$1.model !== this$1.value) {
this$1.$emit('change', this$1.model);
}
});
}
else {
this.model = this.computedDecimals
? parseFloat(value$1.toFixed(this.computedDecimals))
: value$1;
}
}
},
methods: {
__pan: function __pan (event) {
if (!this.editable) {
return
}
if (event.isFinal) {
this.__dragStop(event.evt);
}
else if (event.isFirst) {
this.__dragStart(event.evt);
}
else {
this.__dragMove(event.evt);
}
},
__dragStart: function __dragStart (ev) {
if (!this.editable) {
return
}
stopAndPrevent(ev);
this.centerPosition = this.__getCenter();
this.dragging = true;
this.__onInput(ev);
},
__dragMove: function __dragMove (ev) {
if (!this.dragging || !this.editable) {
return
}
stopAndPrevent(ev);
this.__onInput(ev, this.centerPosition);
},
__dragStop: function __dragStop (ev) {
var this$1 = this;
if (!this.editable) {
return
}
stopAndPrevent(ev);
setTimeout(function () {
this$1.dragging = false;
}, 100);
this.__onInput(ev, this.centerPosition, true, true);
},
__onInput: function __onInput (ev, center, emitChange, dragStop) {
var this$1 = this;
if ( center === void 0 ) center = this.__getCenter();
if (!this.editable) {
return
}
var
pos = position(ev),
height$$1 = Math.abs(pos.top - center.top),
distance = Math.sqrt(
Math.pow(Math.abs(pos.top - center.top), 2) +
Math.pow(Math.abs(pos.left - center.left), 2)
),
angle = Math.asin(height$$1 / distance) * (180 / Math.PI);
if (pos.top < center.top) {
angle = center.left < pos.left ? 90 - angle : 270 + angle;
}
else {
angle = center.left < pos.left ? angle + 90 : 270 - angle;
}
var
model = this.min + (angle / 360) * (this.max - this.min),
modulo = model % this.step;
var value = between(
model - modulo + (Math.abs(modulo) >= this.step / 2 ? (modulo < 0 ? -1 : 1) * this.step : 0),
this.min,
this.max
);
if (this.computedDecimals) {
value = parseFloat(value.toFixed(this.computedDecimals));
}
this.model = value;
this.$emit('input', value);
this.$nextTick(function () {
if (emitChange && JSON.stringify(value) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', value);
}
if (dragStop) {
this$1.$emit('dragend', value);
}
});
},
__getCenter: function __getCenter () {
var knobOffset = offset(this.$el);
return {
top: knobOffset.top + height(this.$el) / 2,
left: knobOffset.left + width(this.$el) / 2
}
}
},
render: function render (h) {
var this$1 = this;
return h('div', {
staticClass: 'q-knob non-selectable',
'class': this.classes,
style: {
width: this.size,
height: this.size
}
}, [
h('div', {
on: {
click: function (e) { return this$1.__onInput(e, undefined, true); }
},
directives: [{
name: 'touch-pan',
value: this.__pan
}]
}, [
h('svg', { attrs: { viewBox: '0 0 100 100' } }, [
h('path', {
attrs: {
d: 'M 50,50 m 0,-47 a 47,47 0 1 1 0,94 a 47,47 0 1 1 0,-94',
'fill-opacity': '0',
stroke: 'currentColor',
'stroke-width': this.lineWidth
},
'class': ("text-" + (this.trackColor))
}),
h('path', {
attrs: {
d: 'M 50,50 m 0,-47 a 47,47 0 1 1 0,94 a 47,47 0 1 1 0,-94',
'fill-opacity': '0',
stroke: 'currentColor',
'stroke-linecap': 'round',
'stroke-width': this.lineWidth
},
style: this.svgStyle
})
]),
h('div', {
staticClass: 'q-knob-label row flex-center content-center'
}, [
this.$slots.default
? this.$slots.default
: h('span', [ this.model ])
])
])
])
}
}
var QLayout = {
name: 'q-layout',
provide: function provide () {
return {
layout: this
}
},
props: {
view: {
type: String,
default: 'hhh lpr fff',
validator: function (v) { return /^(h|l)h(h|r) lpr (f|l)f(f|r)$/.test(v.toLowerCase()); }
}
},
data: function data () {
var ref = viewport();
var height$$1 = ref.height;
var width$$1 = ref.width;
return {
height: height$$1, // window height
width: width$$1, // window width
header: {
size: 0,
offset: 0,
space: true
},
right: {
size: 300,
offset: 0,
space: false
},
footer: {
size: 0,
offset: 0,
space: true
},
left: {
size: 300,
offset: 0,
space: false
},
scrollHeight: 0,
scroll: {
position: 0,
direction: 'down'
}
}
},
computed: {
rows: function rows () {
var rows = this.view.toLowerCase().split(' ');
return {
top: rows[0].split(''),
middle: rows[1].split(''),
bottom: rows[2].split('')
}
}
},
render: function render (h) {
return h('div', { staticClass: 'q-layout' }, [
h(QScrollObservable, {
on: { scroll: this.__onPageScroll }
}),
h(QResizeObservable, {
on: { resize: this.__onLayoutResize }
}),
h(QWindowResizeObservable, {
on: { resize: this.__onWindowResize }
}),
this.$slots.default
])
},
methods: {
__animate: function __animate () {
var this$1 = this;
if (this.timer) {
clearTimeout(this.timer);
}
else {
document.body.classList.add('q-layout-animate');
}
this.timer = setTimeout(function () {
document.body.classList.remove('q-layout-animate');
this$1.timer = null;
}, 150);
},
__onPageScroll: function __onPageScroll (data) {
this.scroll = data;
this.$emit('scroll', data);
},
__onLayoutResize: function __onLayoutResize () {
this.scrollHeight = getScrollHeight(this.$el);
this.$emit('scrollHeight', this.scrollHeight);
},
__onWindowResize: function __onWindowResize (ref) {
var height$$1 = ref.height;
var width$$1 = ref.width;
if (this.height !== height$$1) {
this.height = height$$1;
}
if (this.width !== width$$1) {
this.width = width$$1;
}
}
}
}
var bodyClassBelow = 'with-layout-drawer-opened';
var bodyClassAbove = 'with-layout-drawer-opened-above';
var duration = 150;
var QLayoutDrawer = {
name: 'q-layout-drawer',
inject: {
layout: {
default: function default$1 () {
console.error('QLayoutDrawer needs to be child of QLayout');
}
}
},
mixins: [ModelToggleMixin],
directives: {
TouchPan: TouchPan
},
props: {
overlay: Boolean,
side: {
type: String,
default: 'left',
validator: function (v) { return ['left', 'right'].includes(v); }
},
breakpoint: {
type: Number,
default: 992
},
behavior: {
type: String,
validator: function (v) { return ['default', 'desktop', 'mobile'].includes(v); },
default: 'default'
},
contentStyle: Object,
contentClass: [String, Object, Array],
noSwipeOpen: Boolean,
noSwipeClose: Boolean
},
data: function data () {
var
largeScreenState = this.value !== void 0 ? this.value : true,
showing = this.behavior !== 'mobile' && this.breakpoint < this.layout.width && !this.overlay
? largeScreenState
: false;
if (this.value !== void 0 && this.value !== showing) {
this.$emit('input', showing);
}
return {
showing: showing,
belowBreakpoint: (
this.behavior === 'mobile' ||
(this.behavior !== 'desktop' && this.breakpoint >= this.layout.width)
),
largeScreenState: largeScreenState,
mobileOpened: false,
size: 300,
inTransit: false,
position: 0,
percentage: 0
}
},
watch: {
belowBreakpoint: function belowBreakpoint (val, old) {
if (this.mobileOpened) {
return
}
if (val) { // from lg to xs
if (!this.overlay) {
this.largeScreenState = this.showing;
}
// ensure we close it for small screen
this.hide();
}
else if (!this.overlay) { // from xs to lg
this[this.largeScreenState ? 'show' : 'hide']();
}
},
behavior: function behavior (val) {
this.__updateLocal('belowBreakpoint', (
val === 'mobile' ||
(val !== 'desktop' && this.breakpoint >= this.layout.width)
));
},
breakpoint: function breakpoint (val) {
this.__updateLocal('belowBreakpoint', (
this.behavior === 'mobile' ||
(this.behavior !== 'desktop' && val >= this.layout.width)
));
},
'layout.width': function layout_width (val) {
this.__updateLocal('belowBreakpoint', (
this.behavior === 'mobile' ||
(this.behavior !== 'desktop' && this.breakpoint >= val)
));
},
offset: function offset$$1 (val) {
this.__update('offset', val);
},
onScreenOverlay: function onScreenOverlay () {
if (this.animateOverlay) {
this.layout.__animate();
}
},
onLayout: function onLayout (val) {
this.__update('space', val);
this.layout.__animate();
},
$route: function $route () {
if (this.mobileOpened) {
this.hide();
return
}
if (this.onScreenOverlay) {
this.hide();
}
}
},
computed: {
rightSide: function rightSide () {
return this.side === 'right'
},
offset: function offset$$1 () {
return this.showing && !this.mobileOpened
? this.size
: 0
},
fixed: function fixed () {
return this.overlay || this.layout.view.indexOf(this.rightSide ? 'R' : 'L') > -1
},
onLayout: function onLayout () {
return this.showing && !this.mobileView && !this.overlay
},
onScreenOverlay: function onScreenOverlay () {
return this.showing && !this.mobileView && this.overlay
},
backdropClass: function backdropClass () {
return {
'q-layout-backdrop-transition': !this.inTransit,
'no-pointer-events': !this.inTransit && !this.showing
}
},
mobileView: function mobileView () {
return this.belowBreakpoint || this.mobileOpened
},
headerSlot: function headerSlot () {
return this.overlay
? false
: (this.rightSide
? this.layout.rows.top[2] === 'r'
: this.layout.rows.top[0] === 'l'
)
},
footerSlot: function footerSlot () {
return this.overlay
? false
: (this.rightSide
? this.layout.rows.bottom[2] === 'r'
: this.layout.rows.bottom[0] === 'l'
)
},
backdropStyle: function backdropStyle () {
return { backgroundColor: ("rgba(0,0,0," + (this.percentage * 0.4) + ")") }
},
belowClass: function belowClass () {
return {
'fixed': true,
'on-top': true,
'on-screen': this.showing,
'off-screen': !this.showing,
'transition-generic': !this.inTransit,
'top-padding': this.fixed || this.headerSlot
}
},
belowStyle: function belowStyle () {
if (this.inTransit) {
return cssTransform(("translateX(" + (this.position) + "px)"))
}
},
aboveClass: function aboveClass () {
var onScreen = this.onLayout || this.onScreenOverlay;
return {
'off-screen': !onScreen,
'on-screen': onScreen,
'fixed': this.fixed || !this.onLayout,
'top-padding': this.fixed || this.headerSlot
}
},
aboveStyle: function aboveStyle () {
var css$$1 = {};
if (this.layout.header.space && !this.headerSlot) {
if (this.fixed) {
css$$1.top = (this.layout.header.offset) + "px";
}
else if (this.layout.header.space) {
css$$1.top = (this.layout.header.size) + "px";
}
}
if (this.layout.footer.space && !this.footerSlot) {
if (this.fixed) {
css$$1.bottom = (this.layout.footer.offset) + "px";
}
else if (this.layout.footer.space) {
css$$1.bottom = (this.layout.footer.size) + "px";
}
}
return css$$1
},
computedStyle: function computedStyle () {
return [this.contentStyle, this.mobileView ? this.belowStyle : this.aboveStyle]
},
computedClass: function computedClass () {
return [this.contentClass, this.mobileView ? this.belowClass : this.aboveClass]
}
},
render: function render (h) {
var child = [];
if (this.mobileView) {
if (!this.noSwipeOpen) {
child.push(h('div', {
staticClass: ("q-layout-drawer-opener fixed-" + (this.side)),
directives: [{
name: 'touch-pan',
modifiers: { horizontal: true },
value: this.__openByTouch
}]
}));
}
child.push(h('div', {
staticClass: 'fullscreen q-layout-backdrop',
'class': this.backdropClass,
style: this.backdropStyle,
on: { click: this.hide },
directives: [{
name: 'touch-pan',
modifiers: { horizontal: true },
value: this.__closeByTouch
}]
}));
}
return h('div', { staticClass: 'q-drawer-container' }, child.concat([
h('aside', {
staticClass: ("q-layout-drawer q-layout-drawer-" + (this.side) + " scroll q-layout-transition"),
'class': this.computedClass,
style: this.computedStyle,
attrs: this.$attrs,
listeners: this.$listeners,
directives: this.mobileView && !this.noSwipeClose ? [{
name: 'touch-pan',
modifiers: { horizontal: true },
value: this.__closeByTouch
}] : null
}, [
this.$slots.default,
h(QResizeObservable, {
on: { resize: this.__onResize }
})
])
]))
},
created: function created () {
var this$1 = this;
if (this.onLayout) {
this.__update('space', true);
this.__update('offset', this.offset);
}
this.$nextTick(function () {
this$1.animateOverlay = true;
});
},
beforeDestroy: function beforeDestroy () {
clearTimeout(this.timer);
this.__update('size', 0);
this.__update('space', false);
},
methods: {
__openByTouch: function __openByTouch (evt) {
if (!this.belowBreakpoint) {
return
}
var
width$$1 = this.size,
position = between(evt.distance.x, 0, width$$1);
if (evt.isFinal) {
var opened = position >= Math.min(75, width$$1);
this.inTransit = false;
if (opened) { this.show(); }
else { this.percentage = 0; }
return
}
this.position = this.rightSide
? Math.max(width$$1 - position, 0)
: Math.min(0, position - width$$1);
this.percentage = between(position / width$$1, 0, 1);
if (evt.isFirst) {
document.body.classList.add(bodyClassBelow);
this.inTransit = true;
}
},
__closeByTouch: function __closeByTouch (evt) {
if (!this.mobileOpened) {
return
}
var
width$$1 = this.size,
position = evt.direction === this.side
? between(evt.distance.x, 0, width$$1)
: 0;
if (evt.isFinal) {
var opened = Math.abs(position) < Math.min(75, width$$1);
this.inTransit = false;
if (opened) { this.percentage = 1; }
else { this.hide(); }
return
}
this.position = (this.rightSide ? 1 : -1) * position;
this.percentage = between(1 - position / width$$1, 0, 1);
if (evt.isFirst) {
this.inTransit = true;
}
},
__show: function __show () {
var this$1 = this;
if (this.belowBreakpoint) {
this.mobileOpened = true;
this.percentage = 1;
}
document.body.classList.add(this.belowBreakpoint ? bodyClassBelow : bodyClassAbove);
clearTimeout(this.timer);
this.timer = setTimeout(function () {
if (this$1.showPromise) {
this$1.showPromise.then(function () {
document.body.classList.remove(bodyClassAbove);
});
this$1.showPromiseResolve();
}
}, duration);
},
__hide: function __hide () {
var this$1 = this;
this.mobileOpened = false;
this.percentage = 0;
document.body.classList.remove(bodyClassAbove);
document.body.classList.remove(bodyClassBelow);
clearTimeout(this.timer);
this.timer = setTimeout(function () {
this$1.hidePromise && this$1.hidePromiseResolve();
}, duration);
},
__onResize: function __onResize (ref) {
var width$$1 = ref.width;
this.__update('size', width$$1);
this.__updateLocal('size', width$$1);
},
__update: function __update (prop, val) {
if (this.layout[this.side][prop] !== val) {
this.layout[this.side][prop] = val;
}
},
__updateLocal: function __updateLocal (prop, val) {
if (this[prop] !== val) {
this[prop] = val;
}
}
}
}
var QLayoutFooter = {
name: 'q-layout-footer',
inject: {
layout: {
default: function default$1 () {
console.error('QLayoutFooter needs to be child of QLayout');
}
}
},
props: {
value: {
type: Boolean,
default: true
},
reveal: Boolean
},
data: function data () {
return {
size: 0,
revealed: true
}
},
watch: {
value: function value (val) {
this.__update('space', val);
this.__updateLocal('revealed', true);
this.layout.__animate();
},
offset: function offset (val) {
this.__update('offset', val);
},
revealed: function revealed () {
this.layout.__animate();
},
'layout.scroll': function layout_scroll () {
this.__updateRevealed();
},
'layout.scrollHeight': function layout_scrollHeight () {
this.__updateRevealed();
},
size: function size () {
this.__updateRevealed();
}
},
computed: {
fixed: function fixed () {
return this.reveal || this.layout.view.indexOf('F') > -1
},
offset: function offset () {
if (!this.value) {
return 0
}
if (this.fixed) {
return this.revealed ? this.size : 0
}
var offset = this.layout.height + this.layout.scroll.position + this.size - this.layout.scrollHeight;
return offset > 0 ? offset : 0
},
computedClass: function computedClass () {
return {
'fixed-bottom': this.fixed,
'absolute-bottom': !this.fixed,
'hidden': !this.value && !this.fixed,
'q-layout-footer-hidden': !this.value || (this.fixed && !this.revealed)
}
},
computedStyle: function computedStyle () {
var
view = this.layout.rows.bottom,
css = {};
if (view[0] === 'l' && this.layout.left.space) {
css.marginLeft = (this.layout.left.size) + "px";
}
if (view[2] === 'r' && this.layout.right.space) {
css.marginRight = (this.layout.right.size) + "px";
}
return css
}
},
render: function render (h) {
return h('footer', {
staticClass: 'q-layout-footer q-layout-transition',
'class': this.computedClass,
style: this.computedStyle
}, [
h(QResizeObservable, {
on: { resize: this.__onResize }
}),
this.$slots.default
])
},
created: function created () {
this.__update('space', this.value);
},
destroyed: function destroyed () {
this.__update('size', 0);
this.__update('space', false);
},
methods: {
__onResize: function __onResize (ref) {
var height = ref.height;
this.__updateLocal('size', height);
this.__update('size', height);
},
__update: function __update (prop, val) {
if (this.layout.footer[prop] !== val) {
this.layout.footer[prop] = val;
}
},
__updateLocal: function __updateLocal (prop, val) {
if (this[prop] !== val) {
this[prop] = val;
}
},
__updateRevealed: function __updateRevealed () {
if (!this.reveal) {
return
}
var
scroll = this.layout.scroll,
scrollHeight = this.layout.scrollHeight,
height = this.layout.height;
this.__updateLocal('revealed',
scroll.direction === 'up' ||
scroll.position - scroll.inflexionPosition < 100 ||
scrollHeight - height - scroll.position < this.size + 300
);
}
}
}
var QLayoutHeader = {
name: 'q-layout-header',
inject: {
layout: {
default: function default$1 () {
console.error('QLayoutHeader needs to be child of QLayout');
}
}
},
props: {
value: {
type: Boolean,
default: true
},
reveal: Boolean,
revealOffset: {
type: Number,
default: 250
}
},
data: function data () {
return {
size: 0,
revealed: true
}
},
watch: {
value: function value (val) {
this.__update('space', val);
this.__updateLocal('revealed', true);
this.layout.__animate();
},
offset: function offset (val) {
this.__update('offset', val);
},
revealed: function revealed () {
this.layout.__animate();
},
'layout.scroll': function layout_scroll (scroll) {
if (!this.reveal) {
return
}
this.__updateLocal('revealed',
scroll.direction === 'up' ||
scroll.position <= this.revealOffset ||
scroll.position - scroll.inflexionPosition < 100
);
}
},
computed: {
fixed: function fixed () {
return this.reveal || this.layout.view.indexOf('H') > -1
},
offset: function offset () {
if (!this.value) {
return 0
}
if (this.fixed) {
return this.revealed ? this.size : 0
}
var offset = this.size - this.layout.scroll.position;
return offset > 0 ? offset : 0
},
computedClass: function computedClass () {
return {
'fixed-top': this.fixed,
'absolute-top': !this.fixed,
'q-layout-header-hidden': !this.value || (this.fixed && !this.revealed)
}
},
computedStyle: function computedStyle () {
var
view = this.layout.rows.top,
css = {};
if (view[0] === 'l' && this.layout.left.space) {
css.marginLeft = (this.layout.left.size) + "px";
}
if (view[2] === 'r' && this.layout.right.space) {
css.marginRight = (this.layout.right.size) + "px";
}
return css
}
},
render: function render (h) {
return h('header', {
staticClass: 'q-layout-header q-layout-transition',
'class': this.computedClass,
style: this.computedStyle
}, [
h(QResizeObservable, {
on: { resize: this.__onResize }
}),
this.$slots.default
])
},
created: function created () {
this.__update('space', this.value);
},
destroyed: function destroyed () {
this.__update('size', 0);
this.__update('space', false);
},
methods: {
__onResize: function __onResize (ref) {
var height = ref.height;
this.__updateLocal('size', height);
this.__update('size', height);
},
__update: function __update (prop, val) {
if (this.layout.header[prop] !== val) {
this.layout.header[prop] = val;
}
},
__updateLocal: function __updateLocal (prop, val) {
if (this[prop] !== val) {
this[prop] = val;
}
}
}
}
var QPage = {
name: 'q-page',
inject: {
pageContainer: {
default: function default$1 () {
console.error('QPage needs to be child of QPageContainer');
}
},
layout: {}
},
props: {
padding: Boolean
},
computed: {
computedStyle: function computedStyle () {
var offset =
(this.layout.header.space ? this.layout.header.size : 0) +
(this.layout.footer.space ? this.layout.footer.size : 0);
return {
minHeight: offset ? ("calc(100vh - " + offset + "px)") : '100vh'
}
},
computedClass: function computedClass () {
if (this.padding) {
return 'layout-padding'
}
}
},
render: function render (h) {
return h('main', {
staticClass: 'q-layout-page',
style: this.computedStyle,
'class': this.computedClass
}, [
this.$slots.default
])
}
}
var QPageContainer = {
name: 'q-page-container',
inject: {
layout: {
default: function default$1 () {
console.error('QPageContainer needs to be child of QLayout');
}
}
},
provide: {
pageContainer: true
},
computed: {
computedStyle: function computedStyle () {
var css = {};
if (this.layout.header.space) {
css.paddingTop = (this.layout.header.size) + "px";
}
if (this.layout.right.space) {
css.paddingRight = (this.layout.right.size) + "px";
}
if (this.layout.footer.space) {
css.paddingBottom = (this.layout.footer.size) + "px";
}
if (this.layout.left.space) {
css.paddingLeft = (this.layout.left.size) + "px";
}
return css
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-layout-page-container q-layout-transition',
style: this.computedStyle
}, [
this.$slots.default
])
}
}
var QPageSticky = {
name: 'q-page-sticky',
inject: {
layout: {
default: function default$1 () {
console.error('QPageSticky needs to be child of QLayout');
}
}
},
props: {
position: {
type: String,
default: 'bottom-right',
validator: function (v) { return [
'top-right', 'top-left',
'bottom-right', 'bottom-left',
'top', 'right', 'bottom', 'left'
].includes(v); }
},
offset: {
type: Array,
validator: function (v) { return v.length === 2; }
}
},
computed: {
attach: function attach () {
var pos = this.position;
return {
top: pos.indexOf('top') > -1,
right: pos.indexOf('right') > -1,
bottom: pos.indexOf('bottom') > -1,
left: pos.indexOf('left') > -1,
vertical: pos === 'top' || pos === 'bottom',
horizontal: pos === 'left' || pos === 'right'
}
},
top: function top () {
return this.layout.header.offset
},
right: function right () {
return this.layout.right.offset
},
bottom: function bottom () {
return this.layout.footer.offset
},
left: function left () {
return this.layout.left.offset
},
computedStyle: function computedStyle () {
var
attach = this.attach,
transforms = [];
if (attach.top && this.top) {
transforms.push(("translateY(" + (this.top) + "px)"));
}
else if (attach.bottom && this.bottom) {
transforms.push(("translateY(" + (-this.bottom) + "px)"));
}
if (attach.left && this.left) {
transforms.push(("translateX(" + (this.left) + "px)"));
}
else if (attach.right && this.right) {
transforms.push(("translateX(" + (-this.right) + "px)"));
}
var css$$1 = transforms.length
? cssTransform(transforms.join(' '))
: {};
if (this.offset) {
css$$1.margin = (this.offset[1]) + "px " + (this.offset[0]) + "px";
}
if (attach.vertical) {
if (this.left) {
css$$1.left = (this.left) + "px";
}
if (this.right) {
css$$1.right = (this.right) + "px";
}
}
else if (attach.horizontal) {
if (this.top) {
css$$1.top = (this.top) + "px";
}
if (this.bottom) {
css$$1.bottom = (this.bottom) + "px";
}
}
return css$$1
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-page-sticky q-layout-transition z-fixed',
'class': ("fixed-" + (this.position)),
style: this.computedStyle
}, [
this.$slots.default
])
}
}
var QPagination = {
name: 'q-pagination',
props: {
value: {
type: Number,
required: true
},
min: {
type: Number,
default: 1
},
max: {
type: Number,
required: true
},
color: {
type: String,
default: 'primary'
},
size: String,
disable: Boolean,
input: Boolean,
boundaryLinks: {
type: Boolean,
default: null
},
boundaryNumbers: {
type: Boolean,
default: null
},
directionLinks: {
type: Boolean,
default: null
},
ellipses: {
type: Boolean,
default: null
},
maxPages: {
type: Number,
default: 0,
validator: function (v) {
if (v < 0) {
console.error('maxPages should not be negative');
return false
}
return true
}
}
},
data: function data () {
return {
newPage: null
}
},
watch: {
min: function min (value) {
this.model = this.value;
},
max: function max (value) {
this.model = this.value;
}
},
computed: {
model: {
get: function get () {
return this.value
},
set: function set (val) {
var this$1 = this;
if (this.disable || !val || isNaN(val)) {
return
}
var value = between(parseInt(val, 10), this.min, this.max);
this.$emit('input', value);
this.$nextTick(function () {
if (JSON.stringify(value) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', value);
}
});
}
},
inputPlaceholder: function inputPlaceholder () {
return this.model + ' / ' + this.max
},
__boundaryLinks: function __boundaryLinks () {
return this.__getBool(this.boundaryLinks, this.input)
},
__boundaryNumbers: function __boundaryNumbers () {
return this.__getBool(this.boundaryNumbers, !this.input)
},
__directionLinks: function __directionLinks () {
return this.__getBool(this.directionLinks, this.input)
},
__ellipses: function __ellipses () {
return this.__getBool(this.ellipses, !this.input)
}
},
methods: {
set: function set (value) {
this.model = value;
},
setByOffset: function setByOffset (offset) {
this.model = this.model + offset;
},
__update: function __update () {
this.model = this.newPage;
this.newPage = null;
},
__getRepeatEasing: function __getRepeatEasing (from, step, to) {
if ( from === void 0 ) from = 300;
if ( step === void 0 ) step = 10;
if ( to === void 0 ) to = 100;
return function (cnt) { return cnt ? Math.max(to, from - cnt * cnt * step) : 100; }
},
__getBool: function __getBool (val, otherwise) {
return [true, false].includes(val)
? val
: otherwise
},
__getBtn: function __getBtn (h, props) {
return h(QBtn, extend(true, {
props: {
color: this.color,
flat: true,
size: this.size
}
}, props))
}
},
render: function render (h) {
var this$1 = this;
var
contentStart = [],
contentEnd = [],
contentMiddle = [];
if (this.__boundaryLinks) {
contentStart.push(this.__getBtn(h, {
key: 'bls',
props: {
disable: this.disable || this.value <= this.min,
icon: this.$q.icon.pagination.first
},
on: {
click: function () { return this$1.set(this$1.min); }
}
}));
contentEnd.unshift(this.__getBtn(h, {
key: 'ble',
props: {
disable: this.disable || this.value >= this.max,
icon: this.$q.icon.pagination.last
},
on: {
click: function () { return this$1.set(this$1.max); }
}
}));
}
if (this.__directionLinks) {
contentStart.push(this.__getBtn(h, {
key: 'bdp',
props: {
disable: this.disable || this.value <= this.min,
icon: this.$q.icon.pagination.prev,
repeatTimeout: this.__getRepeatEasing()
},
on: {
click: function () { return this$1.setByOffset(-1); }
}
}));
contentEnd.unshift(this.__getBtn(h, {
key: 'bdn',
props: {
disable: this.disable || this.value >= this.max,
icon: this.$q.icon.pagination.next,
repeatTimeout: this.__getRepeatEasing()
},
on: {
click: function () { return this$1.setByOffset(1); }
}
}));
}
if (this.input) {
contentMiddle.push(h(QInput, {
staticClass: 'inline no-margin no-padding',
style: {
width: ((this.inputPlaceholder.length) + "rem")
},
props: {
type: 'number',
value: this.newPage,
noNumberToggle: true,
min: this.min,
max: this.max,
color: this.color,
placeholder: this.inputPlaceholder,
disable: this.disable,
hideUnderline: true
},
on: {
input: function (value) { return (this$1.newPage = value); },
keyup: function (event) { return (event.keyCode === 13 && this$1.__update()); },
blur: function () { return this$1.__update(); }
}
}));
}
else { // is type select
var
maxPages = Math.max(
this.maxPages,
1 + (this.__ellipses ? 2 : 0) + (this.__boundaryNumbers ? 2 : 0)
),
pgFrom = this.min,
pgTo = this.max,
ellipsesStart = false,
ellipsesEnd = false,
boundaryStart = false,
boundaryEnd = false;
if (this.maxPages && maxPages < (this.max - this.min + 1)) {
maxPages = 1 + Math.floor(maxPages / 2) * 2;
pgFrom = Math.max(this.min, Math.min(this.max - maxPages + 1, this.value - Math.floor(maxPages / 2)));
pgTo = Math.min(this.max, pgFrom + maxPages - 1);
if (this.__boundaryNumbers && pgFrom > this.min) {
boundaryStart = true;
pgFrom += 1;
}
if (this.__ellipses && pgFrom > (this.min + (this.__boundaryNumbers ? 1 : 0))) {
ellipsesStart = true;
pgFrom += 1;
}
if (this.__boundaryNumbers && pgTo < this.max) {
boundaryEnd = true;
pgTo -= 1;
}
if (this.__ellipses && pgTo < (this.max - (this.__boundaryNumbers ? 1 : 0))) {
ellipsesEnd = true;
pgTo -= 1;
}
}
var style = {
minWidth: ((Math.max(1.5, String(this.max).length)) + "em")
};
if (boundaryStart) {
contentStart.push(this.__getBtn(h, {
key: 'bns',
style: style,
props: {
disable: this.disable || this.value <= this.min,
label: this.min
},
on: {
click: function () { return this$1.set(this$1.min); }
}
}));
}
if (boundaryEnd) {
contentEnd.unshift(this.__getBtn(h, {
key: 'bne',
style: style,
props: {
disable: this.disable || this.value >= this.max,
label: this.max
},
on: {
click: function () { return this$1.set(this$1.max); }
}
}));
}
if (ellipsesStart) {
contentStart.push(this.__getBtn(h, {
key: 'bes',
style: style,
props: {
disable: this.disable,
label: '…',
repeatTimeout: this.__getRepeatEasing()
},
on: {
click: function () { return this$1.set(pgFrom - 1); }
}
}));
}
if (ellipsesEnd) {
contentEnd.unshift(this.__getBtn(h, {
key: 'bee',
style: style,
props: {
disable: this.disable,
label: '…',
repeatTimeout: this.__getRepeatEasing()
},
on: {
click: function () { return this$1.set(pgTo + 1); }
}
}));
}
var loop = function ( i ) {
contentMiddle.push(this$1.__getBtn(h, {
key: (i + "." + (i === this$1.value)),
style: style,
props: {
disable: this$1.disable,
flat: i !== this$1.value,
label: i,
noRipple: true
},
on: {
click: function () { return this$1.set(i); }
}
}));
};
for (var i = pgFrom; i <= pgTo; i++) loop( i );
}
return h('div', {
staticClass: 'q-pagination',
'class': { disabled: this.disable }
}, [
contentStart,
h('div', { staticClass: 'row wrap justify-center' }, [
contentMiddle
]),
contentEnd
])
}
}
var QParallax = {
name: 'q-parallax',
props: {
src: {
type: String,
required: true
},
height: {
type: Number,
default: 500
},
speed: {
type: Number,
default: 1,
validator: function validator (value) {
return value >= 0 && value <= 1
}
}
},
data: function data () {
return {
imageHasBeenLoaded: false,
scrolling: false
}
},
watch: {
src: function src () {
this.imageHasBeenLoaded = false;
},
height: function height$$1 () {
this.__updatePos();
}
},
methods: {
__processImage: function __processImage () {
this.imageHasBeenLoaded = true;
this.__onResize();
},
__onResize: function __onResize () {
if (!this.imageHasBeenLoaded || !this.scrollTarget) {
return
}
if (this.scrollTarget === window) {
this.viewportHeight = viewport().height;
}
this.imageHeight = height(this.image);
this.__updatePos();
},
__updatePos: function __updatePos () {
if (!this.imageHasBeenLoaded) {
return
}
var containerTop, containerHeight, containerBottom, top, bottom;
if (this.scrollTarget === window) {
containerTop = 0;
containerHeight = this.viewportHeight;
containerBottom = containerHeight;
}
else {
containerTop = offset(this.scrollTarget).top;
containerHeight = height(this.scrollTarget);
containerBottom = containerTop + containerHeight;
}
top = offset(this.container).top;
bottom = top + this.height;
if (bottom > containerTop && top < containerBottom) {
var percentScrolled = (containerBottom - top) / (this.height + containerHeight);
this.__setPos(Math.round((this.imageHeight - this.height) * percentScrolled * this.speed));
}
},
__setPos: function __setPos (offset$$1) {
css(this.$refs.img, cssTransform(("translate3D(-50%," + offset$$1 + "px, 0)")));
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-parallax',
style: { height: ((this.height) + "px") }
}, [
h('div', {
staticClass: 'q-parallax-image absolute-full'
}, [
h('img', {
ref: 'img',
domProps: {
src: this.src
},
'class': { ready: this.imageHasBeenLoaded },
on: {
load: this.__processImage
}
})
]),
h('div', {
staticClass: 'q-parallax-text absolute-full column flex-center'
}, [
this.imageHasBeenLoaded
? this.$slots.default
: this.$slots.loading
])
])
},
created: function created () {
this.__setPos = frameDebounce(this.__setPos);
},
mounted: function mounted () {
var this$1 = this;
this.$nextTick(function () {
this$1.container = this$1.$el;
this$1.image = this$1.$refs.img;
this$1.scrollTarget = getScrollTarget(this$1.$el);
this$1.resizeHandler = debounce(this$1.__onResize, 50);
window.addEventListener('resize', this$1.resizeHandler);
this$1.scrollTarget.addEventListener('scroll', this$1.__updatePos);
this$1.__onResize();
});
},
beforeDestroy: function beforeDestroy () {
window.removeEventListener('resize', this.resizeHandler);
this.scrollTarget.removeEventListener('scroll', this.__updatePos);
}
}
function width$1 (val) {
return { width: (val + "%") }
}
var QProgress = {
name: 'q-progress',
props: {
percentage: {
type: Number,
default: 0
},
color: String,
stripe: Boolean,
animate: Boolean,
indeterminate: Boolean,
buffer: Number,
height: {
type: String,
default: '4px'
}
},
computed: {
model: function model () {
return between(this.percentage, 0, 100)
},
bufferModel: function bufferModel () {
return between(this.buffer || 0, 0, 100 - this.model)
},
bufferStyle: function bufferStyle () {
return width$1(this.bufferModel)
},
trackStyle: function trackStyle () {
return width$1(this.buffer ? 100 - this.buffer : 100)
},
computedClass: function computedClass () {
if (this.color) {
return ("text-" + (this.color))
}
},
computedStyle: function computedStyle () {
return { height: this.height }
},
modelClass: function modelClass () {
return {
animate: this.animate,
stripe: this.stripe,
indeterminate: this.indeterminate
}
},
modelStyle: function modelStyle () {
return width$1(this.model)
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-progress',
style: this.computedStyle,
'class': this.computedClass
}, [
this.buffer && !this.indeterminate
? h('div', {
staticClass: 'q-progress-buffer',
style: this.bufferStyle
})
: null,
h('div', {
staticClass: 'q-progress-track',
style: this.trackStyle
}),
h('div', {
staticClass: 'q-progress-model',
style: this.modelStyle,
'class': this.modelClass
})
])
}
}
var QPullToRefresh = {
name: 'q-pull-to-refresh',
directives: {
TouchPan: TouchPan
},
props: {
handler: {
type: Function,
required: true
},
distance: {
type: Number,
default: 35
},
pullMessage: String,
releaseMessage: String,
refreshMessage: String,
refreshIcon: String,
inline: Boolean,
disable: Boolean
},
data: function data () {
var height$$1 = 65;
return {
state: 'pull',
pullPosition: -height$$1,
height: height$$1,
animating: false,
pulling: false,
scrolling: false
}
},
computed: {
message: function message () {
switch (this.state) {
case 'pulled':
return this.releaseMessage || this.$q.i18n.pullToRefresh.release
case 'refreshing':
return this.refreshMessage || this.$q.i18n.pullToRefresh.refresh
case 'pull':
default:
return this.pullMessage || this.$q.i18n.pullToRefresh.pull
}
},
style: function style$$1 () {
return cssTransform(("translateY(" + (this.pullPosition) + "px)"))
}
},
methods: {
__pull: function __pull (event) {
if (this.disable) {
return
}
if (event.isFinal) {
this.scrolling = false;
this.pulling = false;
if (this.scrolling) {
return
}
if (this.state === 'pulled') {
this.state = 'refreshing';
this.__animateTo(0);
this.trigger();
}
else if (this.state === 'pull') {
this.__animateTo(-this.height);
}
return
}
if (this.animating || this.scrolling || this.state === 'refreshing') {
return true
}
var top = getScrollPosition(this.scrollContainer);
if (top !== 0 || (top === 0 && event.direction !== 'down')) {
this.scrolling = true;
if (this.pulling) {
this.pulling = false;
this.state = 'pull';
this.__animateTo(-this.height);
}
return true
}
event.evt.preventDefault();
this.pulling = true;
this.pullPosition = -this.height + Math.max(0, Math.pow(event.distance.y, 0.85));
this.state = this.pullPosition > this.distance ? 'pulled' : 'pull';
},
__animateTo: function __animateTo (target, done, previousCall) {
var this$1 = this;
if (!previousCall && this.animationId) {
cancelAnimationFrame(this.animating);
}
this.pullPosition -= (this.pullPosition - target) / 7;
if (this.pullPosition - target > 1) {
this.animating = window.requestAnimationFrame(function () {
this$1.__animateTo(target, done, true);
});
}
else {
this.animating = window.requestAnimationFrame(function () {
this$1.pullPosition = target;
this$1.animating = false;
done && done();
});
}
},
trigger: function trigger () {
var this$1 = this;
this.handler(function () {
this$1.__animateTo(-this$1.height, function () {
this$1.state = 'pull';
});
});
}
},
mounted: function mounted () {
var this$1 = this;
this.$nextTick(function () {
this$1.scrollContainer = this$1.inline ? this$1.$el.parentNode : getScrollTarget(this$1.$el);
});
},
render: function render (h) {
return h('div', { staticClass: 'pull-to-refresh' }, [
h('div', {
staticClass: 'pull-to-refresh-container',
style: this.style,
directives: [{
name: 'touch-pan',
modifiers: {
vertical: true,
scroll: true
},
value: this.__pull
}]
}, [
h('div', { staticClass: 'pull-to-refresh-message row flex-center' }, [
h(QIcon, {
'class': { 'rotate-180': this.state === 'pulled' },
props: { name: this.$q.icon.pullToRefresh.arrow },
directives: [{
name: 'show',
value: this.state !== 'refreshing'
}]
}),
h(QIcon, {
staticClass: 'animate-spin',
props: { name: this.refreshIcon || this.$q.icon.pullToRefresh.refresh },
directives: [{
name: 'show',
value: this.state === 'refreshing'
}]
}),
(" " + (this.message))
]),
this.$slots.default
])
])
}
}
var dragType = {
MIN: 0,
RANGE: 1,
MAX: 2
};
var QRange = {
name: 'q-range',
mixins: [SliderMixin],
props: {
value: {
type: Object,
required: true,
validator: function validator (value) {
return typeof value.min !== 'undefined' && typeof value.max !== 'undefined'
}
},
dragRange: Boolean,
dragOnlyRange: Boolean,
leftLabelColor: String,
leftLabelValue: String,
rightLabelColor: String,
rightLabelValue: String
},
data: function data () {
return {
model: extend({}, this.value),
dragging: false,
currentMinPercentage: (this.value.min - this.min) / (this.max - this.min),
currentMaxPercentage: (this.value.max - this.min) / (this.max - this.min)
}
},
computed: {
percentageMin: function percentageMin () {
return this.snap ? (this.model.min - this.min) / (this.max - this.min) : this.currentMinPercentage
},
percentageMax: function percentageMax () {
return this.snap ? (this.model.max - this.min) / (this.max - this.min) : this.currentMaxPercentage
},
activeTrackWidth: function activeTrackWidth () {
return 100 * (this.percentageMax - this.percentageMin) + '%'
},
leftDisplayValue: function leftDisplayValue () {
return this.leftLabelValue !== void 0
? this.leftLabelValue
: this.model.min
},
rightDisplayValue: function rightDisplayValue () {
return this.rightLabelValue !== void 0
? this.rightLabelValue
: this.model.max
},
leftTooltipColor: function leftTooltipColor () {
return this.leftLabelColor || this.labelColor
},
rightTooltipColor: function rightTooltipColor () {
return this.rightLabelColor || this.labelColor
}
},
watch: {
'value.min': function value_min (value) {
this.model.min = value;
},
'value.max': function value_max (value) {
this.model.max = value;
},
'model.min': function model_min (value) {
if (this.dragging) {
return
}
if (value > this.model.max) {
value = this.model.max;
}
this.currentMinPercentage = (value - this.min) / (this.max - this.min);
},
'model.max': function model_max (value) {
if (this.dragging) {
return
}
if (value < this.model.min) {
value = this.model.min;
}
this.currentMaxPercentage = (value - this.min) / (this.max - this.min);
},
min: function min (value) {
if (this.model.min < value) {
this.__update({min: value});
}
if (this.model.max < value) {
this.__update({max: value});
}
this.$nextTick(this.__validateProps);
},
max: function max (value) {
if (this.model.min > value) {
this.__update({min: value});
}
if (this.model.max > value) {
this.__update({max: value});
}
this.$nextTick(this.__validateProps);
},
step: function step () {
this.$nextTick(this.__validateProps);
}
},
methods: {
__setActive: function __setActive (event) {
var
container = this.$refs.handle,
width = container.offsetWidth,
sensitivity = (this.dragOnlyRange ? -1 : 1) * this.$refs.handleMin.offsetWidth / (2 * width);
this.dragging = {
left: container.getBoundingClientRect().left,
width: width,
valueMin: this.model.min,
valueMax: this.model.max,
percentageMin: this.currentMinPercentage,
percentageMax: this.currentMaxPercentage
};
var
percentage = getPercentage(event, this.dragging),
type;
if (percentage < this.currentMinPercentage + sensitivity) {
type = dragType.MIN;
}
else if (percentage < this.currentMaxPercentage - sensitivity) {
if (this.dragRange || this.dragOnlyRange) {
type = dragType.RANGE;
extend(this.dragging, {
offsetPercentage: percentage,
offsetModel: getModel(percentage, this.min, this.max, this.step, this.computedDecimals),
rangeValue: this.dragging.valueMax - this.dragging.valueMin,
rangePercentage: this.currentMaxPercentage - this.currentMinPercentage
});
}
else {
type = this.currentMaxPercentage - percentage < percentage - this.currentMinPercentage
? dragType.MAX
: dragType.MIN;
}
}
else {
type = dragType.MAX;
}
if (this.dragOnlyRange && type !== dragType.RANGE) {
this.dragging = false;
return
}
this.dragging.type = type;
this.__update(event);
},
__update: function __update (event) {
var
percentage = getPercentage(event, this.dragging),
model = getModel(percentage, this.min, this.max, this.step, this.computedDecimals),
pos;
switch (this.dragging.type) {
case dragType.MIN:
if (percentage <= this.dragging.percentageMax) {
pos = {
minP: percentage,
maxP: this.dragging.percentageMax,
min: model,
max: this.dragging.valueMax
};
}
else {
pos = {
minP: this.dragging.percentageMax,
maxP: percentage,
min: this.dragging.valueMax,
max: model
};
}
break
case dragType.MAX:
if (percentage >= this.dragging.percentageMin) {
pos = {
minP: this.dragging.percentageMin,
maxP: percentage,
min: this.dragging.valueMin,
max: model
};
}
else {
pos = {
minP: percentage,
maxP: this.dragging.percentageMin,
min: model,
max: this.dragging.valueMin
};
}
break
case dragType.RANGE:
var
percentageDelta = percentage - this.dragging.offsetPercentage,
minP = between(this.dragging.percentageMin + percentageDelta, 0, 1 - this.dragging.rangePercentage),
modelDelta = model - this.dragging.offsetModel,
min = between(this.dragging.valueMin + modelDelta, this.min, this.max - this.dragging.rangeValue);
pos = {
minP: minP,
maxP: minP + this.dragging.rangePercentage,
min: min,
max: min + this.dragging.rangeValue
};
break
}
this.currentMinPercentage = pos.minP;
this.currentMaxPercentage = pos.maxP;
this.__updateInput(pos);
},
__end: function __end () {
var this$1 = this;
this.dragging = false;
this.currentMinPercentage = (this.model.min - this.min) / (this.max - this.min);
this.currentMaxPercentage = (this.model.max - this.min) / (this.max - this.min);
this.$nextTick(function () {
if (JSON.stringify(this$1.model) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', this$1.model);
}
this$1.$emit('dragend', this$1.model);
});
},
__updateInput: function __updateInput (ref) {
var min = ref.min; if ( min === void 0 ) min = this.model.min;
var max = ref.max; if ( max === void 0 ) max = this.model.max;
var model = {min: min, max: max};
this.model = model;
this.$emit('input', model);
},
__validateProps: function __validateProps () {
if (this.min >= this.max) {
console.error('Range error: min >= max', this.$el, this.min, this.max);
}
else if (notDivides((this.max - this.min) / this.step, this.computedDecimals)) {
console.error('Range error: step must be a divisor of max - min', this.min, this.max, this.step);
}
else if (notDivides((this.model.min - this.min) / this.step, this.computedDecimals)) {
console.error('Range error: step must be a divisor of initial value.min - min', this.model.min, this.min, this.step);
}
else if (notDivides((this.model.max - this.min) / this.step, this.computedDecimals)) {
console.error('Range error: step must be a divisor of initial value.max - min', this.model.max, this.max, this.step);
}
},
__getHandle: function __getHandle (h, lower, upper, edge, percentage, color, label) {
return h('div', {
ref: ("handle" + upper),
staticClass: ("q-slider-handle q-slider-handle-" + lower),
style: {
left: ((percentage * 100) + "%"),
borderRadius: this.square ? '0' : '50%'
},
'class': [
edge ? 'handle-at-minimum' : null,
{ dragging: this.dragging }
]
}, [
this.label || this.labelAlways
? h(QChip, {
props: {
pointing: 'down',
square: true,
color: color
},
staticClass: 'q-slider-label no-pointer-events',
'class': { 'label-always': this.labelAlways }
}, [ label ])
: null,
h('div', { staticClass: 'q-slider-ring' })
])
},
__getContent: function __getContent (h) {
return [
h('div', {
staticClass: 'q-slider-track active-track',
style: {
left: ((this.percentageMin * 100) + "%"),
width: this.activeTrackWidth
},
'class': {
dragging: this.dragging,
'track-draggable': this.dragRange || this.dragOnlyRange
}
}),
this.__getHandle(
h, 'min', 'Min', !this.fillHandleAlways && this.model.min === this.min, this.percentageMin,
this.leftTooltipColor, this.leftDisplayValue
),
this.__getHandle(
h, 'max', 'Max', false, this.percentageMax,
this.rightTooltipColor, this.rightDisplayValue
)
]
}
}
}
var QRating = {
name: 'q-rating',
props: {
value: {
type: Number,
default: 0,
required: true
},
max: {
type: Number,
default: 5
},
icon: String,
color: String,
size: String,
readonly: Boolean,
disable: Boolean
},
data: function data () {
return {
mouseModel: 0
}
},
computed: {
model: {
get: function get () {
return this.value
},
set: function set (value) {
var this$1 = this;
this.$emit('input', value);
this.$nextTick(function () {
if (JSON.stringify(value) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', value);
}
});
}
},
editable: function editable () {
return !this.readonly && !this.disable
},
classes: function classes () {
var cls = [];
this.disable && cls.push('disabled');
this.editable && cls.push('editable');
this.color && cls.push(("text-" + (this.color)));
return cls
}
},
methods: {
set: function set (value) {
if (this.editable) {
this.model = between(parseInt(value, 10), 1, this.max);
this.mouseModel = 0;
}
},
__setHoverValue: function __setHoverValue (value) {
if (this.editable) {
this.mouseModel = value;
}
}
},
render: function render (h) {
var this$1 = this;
var child = [];
var loop = function ( i ) {
child.push(h(QIcon, {
key: i,
props: { name: this$1.icon || this$1.$q.icon.rating.icon },
'class': {
active: (!this$1.mouseModel && this$1.model >= i) || (this$1.mouseModel && this$1.mouseModel >= i),
exselected: this$1.mouseModel && this$1.model >= i && this$1.mouseModel < i,
hovered: this$1.mouseModel === i
},
nativeOn: {
click: function () { return this$1.set(i); },
mouseover: function () { return this$1.__setHoverValue(i); },
mouseout: function () { this$1.mouseModel = 0; }
}
}));
};
for (var i = 1; i <= this.max; i++) loop( i );
return h('div', {
staticClass: 'q-rating row inline items-center no-wrap',
'class': this.classes,
style: this.size ? ("font-size: " + (this.size)) : ''
}, child)
}
}
var QScrollArea = {
name: 'q-scroll-area',
directives: {
TouchPan: TouchPan
},
props: {
thumbStyle: {
type: Object,
default: function () { return ({}); }
},
contentStyle: {
type: Object,
default: function () { return ({}); }
},
contentActiveStyle: {
type: Object,
default: function () { return ({}); }
},
delay: {
type: Number,
default: 1000
}
},
data: function data () {
return {
active: false,
hover: false,
containerHeight: 0,
scrollPosition: 0,
scrollHeight: 0
}
},
computed: {
thumbHidden: function thumbHidden () {
return this.scrollHeight <= this.containerHeight || (!this.active && !this.hover)
},
thumbHeight: function thumbHeight () {
return Math.round(between(this.containerHeight * this.containerHeight / this.scrollHeight, 50, this.containerHeight))
},
style: function style () {
var top = this.scrollPercentage * (this.containerHeight - this.thumbHeight);
return extend({}, this.thumbStyle, {
top: (top + "px"),
height: ((this.thumbHeight) + "px")
})
},
mainStyle: function mainStyle () {
return this.thumbHidden ? this.contentStyle : this.contentActiveStyle
},
scrollPercentage: function scrollPercentage () {
var p = between(this.scrollPosition / (this.scrollHeight - this.containerHeight), 0, 1);
return Math.round(p * 10000) / 10000
}
},
methods: {
setScrollPosition: function setScrollPosition$1 (offset, duration) {
setScrollPosition(this.$refs.target, offset, duration);
},
__updateContainer: function __updateContainer (size) {
if (this.containerHeight !== size.height) {
this.containerHeight = size.height;
this.__setActive(true, true);
}
},
__updateScroll: function __updateScroll (scroll) {
if (this.scrollPosition !== scroll.position) {
this.scrollPosition = scroll.position;
this.__setActive(true, true);
}
},
__updateScrollHeight: function __updateScrollHeight (ref) {
var height = ref.height;
if (this.scrollHeight !== height) {
this.scrollHeight = height;
this.__setActive(true, true);
}
},
__panThumb: function __panThumb (e) {
e.evt.preventDefault();
if (e.isFirst) {
this.refPos = this.scrollPosition;
this.__setActive(true, true);
document.body.classList.add('non-selectable');
if (document.selection) {
document.selection.empty();
}
else if (window.getSelection) {
window.getSelection().removeAllRanges();
}
}
if (e.isFinal) {
this.__setActive(false);
document.body.classList.remove('non-selectable');
}
var multiplier = (this.scrollHeight - this.containerHeight) / (this.containerHeight - this.thumbHeight);
this.$refs.target.scrollTop = this.refPos + (e.direction === 'down' ? 1 : -1) * e.distance.y * multiplier;
},
__panContainer: function __panContainer (e) {
if (e.isFirst) {
this.refPos = this.scrollPosition;
this.__setActive(true, true);
}
if (e.isFinal) {
this.__setActive(false);
}
var pos = this.refPos + (e.direction === 'down' ? -1 : 1) * e.distance.y;
this.$refs.target.scrollTop = pos;
if (pos > 0 && pos + this.containerHeight < this.scrollHeight) {
e.evt.preventDefault();
}
},
__mouseWheel: function __mouseWheel (e) {
var el = this.$refs.target;
el.scrollTop += getMouseWheelDistance(e).pixelY;
if (el.scrollTop > 0 && el.scrollTop + this.containerHeight < this.scrollHeight) {
e.preventDefault();
}
},
__setActive: function __setActive (active, timer) {
clearTimeout(this.timer);
if (active === this.active) {
if (active && this.timer) {
this.__startTimer();
}
return
}
if (active) {
this.active = true;
if (timer) {
this.__startTimer();
}
}
else {
this.active = false;
}
},
__startTimer: function __startTimer () {
var this$1 = this;
this.timer = setTimeout(function () {
this$1.active = false;
this$1.timer = null;
}, this.delay);
}
},
render: function render (h) {
var this$1 = this;
if (!this.$q.platform.is.desktop) {
return h('div', {
ref: 'target',
staticClass: 'q-scroll-area scroll relative-position',
style: this.contentStyle
}, [
this.$slots.default
])
}
return h('div', {
staticClass: 'q-scrollarea relative-position',
on: {
mouseenter: function () { this$1.hover = true; },
mouseleave: function () { this$1.hover = false; }
}
}, [
h('div', {
ref: 'target',
staticClass: 'scroll relative-position overflow-hidden fit',
on: {
wheel: this.__mouseWheel,
mousewheel: this.__mouseWheel,
DOMMouseScroll: this.__mouseWheel
},
directives: [{
name: 'touch-pan',
modifiers: { vertical: true, nomouse: true },
value: this.__panContainer
}]
}, [
h('div', {
staticClass: 'absolute full-width',
style: this.mainStyle
}, [
this.$slots.default,
h(QResizeObservable, {
staticClass: 'resize-obs',
on: { resize: this.__updateScrollHeight }
})
]),
h(QScrollObservable, {
staticClass: 'scroll-obs',
on: { scroll: this.__updateScroll }
})
]),
h(QResizeObservable, {
staticClass: 'main-resize-obs',
on: { resize: this.__updateContainer }
}),
h('div', {
staticClass: 'q-scrollarea-thumb absolute-right',
style: this.style,
'class': { 'invisible-thumb': this.thumbHidden },
directives: [{
name: 'touch-pan',
modifiers: { vertical: true },
value: this.__panThumb
}]
})
])
}
}
var QSearch = {
name: 'q-search',
mixins: [FrameMixin, InputMixin],
props: {
value: { required: true },
type: String,
debounce: {
type: Number,
default: 300
},
icon: String,
placeholder: String
},
data: function data () {
return {
model: this.value,
childDebounce: false
}
},
provide: function provide () {
var this$1 = this;
return {
__inputDebounce: {
set: function (val) {
if (this$1.model !== val) {
this$1.model = val;
}
},
setChildDebounce: function (v) {
this$1.childDebounce = v;
}
}
}
},
watch: {
value: function value (v) {
this.model = v;
},
model: function model (val) {
var this$1 = this;
clearTimeout(this.timer);
if (this.value === val) {
return
}
if (!val && val !== 0) {
this.model = this.type === 'number' ? null : '';
}
this.timer = setTimeout(function () {
this$1.$emit('input', this$1.model);
}, this.debounceValue);
}
},
computed: {
debounceValue: function debounceValue () {
return this.childDebounce
? 0
: this.debounce
},
controlBefore: function controlBefore () {
return this.before || [{
icon: this.icon || this.$q.icon.search.icon,
handler: this.focus
}]
},
controlAfter: function controlAfter () {
return this.after || [{
icon: this.$q.icon.search[("clear" + (this.inverted ? 'Inverted' : ''))],
content: true,
handler: this.clear
}]
}
},
methods: {
clear: function clear () {
this.$refs.input.clear();
this.$emit('clear');
}
},
render: function render (h) {
var this$1 = this;
return h(QInput, {
ref: 'input',
staticClass: 'q-search',
props: {
value: this.model,
type: this.type,
autofocus: this.autofocus,
placeholder: this.placeholder || this.$q.i18n.label.search,
disable: this.disable,
error: this.error,
warning: this.warning,
align: this.align,
floatLabel: this.floatLabel,
stackLabel: this.stackLabel,
prefix: this.prefix,
suffix: this.suffix,
inverted: this.inverted,
dark: this.dark,
hideUnderline: this.hideUnderline,
maxLength: this.maxLength,
color: this.color,
before: this.controlBefore,
after: this.controlAfter,
clearValue: this.clearValue
},
on: {
input: function (v) { this$1.model = v; },
focus: this.__onFocus,
blur: this.__onBlur,
keyup: this.__onKeyup,
keydown: this.__onKeydown,
click: this.__onClick,
clear: function () { this$1.$emit('clear'); }
}
}, [
this.$slots.default
])
}
}
function defaultFilterFn (terms, obj) {
return obj.label.toLowerCase().indexOf(terms) > -1
}
var QSelect = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('q-input-frame',{ref:"input",staticClass:"q-select",attrs:{"prefix":_vm.prefix,"suffix":_vm.suffix,"stack-label":_vm.stackLabel,"float-label":_vm.floatLabel,"error":_vm.error,"warning":_vm.warning,"disable":_vm.disable,"inverted":_vm.inverted,"dark":_vm.dark,"hide-underline":_vm.hideUnderline,"before":_vm.before,"after":_vm.after,"color":_vm.frameColor || _vm.color,"focused":_vm.focused,"focusable":"","length":_vm.length,"additional-length":_vm.additionalLength},nativeOn:{"click":function($event){_vm.togglePopup($event);},"focus":function($event){_vm.__onFocus($event);},"blur":function($event){_vm.__onBlur($event);},"keydown":function($event){_vm.__handleKey($event);}}},[(_vm.hasChips)?_c('div',{staticClass:"col row items-center group q-input-chips q-if-control",class:_vm.alignClass},_vm._l((_vm.selectedOptions),function(ref){
var label = ref.label;
var value = ref.value;
var optDisable = ref.disable;
return _c('q-chip',{key:label,attrs:{"small":"","closable":!_vm.disable && !optDisable,"color":_vm.color},on:{"hide":function($event){_vm.__toggleMultiple(value, _vm.disable || optDisable);}},nativeOn:{"click":function($event){$event.stopPropagation();}}},[_vm._v(" "+_vm._s(label)+" ")])})):_c('div',{staticClass:"col row items-center q-input-target q-if-control",class:_vm.alignClass,domProps:{"innerHTML":_vm._s(_vm.actualValue)}}),_vm._v(" "),(!_vm.disable && _vm.clearable && _vm.length)?_c('q-icon',{staticClass:"q-if-control",attrs:{"slot":"after","name":"cancel"},nativeOn:{"click":function($event){$event.stopPropagation();_vm.clear($event);}},slot:"after"}):_vm._e(),_vm._v(" "),_c('q-icon',{staticClass:"q-if-control",attrs:{"slot":"after","name":_vm.$q.icon.input.dropdown},slot:"after"}),_vm._v(" "),_c('q-popover',{ref:"popover",staticClass:"column no-wrap",attrs:{"fit":"","disable":_vm.disable,"offset":[0, 10],"anchor-click":false},on:{"show":_vm.__onFocus,"hide":_vm.__onClose}},[_c('q-field-reset',[(_vm.filter)?_c('q-search',{ref:"filter",staticClass:"no-margin",staticStyle:{"min-height":"50px","padding":"10px"},attrs:{"placeholder":_vm.filterPlaceholder || _vm.$q.i18n.label.filter,"debounce":100,"color":_vm.color,"icon":"filter_list"},on:{"input":_vm.reposition},model:{value:(_vm.terms),callback:function ($$v) {_vm.terms=$$v;},expression:"terms"}}):_vm._e()],1),_vm._v(" "),_c('q-list',{staticClass:"no-border scroll",attrs:{"separator":_vm.separator}},[(_vm.multiple)?_vm._l((_vm.visibleOptions),function(opt){return _c('q-item-wrapper',{key:JSON.stringify(opt),class:{'text-faded': opt.disable},attrs:{"cfg":opt,"link":!opt.disable,"slot-replace":""},nativeOn:{"!click":function($event){_vm.__toggleMultiple(opt.value, opt.disable);}}},[(_vm.toggle)?_c('q-toggle',{attrs:{"slot":"right","color":_vm.color,"value":_vm.optModel[opt.index],"disable":opt.disable,"no-focus":""},slot:"right"}):_c('q-checkbox',{attrs:{"slot":"left","color":_vm.color,"value":_vm.optModel[opt.index],"disable":opt.disable,"no-focus":""},slot:"left"})],1)}):_vm._l((_vm.visibleOptions),function(opt){return _c('q-item-wrapper',{key:JSON.stringify(opt),class:{'text-faded': opt.disable},attrs:{"cfg":opt,"link":!opt.disable,"slot-replace":"","active":_vm.value === opt.value},nativeOn:{"!click":function($event){_vm.__singleSelect(opt.value, opt.disable);}}},[(_vm.radio)?_c('q-radio',{attrs:{"slot":"left","color":_vm.color,"value":_vm.value,"val":opt.value,"disable":opt.disable,"no-focus":""},slot:"left"}):_vm._e()],1)})],2)],1)],1)},staticRenderFns: [],
name: 'q-select',
mixins: [FrameMixin],
components: {
QFieldReset: QFieldReset,
QSearch: QSearch,
QPopover: QPopover,
QList: QList,
QItemWrapper: QItemWrapper,
QCheckbox: QCheckbox,
QRadio: QRadio,
QToggle: QToggle,
QIcon: QIcon,
QInputFrame: QInputFrame,
QChip: QChip
},
props: {
filter: [Function, Boolean],
filterPlaceholder: String,
autofocusFilter: Boolean,
radio: Boolean,
placeholder: String,
separator: Boolean,
value: { required: true },
multiple: Boolean,
toggle: Boolean,
chips: Boolean,
options: {
type: Array,
required: true,
validator: function (v) { return v.every(function (o) { return 'label' in o && 'value' in o; }); }
},
frameColor: String,
displayValue: String,
clearable: Boolean,
clearValue: {}
},
data: function data () {
return {
model: this.multiple && Array.isArray(this.value)
? this.value.slice()
: this.value,
terms: '',
focused: false
}
},
watch: {
value: function value (val) {
this.model = this.multiple && Array.isArray(val)
? val.slice()
: val;
}
},
computed: {
optModel: function optModel () {
var this$1 = this;
if (this.multiple) {
return this.model.length > 0
? this.options.map(function (opt) { return this$1.model.includes(opt.value); })
: this.options.map(function (opt) { return false; })
}
},
visibleOptions: function visibleOptions () {
var this$1 = this;
var opts = this.options.map(function (opt, index) { return extend({}, opt, { index: index }); });
if (this.filter && this.terms.length) {
var lowerTerms = this.terms.toLowerCase();
opts = opts.filter(function (opt) { return this$1.filterFn(lowerTerms, opt); });
}
return opts
},
filterFn: function filterFn () {
return typeof this.filter === 'boolean'
? defaultFilterFn
: this.filter
},
activeItemSelector: function activeItemSelector () {
return this.multiple
? (".q-item-side > " + (this.toggle ? '.q-toggle' : '.q-checkbox') + " > .active")
: ".q-item.active"
},
actualValue: function actualValue () {
var this$1 = this;
if (this.displayValue) {
return this.displayValue
}
if (!this.multiple) {
var opt$1 = this.options.find(function (opt) { return opt.value === this$1.model; });
return opt$1 ? opt$1.label : ''
}
var opt = this.selectedOptions.map(function (opt) { return opt.label; });
return opt.length ? opt.join(', ') : ''
},
selectedOptions: function selectedOptions () {
var this$1 = this;
if (this.multiple) {
return this.length > 0
? this.options.filter(function (opt) { return this$1.model.includes(opt.value); })
: []
}
},
hasChips: function hasChips () {
return this.multiple && this.chips
},
length: function length () {
return this.multiple
? this.model.length
: ([null, undefined, ''].includes(this.model) ? 0 : 1)
},
additionalLength: function additionalLength () {
return this.displayValue && this.displayValue.length > 0
}
},
methods: {
togglePopup: function togglePopup () {
this[this.$refs.popover.showing ? 'hide' : 'show']();
},
show: function show () {
return this.$refs.popover.show()
},
hide: function hide () {
return this.$refs.popover.hide()
},
reposition: function reposition () {
var popover = this.$refs.popover;
if (popover.showing) {
popover.reposition();
}
},
__handleKey: function __handleKey (e) {
// ENTER key
if (e.which === 13 || e.keyCode === 13) {
this.show();
}
// Backspace key
else if (e.which === 8 || e.keyCode === 8) {
if (this.editable && this.clearable && this.actualValue.length) {
this.clear();
}
}
},
__onFocus: function __onFocus () {
this.focused = true;
if (this.filter && this.autofocusFilter) {
this.$refs.filter.focus();
}
this.$emit('focus');
var selected = this.$refs.popover.$el.querySelector(this.activeItemSelector);
if (selected) {
selected.scrollIntoView();
}
},
__onBlur: function __onBlur (e) {
var this$1 = this;
setTimeout(function () {
var el = document.activeElement;
if (el !== document.body && !this$1.$refs.popover.$el.contains(el)) {
this$1.__onClose();
this$1.hide();
}
}, 1);
},
__onClose: function __onClose () {
var this$1 = this;
this.focused = false;
this.$emit('blur');
this.terms = '';
this.$nextTick(function () {
if (JSON.stringify(this$1.model) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', this$1.model);
}
});
},
__singleSelect: function __singleSelect (val, disable) {
if (disable) {
return
}
this.__emit(val);
this.hide();
},
__toggleMultiple: function __toggleMultiple (value, disable) {
if (disable) {
return
}
var
model = this.model,
index = model.indexOf(value);
if (index > -1) {
model.splice(index, 1);
}
else {
model.push(value);
}
this.$emit('input', model);
},
__emit: function __emit (value) {
var this$1 = this;
this.$emit('input', value);
this.$nextTick(function () {
if (JSON.stringify(value) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', value);
}
});
},
__setModel: function __setModel (val) {
this.model = val || (this.multiple ? [] : null);
this.$emit('input', this.model);
if (!this.$refs.popover.showing) {
this.__onClose();
}
}
}
}
var StepTab = {
name: 'q-step-tab',
components: {
QIcon: QIcon
},
directives: {
Ripple: Ripple
},
props: ['vm'],
computed: {
classes: function classes () {
return {
'step-error': this.vm.error,
'step-active': this.vm.active,
'step-done': this.vm.done,
'step-waiting': this.vm.waiting,
'step-disabled': this.vm.disable,
'step-colored': this.vm.active || this.vm.done,
'items-center': !this.vm.__stepper.vertical,
'items-start': this.vm.__stepper.vertical,
'q-stepper-first': this.vm.first,
'q-stepper-last': this.vm.last
}
}
},
methods: {
__select: function __select () {
this.vm.select();
}
},
render: function render (h) {
var icon = this.vm.stepIcon
? h(QIcon, { props: { name: this.vm.stepIcon } })
: h('span', [ (this.vm.innerOrder + 1) ]);
return h('div', {
staticClass: 'q-stepper-tab col-grow flex no-wrap relative-position',
'class': this.classes,
on: {
click: this.__select
},
directives: [{
name: 'ripple',
value: this.vm.done
}]
}, [
h('div', { staticClass: 'q-stepper-dot row flex-center q-stepper-line relative-position' }, [
h('span', { staticClass: 'row flex-center' }, [ icon ])
]),
this.vm.title
? h('div', {
staticClass: 'q-stepper-label q-stepper-line relative-position'
}, [
h('div', { staticClass: 'q-stepper-title' }, [ this.vm.title ]),
h('div', { staticClass: 'q-stepper-subtitle' }, [ this.vm.subtitle ])
])
: null
])
}
}
var QStep = {
name: 'q-step',
inject: {
__stepper: {
default: function default$1 () {
console.error('QStep needs to be child of QStepper');
}
}
},
props: {
name: {
type: [Number, String],
default: function default$2 () {
return uid()
}
},
default: Boolean,
title: {
type: String,
required: true
},
subtitle: String,
icon: String,
order: [Number, String],
error: Boolean,
activeIcon: String,
errorIcon: String,
doneIcon: String,
disable: Boolean
},
watch: {
order: function order () {
this.__stepper.__sortSteps();
}
},
data: function data () {
return {
innerOrder: 0,
first: false,
last: false
}
},
computed: {
stepIcon: function stepIcon () {
var data = this.__stepper;
if (this.active) {
return this.activeIcon || data.activeIcon || this.$q.icon.stepper.active
}
if (this.error) {
return this.errorIcon || data.errorIcon || this.$q.icon.stepper.error
}
if (this.done && !this.disable) {
return this.doneIcon || data.doneIcon || this.$q.icon.stepper.done
}
return this.icon
},
actualOrder: function actualOrder () {
return parseInt(this.order || this.innerOrder, 10)
},
active: function active () {
return this.__stepper.step === this.name
},
done: function done () {
return !this.disable && this.__stepper.currentOrder > this.innerOrder
},
waiting: function waiting () {
return !this.disable && this.__stepper.currentOrder < this.innerOrder
},
style: function style () {
var ord = this.actualOrder;
return {
'-webkit-box-ordinal-group': ord,
'-ms-flex-order': ord,
order: ord
}
}
},
methods: {
select: function select () {
if (this.done) {
this.__stepper.goToStep(this.name);
}
}
},
mounted: function mounted () {
this.__stepper.__registerStep(this);
if (this.default) {
this.select();
}
},
beforeDestroy: function beforeDestroy () {
this.__stepper.__unregisterStep(this);
},
render: function render (h) {
return h('div', {
staticClass: 'q-stepper-step',
style: this.style
}, [
this.__stepper.vertical
? h(StepTab, { props: { vm: this } })
: null,
h(QSlideTransition, [
this.active
? h('div', {
staticClass: 'q-stepper-step-content'
}, [
h('div', { staticClass: 'q-stepper-step-inner' }, [
this.$slots.default
])
])
: null
])
])
}
}
var QStepper = {
name: 'q-stepper',
components: {
StepTab: StepTab
},
props: {
value: [Number, String],
color: String,
vertical: Boolean,
alternativeLabels: Boolean,
contractable: Boolean,
doneIcon: Boolean,
activeIcon: Boolean,
errorIcon: Boolean
},
data: function data () {
return {
step: this.value || null,
steps: []
}
},
provide: function provide () {
return {
__stepper: this
}
},
watch: {
value: function value (v) {
this.goToStep(v);
}
},
computed: {
classes: function classes () {
var cls = [
("q-stepper-" + (this.vertical ? 'vertical' : 'horizontal'))
];
if (this.color) {
cls.push(("text-" + (this.color)));
}
if (this.contractable) {
cls.push("q-stepper-contractable");
}
return cls
},
hasSteps: function hasSteps () {
return this.steps.length > 0
},
currentStep: function currentStep () {
var this$1 = this;
if (this.hasSteps) {
return this.steps.find(function (step) { return step.name === this$1.step; })
}
},
currentOrder: function currentOrder () {
if (this.currentStep) {
return this.currentStep.innerOrder
}
},
length: function length () {
return this.steps.length
}
},
methods: {
goToStep: function goToStep (value) {
var this$1 = this;
if (this.step === value || value === void 0) {
return
}
this.step = value;
this.$emit('input', value);
this.$emit('step', value);
this.$nextTick(function () {
if (JSON.stringify(value) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', value);
}
});
},
next: function next () {
this.__go(1);
},
previous: function previous () {
this.__go(-1);
},
reset: function reset () {
if (this.hasSteps) {
this.goToStep(this.steps[0].name);
}
},
__go: function __go (offset) {
var
name,
index = this.currentOrder;
if (index === void 0) {
if (!this.hasSteps) {
return
}
name = this.steps[0].name;
}
else {
do {
index += offset;
} while (index >= 0 && index < this.length - 1 && this.steps[index].disable)
if (index < 0 || index > this.length - 1 || this.steps[index].disable) {
return
}
name = this.steps[index].name;
}
this.goToStep(name);
},
__sortSteps: function __sortSteps () {
var this$1 = this;
this.steps.sort(function (a, b) {
return a.actualOrder - b.actualOrder
});
var last = this.steps.length - 1;
this.steps.forEach(function (step, index) {
step.innerOrder = index;
step.first = index === 0;
step.last = index === last;
});
this.$nextTick(function () {
if (!this$1.steps.some(function (step) { return step.active; })) {
this$1.goToStep(this$1.steps[0].name);
}
});
},
__registerStep: function __registerStep (vm) {
this.steps.push(vm);
this.__sortSteps();
return this
},
__unregisterStep: function __unregisterStep (vm) {
this.steps = this.steps.filter(function (step) { return step !== vm; });
}
},
created: function created () {
this.__sortSteps = frameDebounce(this.__sortSteps);
},
render: function render (h) {
return h('div', {
staticClass: 'q-stepper column overflow-hidden relative-position',
'class': this.classes
}, [
this.vertical
? null
: h('div', {
staticClass: 'q-stepper-header row items-stretch justify-between shadow-1',
'class': { 'alternative-labels': this.alternativeLabels }
},
this.steps.map(function (step) { return h(StepTab, {
key: step.name,
props: {
vm: step
}
}); })),
this.$slots.default
])
}
}
var QStepperNavigation = {
name: 'q-stepper-navigation',
render: function render (h) {
return h('div', {
staticClass: 'q-stepper-nav order-last row no-wrap items-center'
}, [
this.$slots.left,
h('div', { staticClass: 'col' }),
this.$slots.default
])
}
}
var TabMixin = {
directives: {
Ripple: Ripple
},
props: {
label: String,
icon: String,
disable: Boolean,
hidden: Boolean,
hide: {
type: String,
default: ''
},
name: {
type: String,
default: function default$1 () {
return uid()
}
},
alert: Boolean,
count: [Number, String],
color: String
},
inject: {
data: {
default: function default$2 () {
console.error('QTab/QRouteTab components need to be child of QTabs');
}
},
selectTab: {}
},
watch: {
active: function active (val) {
if (val) {
this.$emit('select', this.name);
}
}
},
computed: {
active: function active () {
return this.data.tabName === this.name
},
classes: function classes () {
var cls = {
active: this.active,
hidden: this.hidden,
disabled: this.disable,
'icon-and-label': this.icon && this.label,
'hide-icon': this.hide === 'icon',
'hide-label': this.hide === 'label'
};
var color = this.data.inverted
? this.color || this.data.color
: this.color;
if (color) {
cls[("text-" + color)] = true;
}
return cls
},
barStyle: function barStyle () {
if (!this.active || !this.data.highlight) {
return 'display: none;'
}
}
},
methods: {
__getTabContent: function __getTabContent (h) {
var child = [];
this.icon && child.push(h(QIcon, {
staticClass: 'q-tab-icon',
props: {
name: this.icon
}
}));
this.label && child.push(h('span', {
staticClass: 'q-tab-label',
domProps: {
innerHTML: this.label
}
}));
if (this.count) {
child.push(h(QChip, {
props: {
floating: true
}
}, [ this.count ]));
}
else if (this.alert) {
child.push(h('div', {
staticClass: 'q-dot'
}));
}
child.push(this.$slots.default);
{
child.push(h('div', {
staticClass: 'q-tabs-bar',
style: this.barStyle
}));
}
return child
}
}
}
var QRouteTab = {
name: 'q-route-tab',
mixins: [TabMixin, RouterLinkMixin],
watch: {
$route: function $route () {
this.checkIfSelected();
}
},
methods: {
select: function select () {
this.$emit('click', this.name);
if (!this.disable) {
this.$el.dispatchEvent(evt);
this.selectTab(this.name);
}
},
checkIfSelected: function checkIfSelected () {
var this$1 = this;
this.$nextTick(function () {
if (this$1.$el.classList.contains('router-link-active') || this$1.$el.classList.contains('router-link-exact-active')) {
this$1.selectTab(this$1.name);
}
else if (this$1.active) {
this$1.selectTab(null);
}
});
}
},
created: function created () {
this.checkIfSelected();
},
render: function render (h) {
return h('router-link', {
props: {
tag: 'div',
to: this.to,
replace: this.replace,
append: this.append,
event: routerLinkEventName
},
nativeOn: {
click: this.select
},
staticClass: 'q-tab column flex-center relative-position',
'class': this.classes,
directives: [{ name: 'ripple' }]
}, this.__getTabContent(h))
}
}
var QTab = {
name: 'q-tab',
mixins: [TabMixin],
props: {
default: Boolean
},
methods: {
select: function select () {
this.$emit('click', this.name);
if (!this.disable) {
this.selectTab(this.name);
}
}
},
mounted: function mounted () {
if (this.default && !this.disable) {
this.select();
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-tab column flex-center relative-position',
'class': this.classes,
on: {
click: this.select
},
directives: [{ name: 'ripple' }]
}, this.__getTabContent(h))
}
}
var QTabPane = {
name: 'q-tab-pane',
inject: {
data: {
default: function default$1 () {
console.error('QTabPane needs to be child of QTabs');
}
}
},
props: {
name: {
type: String,
required: true
},
keepAlive: Boolean
},
data: function data () {
return {
shown: false
}
},
computed: {
active: function active () {
return this.data.tabName === this.name
}
},
render: function render (h) {
var node = h('div', {staticClass: 'q-tab-pane', 'class': {hidden: !this.active}}, [this.$slots.default]);
if (this.keepAlive) {
if (!this.shown && !this.active) {
return
}
this.shown = true;
return node
}
else {
this.shown = this.active;
if (this.active) {
return node
}
}
}
}
var scrollNavigationSpeed = 5;
var debounceDelay = 50; // in ms
var QTabs = {render: function(){
var obj;
var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"q-tabs flex no-wrap",class:[ ("q-tabs-position-" + (_vm.position)), ("q-tabs-" + (_vm.inverted ? 'inverted' : 'normal')), _vm.noPaneBorder ? 'q-tabs-no-pane-border' : '', _vm.twoLines ? 'q-tabs-two-lines' : '' ]},[_c('div',{ref:"tabs",staticClass:"q-tabs-head row",class:( obj = {}, obj[("q-tabs-align-" + (_vm.align))] = true, obj.glossy = _vm.glossy, obj[("bg-" + (_vm.color))] = !_vm.inverted && _vm.color, obj)},[_c('div',{ref:"scroller",staticClass:"q-tabs-scroller row no-wrap"},[_vm._t("title"),_vm._v(" "),(_vm.$q.theme !== 'ios')?_c('div',{staticClass:"relative-position self-stretch q-tabs-global-bar-container",class:[_vm.inverted && _vm.color ? ("text-" + (_vm.color)) : '', _vm.data.highlight ? 'highlight' : '']},[_c('div',{ref:"posbar",staticClass:"q-tabs-bar q-tabs-global-bar",on:{"transitionend":_vm.__updatePosbarTransition}})]):_vm._e()],2),_vm._v(" "),_c('div',{ref:"leftScroll",staticClass:"row flex-center q-tabs-left-scroll",on:{"mousedown":function($event){_vm.__animScrollTo(0);},"touchstart":function($event){_vm.__animScrollTo(0);},"mouseup":_vm.__stopAnimScroll,"mouseleave":_vm.__stopAnimScroll,"touchend":_vm.__stopAnimScroll}},[_c('q-icon',{attrs:{"name":_vm.$q.icon.tabs.left}})],1),_vm._v(" "),_c('div',{ref:"rightScroll",staticClass:"row flex-center q-tabs-right-scroll",on:{"mousedown":function($event){_vm.__animScrollTo(9999);},"touchstart":function($event){_vm.__animScrollTo(9999);},"mouseup":_vm.__stopAnimScroll,"mouseleave":_vm.__stopAnimScroll,"touchend":_vm.__stopAnimScroll}},[_c('q-icon',{attrs:{"name":_vm.$q.icon.tabs.right}})],1)]),_vm._v(" "),_c('div',{staticClass:"q-tabs-panes"},[_vm._t("default")],2)])},staticRenderFns: [],
name: 'q-tabs',
provide: function provide () {
return {
data: this.data,
selectTab: this.selectTab
}
},
components: {
QIcon: QIcon
},
props: {
value: String,
align: {
type: String,
default: 'left',
validator: function (v) { return ['left', 'center', 'right', 'justify'].includes(v); }
},
position: {
type: String,
default: 'top',
validator: function (v) { return ['top', 'bottom'].includes(v); }
},
color: String,
inverted: Boolean,
twoLines: Boolean,
noPaneBorder: Boolean,
glossy: Boolean
},
data: function data () {
return {
currentEl: null,
posbar: {
width: 0,
left: 0
},
data: {
highlight: true,
tabName: this.value || '',
color: this.color,
inverted: this.inverted
}
}
},
watch: {
value: function value (name) {
this.selectTab(name);
},
color: function color (v) {
this.data.color = v;
},
inverted: function inverted (v) {
this.data.inverted = v;
}
},
methods: {
selectTab: function selectTab (value) {
var this$1 = this;
if (this.data.tabName === value) {
return
}
this.data.tabName = value;
this.$emit('select', value);
this.$emit('input', value);
this.$nextTick(function () {
if (JSON.stringify(value) !== JSON.stringify(this$1.value)) {
this$1.$emit('change', value);
}
});
var el = this.__getTabElByName(value);
if (el) {
this.__scrollToTab(el);
}
{
this.currentEl = el;
this.__repositionBar();
}
},
__repositionBar: function __repositionBar () {
var this$1 = this;
clearTimeout(this.timer);
var needsUpdate = false;
var
ref = this.$refs.posbar,
el = this.currentEl;
if (this.data.highlight !== false) {
this.data.highlight = false;
needsUpdate = true;
}
if (!el) {
this.finalPosbar = {width: 0, left: 0};
this.__setPositionBar(0, 0);
return
}
var offsetReference = ref.parentNode.offsetLeft;
if (needsUpdate && this.oldEl) {
this.__setPositionBar(
this.oldEl.getBoundingClientRect().width,
this.oldEl.offsetLeft - offsetReference
);
}
this.timer = setTimeout(function () {
var
width$$1 = el.getBoundingClientRect().width,
left = el.offsetLeft - offsetReference;
ref.classList.remove('contract');
this$1.oldEl = el;
this$1.finalPosbar = {width: width$$1, left: left};
this$1.__setPositionBar(
this$1.posbar.left < left
? left + width$$1 - this$1.posbar.left
: this$1.posbar.left + this$1.posbar.width - left,
this$1.posbar.left < left
? this$1.posbar.left
: left
);
}, 20);
},
__setPositionBar: function __setPositionBar (width$$1, left) {
if ( width$$1 === void 0 ) width$$1 = 0;
if ( left === void 0 ) left = 0;
if (this.posbar.width === width$$1 && this.posbar.left === left) {
this.__updatePosbarTransition();
return
}
this.posbar = {width: width$$1, left: left};
css(this.$refs.posbar, cssTransform(("translateX(" + left + "px) scaleX(" + width$$1 + ")")));
},
__updatePosbarTransition: function __updatePosbarTransition () {
if (
this.finalPosbar.width === this.posbar.width &&
this.finalPosbar.left === this.posbar.left
) {
this.posbar = {};
if (this.data.highlight !== true) {
this.data.highlight = true;
}
return
}
this.$refs.posbar.classList.add('contract');
this.__setPositionBar(this.finalPosbar.width, this.finalPosbar.left);
},
__redraw: function __redraw () {
if (!this.$q.platform.is.desktop) {
return
}
if (width(this.$refs.scroller) === 0 && this.$refs.scroller.scrollWidth === 0) {
return
}
if (width(this.$refs.scroller) + 5 < this.$refs.scroller.scrollWidth) {
this.$refs.tabs.classList.add('scrollable');
this.scrollable = true;
this.__updateScrollIndicator();
}
else {
this.$refs.tabs.classList.remove('scrollable');
this.scrollable = false;
}
},
__updateScrollIndicator: function __updateScrollIndicator () {
if (!this.$q.platform.is.desktop || !this.scrollable) {
return
}
var action = this.$refs.scroller.scrollLeft + width(this.$refs.scroller) + 5 >= this.$refs.scroller.scrollWidth ? 'add' : 'remove';
this.$refs.leftScroll.classList[this.$refs.scroller.scrollLeft <= 0 ? 'add' : 'remove']('disabled');
this.$refs.rightScroll.classList[action]('disabled');
},
__getTabElByName: function __getTabElByName (value) {
var tab = this.$children.find(function (child) { return child.name === value && child.$el && child.$el.nodeType === 1; });
if (tab) {
return tab.$el
}
},
__findTabAndScroll: function __findTabAndScroll (name, noAnimation) {
var this$1 = this;
setTimeout(function () {
this$1.__scrollToTab(this$1.__getTabElByName(name), noAnimation);
}, debounceDelay * 4);
},
__scrollToTab: function __scrollToTab (tab, noAnimation) {
if (!tab || !this.scrollable) {
return
}
var
contentRect = this.$refs.scroller.getBoundingClientRect(),
rect = tab.getBoundingClientRect(),
tabWidth = rect.width,
offset$$1 = rect.left - contentRect.left;
if (offset$$1 < 0) {
if (noAnimation) {
this.$refs.scroller.scrollLeft += offset$$1;
}
else {
this.__animScrollTo(this.$refs.scroller.scrollLeft + offset$$1);
}
return
}
offset$$1 += tabWidth - this.$refs.scroller.offsetWidth;
if (offset$$1 > 0) {
if (noAnimation) {
this.$refs.scroller.scrollLeft += offset$$1;
}
else {
this.__animScrollTo(this.$refs.scroller.scrollLeft + offset$$1);
}
}
},
__animScrollTo: function __animScrollTo (value) {
var this$1 = this;
this.__stopAnimScroll();
this.__scrollTowards(value);
this.scrollTimer = setInterval(function () {
if (this$1.__scrollTowards(value)) {
this$1.__stopAnimScroll();
}
}, 5);
},
__stopAnimScroll: function __stopAnimScroll () {
clearInterval(this.scrollTimer);
},
__scrollTowards: function __scrollTowards (value) {
var
scrollPosition = this.$refs.scroller.scrollLeft,
direction = value < scrollPosition ? -1 : 1,
done = false;
scrollPosition += direction * scrollNavigationSpeed;
if (scrollPosition < 0) {
done = true;
scrollPosition = 0;
}
else if (
(direction === -1 && scrollPosition <= value) ||
(direction === 1 && scrollPosition >= value)
) {
done = true;
scrollPosition = value;
}
this.$refs.scroller.scrollLeft = scrollPosition;
return done
}
},
created: function created () {
this.scrollTimer = null;
this.scrollable = !this.$q.platform.is.desktop;
// debounce some costly methods;
// debouncing here because debounce needs to be per instance
this.__redraw = debounce(this.__redraw, debounceDelay);
this.__updateScrollIndicator = debounce(this.__updateScrollIndicator, debounceDelay);
},
mounted: function mounted () {
var this$1 = this;
this.$nextTick(function () {
if (!this$1.$refs.scroller) {
return
}
this$1.$refs.scroller.addEventListener('scroll', this$1.__updateScrollIndicator);
window.addEventListener('resize', this$1.__redraw);
if (this$1.data.tabName !== '' && this$1.value) {
this$1.selectTab(this$1.value);
}
this$1.__redraw();
this$1.__findTabAndScroll(this$1.data.tabName, true);
});
},
beforeDestroy: function beforeDestroy () {
clearTimeout(this.timer);
this.__stopAnimScroll();
this.$refs.scroller.removeEventListener('scroll', this.__updateScrollIndicator);
window.removeEventListener('resize', this.__redraw);
this.__redraw.cancel();
this.__updateScrollIndicator.cancel();
}
}
var Top = {
computed: {
marginalsProps: function marginalsProps () {
return {
pagination: this.computedPagination,
pagesNumber: this.pagesNumber,
isFirstPage: this.isFirstPage,
isLastPage: this.isLastPage,
prevPage: this.prevPage,
nextPage: this.nextPage,
inFullscreen: this.inFullscreen,
toggleFullscreen: this.toggleFullscreen
}
}
},
methods: {
getTop: function getTop (h) {
var
top = this.$scopedSlots.top,
topLeft = this.$scopedSlots['top-left'],
topRight = this.$scopedSlots['top-right'],
topSelection = this.$scopedSlots['top-selection'],
hasSelection = this.selection && topSelection && this.rowsSelectedNumber > 0,
staticClass = 'q-table-top relative-position row no-wrap items-center',
child = [];
if (top) {
return h('div', { staticClass: staticClass }, [ top(this.marginalsProps) ])
}
if (hasSelection) {
child.push(topSelection(this.marginalsProps));
}
else {
if (topLeft) {
child.push(topLeft(this.marginalsProps));
}
else if (this.title) {
child.push(h('div', { staticClass: 'q-table-title' }, this.title));
}
}
if (topRight) {
child.push(h('div', { staticClass: 'q-table-separator col' }));
child.push(topRight(this.marginalsProps));
}
if (child.length === 0) {
return
}
return h('div', { staticClass: staticClass }, child)
}
}
}
var QTh = {
name: 'q-th',
props: {
props: Object,
autoWidth: Boolean
},
render: function render (h) {
var this$1 = this;
if (!this.props) {
return h('td', {
'class': { 'q-table-col-auto-width': this.autoWidth }
}, [ this.$slots.default ])
}
var col;
var
name = this.$vnode.key,
child = [ this.$slots.default ];
if (name) {
col = this.props.colsMap[name];
if (!col) { return }
}
else {
col = this.props.col;
}
if (col.sortable) {
var action = col.align === 'right'
? 'unshift'
: 'push';
child[action](
h(QIcon, {
props: { name: this.$q.icon.table.arrowUp },
staticClass: col.__iconClass
})
);
}
return h('th', {
'class': [col.__thClass, {
'q-table-col-auto-width': this.autoWidth
}],
on: col.sortable
? { click: function () { this$1.props.sort(col); } }
: null
}, child)
}
}
var TableHeader = {
methods: {
getTableHeader: function getTableHeader (h) {
if (this.hideHeader) {
return
}
var child = [ this.getTableHeaderRow(h) ];
if (this.loader) {
child.push(h('tr', { staticClass: 'q-table-progress animate-fade' }, [
h('td', { attrs: {colspan: '100%'} }, [
h(QProgress, {
props: {
color: this.color,
indeterminate: true,
height: '2px'
}
})
])
]));
}
return h('thead', child)
},
getTableHeaderRow: function getTableHeaderRow (h) {
var this$1 = this;
var
header = this.$scopedSlots.header,
headerCell = this.$scopedSlots['header-cell'];
if (header) {
return header(this.addTableHeaderRowMeta({header: true, cols: this.computedCols, sort: this.sort, colsMap: this.computedColsMap}))
}
var mapFn;
if (headerCell) {
mapFn = function (col) { return headerCell({col: col, cols: this$1.computedCols, sort: this$1.sort, colsMap: this$1.computedColsMap}); };
}
else {
mapFn = function (col) { return h(QTh, {
key: col.name,
props: {
props: {
col: col,
cols: this$1.computedCols,
sort: this$1.sort,
colsMap: this$1.computedColsMap
}
}
}, col.label); };
}
var child = this.computedCols.map(mapFn);
if (this.singleSelection) {
child.unshift(h('th', { staticClass: 'q-table-col-auto-width' }, [' ']));
}
else if (this.multipleSelection) {
child.unshift(h('th', { staticClass: 'q-table-col-auto-width' }, [
h(QCheckbox, {
props: {
color: this.color,
value: this.someRowsSelected ? null : this.allRowsSelected,
dark: this.dark
},
on: {
input: function (val) {
if (this$1.someRowsSelected) {
val = false;
}
this$1.__updateSelection(
this$1.computedRows.map(function (row) { return row[this$1.rowKey]; }),
this$1.computedRows,
val
);
}
}
})
]));
}
return h('tr', child)
},
addTableHeaderRowMeta: function addTableHeaderRowMeta (data) {
var this$1 = this;
if (this.multipleSelection) {
Object.defineProperty(data, 'selected', {
get: function () { return this$1.someRowsSelected ? 'some' : this$1.allRowsSelected; },
set: function (val) {
if (this$1.someRowsSelected) {
val = false;
}
this$1.__updateSelection(
this$1.computedRows.map(function (row) { return row[this$1.rowKey]; }),
this$1.computedRows,
val
);
}
});
data.partialSelected = this.someRowsSelected;
data.multipleSelect = true;
}
return data
}
}
}
var TableBody = {
methods: {
getTableBody: function getTableBody (h) {
var this$1 = this;
var
body = this.$scopedSlots.body,
bodyCell = this.$scopedSlots['body-cell'],
topRow = this.$scopedSlots['top-row'],
bottomRow = this.$scopedSlots['bottom-row'];
var
child = [];
if (body) {
child = this.computedRows.map(function (row) {
var
key = row[this$1.rowKey],
selected = this$1.isRowSelected(key);
return body(this$1.addBodyRowMeta({
key: key,
row: row,
cols: this$1.computedCols,
colsMap: this$1.computedColsMap,
__trClass: selected ? 'selected' : ''
}))
});
}
else {
child = this.computedRows.map(function (row) {
var
key = row[this$1.rowKey],
selected = this$1.isRowSelected(key),
child = bodyCell
? this$1.computedCols.map(function (col) { return bodyCell(this$1.addBodyCellMetaData({ row: row, col: col })); })
: this$1.computedCols.map(function (col) {
var slot = this$1.$scopedSlots[("body-cell-" + (col.name))];
return slot
? slot(this$1.addBodyCellMetaData({ row: row, col: col }))
: h('td', { staticClass: col.__tdClass }, this$1.getCellValue(col, row))
});
if (this$1.selection) {
child.unshift(h('td', { staticClass: 'q-table-col-auto-width' }, [
h(QCheckbox, {
props: {
value: selected,
color: this$1.color,
dark: this$1.dark
},
on: {
input: function (adding) {
this$1.__updateSelection([key], [row], adding);
}
}
})
]));
}
return h('tr', { key: key, 'class': { selected: selected } }, child)
});
}
if (topRow) {
child.unshift(topRow({cols: this.computedCols}));
}
if (bottomRow) {
child.push(bottomRow({cols: this.computedCols}));
}
return h('tbody', child)
},
addBodyRowMeta: function addBodyRowMeta (data) {
var this$1 = this;
if (this.selection) {
Object.defineProperty(data, 'selected', {
get: function () { return this$1.isRowSelected(data.key); },
set: function (adding) {
this$1.__updateSelection([data.key], [data.row], adding);
}
});
}
Object.defineProperty(data, 'expand', {
get: function () { return this$1.rowsExpanded[data.key] === true; },
set: function (val) {
this$1.$set(this$1.rowsExpanded, data.key, val);
}
});
data.cols = data.cols.map(function (col) {
var c = Object.assign({}, col);
Object.defineProperty(c, 'value', {
get: function () { return this$1.getCellValue(col, data.row); }
});
return c
});
return data
},
addBodyCellMetaData: function addBodyCellMetaData (data) {
var this$1 = this;
Object.defineProperty(data, 'value', {
get: function () { return this$1.getCellValue(data.col, data.row); }
});
return data
},
getCellValue: function getCellValue (col, row) {
var val = typeof col.field === 'function' ? col.field(row) : row[col.field];
return col.format ? col.format(val) : val
}
}
}
var Bottom = {
methods: {
getBottom: function getBottom (h) {
if (this.hideBottom) {
return
}
if (this.nothingToDisplay) {
var message = this.filter
? this.noResultsLabel || this.$q.i18n.table.noResults
: (this.loader ? this.loaderLabel || this.$q.i18n.table.loader : this.noDataLabel || this.$q.i18n.table.noData);
return h('div', { staticClass: 'q-table-bottom row items-center q-table-nodata' }, [
h(QIcon, {props: { name: this.$q.icon.table.warning }}),
message
])
}
var bottom = this.$scopedSlots.bottom;
return h('div', { staticClass: 'q-table-bottom row items-center' },
bottom ? [ bottom(this.marginalsProps) ] : this.getPaginationRow(h)
)
},
getPaginationRow: function getPaginationRow (h) {
var this$1 = this;
var ref = this.computedPagination;
var rowsPerPage = ref.rowsPerPage;
var paginationLabel = this.paginationLabel || this.$q.i18n.table.pagination,
paginationSlot = this.$scopedSlots.pagination;
return [
h('div', { staticClass: 'col' }, [
this.selection && this.rowsSelectedNumber > 0
? (this.selectedRowsLabel || this.$q.i18n.table.selectedRows)(this.rowsSelectedNumber)
: ''
]),
h('div', { staticClass: 'flex items-center' }, [
h('span', { staticClass: 'q-mr-lg' }, [
this.rowsPerPageLabel || this.$q.i18n.table.rowsPerPage
]),
h(QSelect, {
staticClass: 'inline q-pb-none q-my-none q-ml-none q-mr-lg',
style: {
minWidth: '50px'
},
props: {
color: this.color,
value: rowsPerPage,
options: this.computedRowsPerPageOptions,
dark: this.dark,
hideUnderline: true
},
on: {
input: function (rowsPerPage) {
this$1.setPagination({
page: 1,
rowsPerPage: rowsPerPage
});
}
}
}),
paginationSlot
? paginationSlot(this.marginalsProps)
: [
h('span', { staticClass: 'q-mr-lg' }, [
rowsPerPage
? paginationLabel(this.firstRowIndex + 1, Math.min(this.lastRowIndex, this.computedRowsNumber), this.computedRowsNumber)
: paginationLabel(1, this.computedRowsNumber, this.computedRowsNumber)
]),
h(QBtn, {
props: {
color: this.color,
round: true,
icon: this.$q.icon.table.prevPage,
dense: true,
flat: true,
disable: this.isFirstPage
},
on: { click: this.prevPage }
}),
h(QBtn, {
props: {
color: this.color,
round: true,
icon: this.$q.icon.table.nextPage,
dense: true,
flat: true,
disable: this.isLastPage
},
on: { click: this.nextPage }
})
]
])
]
}
}
}
function sortDate (a, b) {
return (new Date(a)) - (new Date(b))
}
var Sort = {
props: {
sortMethod: {
type: Function,
default: function default$1 (data, sortBy, descending) {
var col = this.computedCols.find(function (def) { return def.name === sortBy; });
if (col === null || col.field === void 0) {
return data
}
var
dir = descending ? -1 : 1,
val = typeof col.field === 'function'
? function (v) { return col.field(v); }
: function (v) { return v[col.field]; };
return data.sort(function (a, b) {
var
A = val(a),
B = val(b);
if (A === null || A === void 0) {
return -1 * dir
}
if (B === null || B === void 0) {
return 1 * dir
}
if (col.sort) {
return col.sort(A, B) * dir
}
if (isNumber(A) && isNumber(B)) {
return (A - B) * dir
}
if (isDate(A) && isDate(B)) {
return sortDate(A, B) * dir
}
var assign;
(assign = [A, B].map(function (s) { return s.toLowerCase(); }), A = assign[0], B = assign[1]);
return A < B
? -1 * dir
: (A === B ? 0 : dir)
})
}
}
},
computed: {
columnToSort: function columnToSort () {
var ref = this.computedPagination;
var sortBy = ref.sortBy;
if (sortBy) {
var col = this.computedCols.find(function (def) { return def.name === sortBy; });
return col || null
}
}
},
methods: {
sort: function sort (col /* String(col name) or Object(col definition) */) {
if (col === Object(col)) {
col = col.name;
}
var ref = this.computedPagination;
var sortBy = ref.sortBy;
var descending = ref.descending;
if (sortBy !== col) {
sortBy = col;
descending = false;
}
else if (descending) {
sortBy = null;
}
else {
descending = true;
}
this.setPagination({ sortBy: sortBy, descending: descending, page: 1 });
}
}
}
var Filter = {
props: {
filter: String,
filterMethod: {
type: Function,
default: function default$1 (rows, terms, cols, cellValue) {
if ( cols === void 0 ) cols = this.computedCols;
if ( cellValue === void 0 ) cellValue = this.getCellValue;
var lowerTerms = terms ? terms.toLowerCase() : '';
return rows.filter(
function (row) { return cols.some(function (col) { return (cellValue(col, row) + '').toLowerCase().indexOf(lowerTerms) !== -1; }); }
)
}
}
},
computed: {
hasFilter: function hasFilter () {
return this.filter !== void 0 && this.filter.length > 0
}
},
watch: {
filter: function filter () {
var this$1 = this;
this.$nextTick(function () {
this$1.setPagination({ page: 1 });
});
}
}
}
var Pagination = {
props: {
pagination: Object,
rowsPerPageOptions: {
type: Array,
default: function () { return [3, 5, 7, 10, 15, 20, 25, 50, 0]; }
}
},
data: function data () {
return {
innerPagination: {
sortBy: null,
descending: false,
page: 1,
rowsPerPage: 5
}
}
},
computed: {
computedPagination: function computedPagination () {
return Object.assign({}, this.innerPagination, this.pagination)
},
firstRowIndex: function firstRowIndex () {
var ref = this.computedPagination;
var page = ref.page;
var rowsPerPage = ref.rowsPerPage;
return (page - 1) * rowsPerPage
},
lastRowIndex: function lastRowIndex () {
var ref = this.computedPagination;
var page = ref.page;
var rowsPerPage = ref.rowsPerPage;
return page * rowsPerPage
},
isFirstPage: function isFirstPage () {
var ref = this.computedPagination;
var page = ref.page;
return page <= 1
},
pagesNumber: function pagesNumber () {
var ref = this.computedPagination;
var rowsPerPage = ref.rowsPerPage;
return Math.ceil(this.computedRowsNumber / rowsPerPage)
},
isLastPage: function isLastPage () {
if (this.lastRowIndex === 0) {
return true
}
var ref = this.computedPagination;
var page = ref.page;
return page >= this.pagesNumber
},
computedRowsPerPageOptions: function computedRowsPerPageOptions () {
var this$1 = this;
return this.rowsPerPageOptions.map(function (count) { return ({
label: count === 0 ? this$1.$q.i18n.table.allRows : '' + count,
value: count
}); })
}
},
methods: {
setPagination: function setPagination (val) {
var newPagination = Object.assign({}, this.computedPagination, val);
if (this.isServerSide) {
this.requestServerInteraction({
pagination: newPagination
});
return
}
if (this.pagination) {
this.$emit('update:pagination', newPagination);
}
else {
this.innerPagination = newPagination;
}
},
prevPage: function prevPage () {
var ref = this.computedPagination;
var page = ref.page;
if (page > 1) {
this.setPagination({page: page - 1});
}
},
nextPage: function nextPage () {
var ref = this.computedPagination;
var page = ref.page;
var rowsPerPage = ref.rowsPerPage;
if (this.lastRowIndex > 0 && page * rowsPerPage < this.computedRowsNumber) {
this.setPagination({page: page + 1});
}
}
},
created: function created () {
this.$emit('update:pagination', Object.assign({}, this.computedPagination));
}
}
var RowSelection = {
props: {
selection: {
type: String,
validator: function (v) { return ['single', 'multiple'].includes(v); }
},
selected: {
type: Array,
default: function () { return []; }
}
},
computed: {
selectedKeys: function selectedKeys () {
var this$1 = this;
var keys = {};
this.selected.map(function (row) { return row[this$1.rowKey]; }).forEach(function (key) {
keys[key] = true;
});
return keys
},
singleSelection: function singleSelection () {
return this.selection === 'single'
},
multipleSelection: function multipleSelection () {
return this.selection === 'multiple'
},
allRowsSelected: function allRowsSelected () {
var this$1 = this;
if (this.multipleSelection) {
return this.computedRows.length > 0 && this.computedRows.every(function (row) { return this$1.selectedKeys[row[this$1.rowKey]] === true; })
}
},
someRowsSelected: function someRowsSelected () {
var this$1 = this;
if (this.multipleSelection) {
return !this.allRowsSelected && this.computedRows.some(function (row) { return this$1.selectedKeys[row[this$1.rowKey]] === true; })
}
},
rowsSelectedNumber: function rowsSelectedNumber () {
return this.selected.length
}
},
methods: {
isRowSelected: function isRowSelected (key) {
return this.selectedKeys[key] === true
},
clearSelection: function clearSelection () {
this.$emit('update:selected', []);
},
__updateSelection: function __updateSelection (keys, rows, adding) {
var this$1 = this;
if (this.singleSelection) {
this.$emit('update:selected', adding ? rows : []);
}
else {
this.$emit('update:selected', adding
? this.selected.concat(rows)
: this.selected.filter(function (row) { return !keys.includes(row[this$1.rowKey]); })
);
}
}
}
}
var ColumnSelection = {
props: {
visibleColumns: Array
},
computed: {
computedCols: function computedCols () {
var this$1 = this;
var ref = this.computedPagination;
var sortBy = ref.sortBy;
var descending = ref.descending;
var cols = this.visibleColumns
? this.columns.filter(function (col) { return col.required || this$1.visibleColumns.includes(col.name); })
: this.columns;
return cols.map(function (col) {
col.align = col.align || 'right';
col.__iconClass = "q-table-sort-icon q-table-sort-icon-" + (col.align);
col.__thClass = "text-" + (col.align) + (col.sortable ? ' sortable' : '') + (col.name === sortBy ? (" sorted " + (descending ? 'sort-desc' : '')) : '');
col.__tdClass = "text-" + (col.align);
return col
})
},
computedColsMap: function computedColsMap () {
var names = {};
this.computedCols.forEach(function (col) {
names[col.name] = col;
});
return names
}
}
}
var Expand = {
data: function data () {
return {
rowsExpanded: {}
}
}
}
var QTable = {
name: 'q-table',
mixins: [
FullscreenMixin,
Top,
TableHeader,
TableBody,
Bottom,
Sort,
Filter,
Pagination,
RowSelection,
ColumnSelection,
Expand
],
props: {
data: {
type: Array,
default: function () { return []; }
},
rowKey: {
type: String,
default: 'id'
},
color: {
type: String,
default: 'grey-8'
},
columns: Array,
loader: Boolean,
title: String,
hideHeader: Boolean,
hideBottom: Boolean,
dark: Boolean,
separator: {
type: String,
default: 'horizontal',
validator: function (v) { return ['horizontal', 'vertical', 'cell', 'none'].includes(v); }
},
noDataLabel: String,
noResultsLabel: String,
loaderLabel: String,
selectedRowsLabel: Function,
rowsPerPageLabel: String,
paginationLabel: Function,
tableStyle: {
type: [String, Array, Object],
default: ''
},
tableClass: {
type: [String, Array, Object],
default: ''
}
},
computed: {
computedRows: function computedRows () {
var rows = this.data.slice().map(function (row, i) {
row.__index = i;
return row
});
if (rows.length === 0) {
return []
}
if (this.isServerSide) {
return rows
}
var ref = this.computedPagination;
var sortBy = ref.sortBy;
var descending = ref.descending;
var rowsPerPage = ref.rowsPerPage;
if (this.hasFilter) {
rows = this.filterMethod(rows, this.filter, this.computedCols, this.getCellValue);
}
if (this.columnToSort) {
rows = this.sortMethod(rows, sortBy, descending);
}
if (rowsPerPage) {
rows = rows.slice(this.firstRowIndex, this.lastRowIndex);
}
return rows
},
computedRowsNumber: function computedRowsNumber () {
return this.isServerSide
? this.computedPagination.rowsNumber || 0
: this.data.length
},
nothingToDisplay: function nothingToDisplay () {
return this.computedRows.length === 0
},
isServerSide: function isServerSide () {
return this.computedPagination.rowsNumber !== void 0
}
},
render: function render (h) {
return h('div',
{
'class': {
'q-table-container': true,
'q-table-dark': this.dark,
fullscreen: this.inFullscreen,
scroll: this.inFullscreen
}
},
[
this.getTop(h),
h('div', { staticClass: 'q-table-middle scroll', 'class': this.tableClass, style: this.tableStyle }, [
h('table', { staticClass: ("q-table q-table-" + (this.separator) + "-separator" + (this.dark ? ' q-table-dark' : '')) },
[
this.getTableHeader(h),
this.getTableBody(h)
]
)
]),
this.getBottom(h)
]
)
},
methods: {
requestServerInteraction: function requestServerInteraction (prop) {
var this$1 = this;
this.$nextTick(function () {
this$1.$emit('request', {
pagination: prop.pagination || this$1.computedPagination,
filter: prop.filter || this$1.filter,
getCellValue: this$1.getCellValue
});
});
}
}
}
var QTr = {
name: 'q-tr',
props: {
props: Object
},
render: function render (h) {
return h('tr',
!this.props || this.props.header ? {} : { 'class': this.props.__trClass },
[ this.$slots.default ]
)
}
}
var QTd = {
name: 'q-td',
props: {
props: Object,
autoWidth: Boolean
},
render: function render (h) {
if (!this.props) {
return h('td', {
'class': { 'q-table-col-auto-width': this.autoWidth }
}, [ this.$slots.default ])
}
var col;
var name = this.$vnode.key;
if (name) {
col = this.props.colsMap[name];
if (!col) { return }
}
else {
col = this.props.col;
}
return h('td', {
'class': [col.__tdClass, {
'q-table-col-auto-width': this.autoWidth
}]
}, [ this.$slots.default ])
}
}
var QTableColumns = {
name: 'q-table-columns',
props: {
value: {
type: Array,
required: true
},
label: String,
columns: {
type: Array,
required: true
},
color: String
},
computed: {
computedOptions: function computedOptions () {
return this.columns.filter(function (col) { return !col.required; }).map(function (col) { return ({
value: col.name,
label: col.label
}); })
}
},
render: function render (h) {
var this$1 = this;
return h(QSelect, {
props: {
multiple: true,
toggle: true,
value: this.value,
options: this.computedOptions,
displayValue: this.label || this.$q.i18n.table.columns,
color: this.color,
hideUnderline: true
},
on: {
input: function (v) { this$1.$emit('input', v); },
change: function (v) { this$1.$emit('change', v); }
}
})
}
}
var QTimeline = {
name: 'q-timeline',
provide: function provide () {
return {
__timeline: this
}
},
props: {
color: {
type: String,
default: 'primary'
},
dark: Boolean
},
render: function render (h) {
return h('ul', {
staticClass: 'q-timeline',
'class': { 'q-timeline-dark': this.dark }
}, [
this.$slots.default
])
}
}
var QTimelineEntry = {
name: 'q-timeline-entry',
inject: {
__timeline: {
default: function default$1 () {
console.error('QTimelineEntry needs to be child of QTimeline');
}
}
},
props: {
heading: Boolean,
tag: {
type: String,
default: 'h3'
},
side: {
type: String,
default: 'right',
validator: function (v) { return ['left', 'right'].includes(v); }
},
icon: String,
color: String,
title: String,
subtitle: String
},
computed: {
colorClass: function colorClass () {
return ("text-" + (this.color || this.__timeline.color))
},
classes: function classes () {
return [
("q-timeline-entry-" + (this.side === 'left' ? 'left' : 'right')),
this.icon ? 'q-timeline-entry-with-icon' : ''
]
}
},
render: function render (h) {
if (this.heading) {
return h('div', { staticClass: 'q-timeline-heading' }, [
h('div'),
h('div'),
h(this.tag, { staticClass: 'q-timeline-heading-title' }, [
this.$slots.default
])
])
}
return h('li', {
staticClass: "q-timeline-entry",
'class': this.classes
}, [
h('div', { staticClass: 'q-timeline-subtitle' }, [
h('span', this.subtitle)
]),
h('div', {
staticClass: 'q-timeline-dot',
'class': this.colorClass
}, [
this.icon
? h(QIcon, { props: { name: this.icon } })
: null
]),
h('div', { staticClass: 'q-timeline-content' }, [
h('h6', { staticClass: 'q-timeline-title' }, [ this.title ]),
this.$slots.default
])
])
}
}
var QToolbar = {
name: 'q-toolbar',
props: {
color: String,
inverted: Boolean,
glossy: Boolean
},
computed: {
classes: function classes () {
return [
("q-toolbar-" + (this.inverted ? 'inverted' : 'normal')),
this.color ? (" " + (this.inverted ? 'text' : 'bg') + "-" + (this.color)) : '',
this.glossy ? 'glossy' : ''
]
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-toolbar row no-wrap items-center relative-position',
'class': this.classes
}, [
this.$slots.default
])
}
}
var QToolbarTitle = {
name: 'q-toolbar-title',
render: function render (h) {
return h('div', {
staticClass: 'q-toolbar-title'
}, [
this.$slots.default,
this.$slots.subtitle
? h('div', { staticClass: 'q-toolbar-subtitle' }, this.$slots.subtitle)
: null
])
}
}
var QTree = {
name: 'q-tree',
directives: {
Ripple: Ripple
},
props: {
nodes: Array,
nodeKey: {
type: String,
default: 'id'
},
color: {
type: String,
default: 'grey'
},
controlColor: String,
textColor: String,
dark: Boolean,
icon: String,
tickStrategy: {
type: String,
validator: function (v) { return ['none', 'strict', 'leaf', 'leaf-filtered'].includes(v); }
},
ticked: Array, // sync
expanded: Array, // sync
selected: {}, // sync
defaultExpandAll: Boolean,
accordion: Boolean,
filter: String,
filterMethod: {
type: Function,
default: function default$1 (node, filter) {
return node.label && node.label.indexOf(filter) > -1
}
},
noNodesLabel: String,
noResultsLabel: String
},
computed: {
hasRipple: function hasRipple () {
return "mat" === 'mat' && !this.noRipple
},
classes: function classes () {
return [
("text-" + (this.color)),
{ 'q-tree-dark': this.dark }
]
},
hasSelection: function hasSelection () {
return this.selected !== void 0
},
computedIcon: function computedIcon () {
return this.icon || this.$q.icon.tree.icon
},
computedControlColor: function computedControlColor () {
return this.controlColor || this.color
},
contentClass: function contentClass () {
return ("text-" + (this.textColor || (this.dark ? 'white' : 'black')))
},
meta: function meta () {
var this$1 = this;
var meta = {};
var travel = function (node, parent) {
var tickStrategy = node.tickStrategy || (parent ? parent.tickStrategy : this$1.tickStrategy);
var
key = node[this$1.nodeKey],
isParent = node.children && node.children.length > 0,
isLeaf = !isParent,
selectable = !node.disabled && this$1.hasSelection && node.selectable !== false,
expandable = !node.disabled && node.expandable !== false,
hasTicking = tickStrategy !== 'none',
strictTicking = tickStrategy === 'strict',
leafFilteredTicking = tickStrategy === 'leaf-filtered',
leafTicking = tickStrategy === 'leaf' || tickStrategy === 'leaf-filtered';
var tickable = !node.disabled && node.tickable !== false;
if (leafTicking && tickable && parent && !parent.tickable) {
tickable = false;
}
var lazy = node.lazy;
if (lazy && this$1.lazy[key]) {
lazy = this$1.lazy[key];
}
var m = {
key: key,
parent: parent,
isParent: isParent,
isLeaf: isLeaf,
lazy: lazy,
disabled: node.disabled,
link: selectable || (expandable && (isParent || lazy === true)),
children: [],
matchesFilter: this$1.filter ? this$1.filterMethod(node, this$1.filter) : true,
selected: key === this$1.selected && selectable,
selectable: selectable,
expanded: isParent ? this$1.innerExpanded.includes(key) : false,
expandable: expandable,
noTick: node.noTick || (!strictTicking && lazy && lazy !== 'loaded'),
tickable: tickable,
tickStrategy: tickStrategy,
hasTicking: hasTicking,
strictTicking: strictTicking,
leafFilteredTicking: leafFilteredTicking,
leafTicking: leafTicking,
ticked: strictTicking
? this$1.innerTicked.includes(key)
: (isLeaf ? this$1.innerTicked.includes(key) : false)
};
meta[key] = m;
if (isParent) {
m.children = node.children.map(function (n) { return travel(n, m); });
if (this$1.filter) {
if (!m.matchesFilter) {
m.matchesFilter = m.children.some(function (n) { return n.matchesFilter; });
}
if (
m.matchesFilter &&
!m.noTick &&
!m.disabled &&
m.tickable &&
leafFilteredTicking &&
m.children.every(function (n) { return !n.matchesFilter || n.noTick || !n.tickable; })
) {
m.tickable = false;
}
}
if (m.matchesFilter) {
if (!m.noTick && !strictTicking && m.children.every(function (n) { return n.noTick; })) {
m.noTick = true;
}
if (leafTicking) {
m.ticked = false;
m.indeterminate = m.children.some(function (node) { return node.indeterminate; });
if (!m.indeterminate) {
var sel = m.children
.reduce(function (acc, meta) { return meta.ticked ? acc + 1 : acc; }, 0);
if (sel === m.children.length) {
m.ticked = true;
}
else if (sel > 0) {
m.indeterminate = true;
}
}
}
}
}
return m
};
this.nodes.forEach(function (node) { return travel(node, null); });
return meta
}
},
data: function data () {
return {
lazy: {},
innerTicked: this.ticked || [],
innerExpanded: this.expanded || []
}
},
watch: {
ticked: function ticked (val) {
this.innerTicked = val;
},
expanded: function expanded (val) {
this.innerExpanded = val;
}
},
methods: {
getNodeByKey: function getNodeByKey (key) {
var this$1 = this;
var reduce = [].reduce;
var find = function (result, node) {
if (result || !node) {
return result
}
if (Array.isArray(node)) {
return reduce.call(Object(node), find, result)
}
if (node[this$1.nodeKey] === key) {
return node
}
if (node.children) {
return find(null, node.children)
}
};
return find(null, this.nodes)
},
getTickedNodes: function getTickedNodes () {
var this$1 = this;
return this.innerTicked.map(function (key) { return this$1.getNodeByKey(key); })
},
getExpandedNodes: function getExpandedNodes () {
var this$1 = this;
return this.innerExpanded.map(function (key) { return this$1.getNodeByKey(key); })
},
isExpanded: function isExpanded (key) {
return key && this.meta[key]
? this.meta[key].expanded
: false
},
collapseAll: function collapseAll () {
if (this.expanded !== void 0) {
this.$emit('update:expanded', []);
}
else {
this.innerExpanded = [];
}
},
expandAll: function expandAll () {
var this$1 = this;
var
expanded = this.innerExpanded,
travel = function (node) {
if (node.children && node.children.length > 0) {
if (node.expandable !== false && node.disabled !== true) {
expanded.push(node[this$1.nodeKey]);
node.children.forEach(travel);
}
}
};
this.nodes.forEach(travel);
if (this.expanded !== void 0) {
this.$emit('update:expanded', expanded);
}
else {
this.innerExpanded = expanded;
}
},
setExpanded: function setExpanded (key, state, node, meta) {
var this$1 = this;
if ( node === void 0 ) node = this.getNodeByKey(key);
if ( meta === void 0 ) meta = this.meta[key];
if (meta.lazy && meta.lazy !== 'loaded') {
if (meta.lazy === 'loading') {
return
}
this.$set(this.lazy, key, 'loading');
this.$emit('lazy-load', {
node: node,
key: key,
done: function (children) {
this$1.lazy[key] = 'loaded';
if (children) {
node.children = children;
}
this$1.$nextTick(function () {
var m = this$1.meta[key];
if (m && m.isParent) {
this$1.__setExpanded(key, true);
}
});
},
fail: function () {
this$1.$delete(this$1.lazy, key);
}
});
}
else if (meta.isParent && meta.expandable) {
this.__setExpanded(key, state);
}
},
__setExpanded: function __setExpanded (key, state) {
var this$1 = this;
var target = this.innerExpanded;
var emit = this.expanded !== void 0;
if (emit) {
target = target.slice();
}
if (state) {
if (this.accordion) {
if (this.meta[key]) {
var collapse = [];
if (this.meta[key].parent) {
this.meta[key].parent.children.forEach(function (m) {
if (m.key !== key && m.expandable) {
collapse.push(m.key);
}
});
}
else {
this.nodes.forEach(function (node) {
var k = node[this$1.nodeKey];
if (k !== key) {
collapse.push(k);
}
});
}
if (collapse.length > 0) {
target = target.filter(function (k) { return !collapse.includes(k); });
}
}
}
target = target.concat([ key ])
.filter(function (key, index, self) { return self.indexOf(key) === index; });
}
else {
target = target.filter(function (k) { return k !== key; });
}
if (emit) {
this.$emit("update:expanded", target);
}
},
isTicked: function isTicked (key) {
return key && this.meta[key]
? this.meta[key].ticked
: false
},
setTicked: function setTicked (keys, state) {
var target = this.innerTicked;
var emit = this.ticked !== void 0;
if (emit) {
target = target.slice();
}
if (state) {
target = target.concat(keys)
.filter(function (key, index, self) { return self.indexOf(key) === index; });
}
else {
target = target.filter(function (k) { return !keys.includes(k); });
}
if (emit) {
this.$emit("update:ticked", target);
}
},
__getSlotScope: function __getSlotScope (node, meta, key) {
var this$1 = this;
var scope = { tree: this, node: node, key: key, color: this.color, dark: this.dark };
Object.defineProperty(scope, 'expanded', {
get: function () { return meta.expanded },
set: function (val) { val !== meta.expanded && this$1.setExpanded(key, val); }
});
Object.defineProperty(scope, 'ticked', {
get: function () { return meta.ticked },
set: function (val) { val !== meta.ticked && this$1.setTicked([ key ], val); }
});
return scope
},
__getChildren: function __getChildren (h, nodes) {
var this$1 = this;
return (
this.filter
? nodes.filter(function (n) { return this$1.meta[n[this$1.nodeKey]].matchesFilter; })
: nodes
).map(function (child) { return this$1.__getNode(h, child); })
},
__getNodeMedia: function __getNodeMedia (h, node) {
if (node.icon) {
return h(QIcon, {
staticClass: "q-tree-icon q-mr-sm",
props: { name: node.icon }
})
}
if (node.img || node.avatar) {
return h('img', {
staticClass: "q-tree-img q-mr-sm",
'class': { avatar: node.avatar },
domProps: { src: node.img || node.avatar }
})
}
},
__getNode: function __getNode (h, node) {
var this$1 = this;
var
key = node[this.nodeKey],
meta = this.meta[key],
header = node.header
? this.$scopedSlots[("header-" + (node.header))] || this.$scopedSlots['default-header']
: this.$scopedSlots['default-header'];
var children = meta.isParent
? this.__getChildren(h, node.children)
: [];
var isParent = children.length > 0 || (meta.lazy && meta.lazy !== 'loaded');
var
body = node.body
? this.$scopedSlots[("body-" + (node.body))] || this.$scopedSlots['default-body']
: this.$scopedSlots['default-body'],
slotScope = header || body
? this.__getSlotScope(node, meta, key)
: null;
if (body) {
body = h('div', { staticClass: 'q-tree-node-body relative-position' }, [
h('div', { 'class': this.contentClass }, [
body(slotScope)
])
]);
}
return h('div', {
key: key,
staticClass: 'q-tree-node',
'class': { 'q-tree-node-parent': isParent }
}, [
h('div', {
staticClass: 'q-tree-node-header relative-position row no-wrap items-center',
'class': {
'q-tree-node-link': meta.link,
'q-tree-node-selected': meta.selected,
disabled: meta.disabled
},
on: { click: function () { this$1.__onClick(node, meta); } },
directives: "mat" === 'mat' && meta.selectable
? [{ name: 'ripple' }]
: null
}, [
meta.lazy === 'loading'
? h(QSpinner, {
staticClass: 'q-tree-node-header-media q-mr-xs',
props: { color: this.computedControlColor }
})
: (
isParent
? h(QIcon, {
staticClass: 'q-tree-arrow q-mr-xs transition-generic',
'class': { 'rotate-90': meta.expanded },
props: { name: this.computedIcon },
nativeOn: this.hasSelection
? { click: function (e) { this$1.__onExpandClick(node, meta, e); } }
: undefined
})
: null
),
h('span', { 'staticClass': 'row no-wrap items-center', 'class': this.contentClass }, [
meta.hasTicking && !meta.noTick
? h(QCheckbox, {
staticClass: 'q-mr-xs',
props: {
value: meta.indeterminate ? null : meta.ticked,
color: this.computedControlColor,
dark: this.dark,
keepColor: true,
disable: !meta.tickable
},
on: {
input: function (v) {
this$1.__onTickedClick(node, meta, v);
}
}
})
: null,
header
? header(slotScope)
: [
this.__getNodeMedia(h, node),
h('span', node.label)
]
])
]),
isParent
? h(QSlideTransition, [
h('div', {
directives: [{ name: 'show', value: meta.expanded }],
staticClass: 'q-tree-node-collapsible',
'class': ("text-" + (this.color))
}, [
body,
h('div', {
staticClass: 'q-tree-children',
'class': { disabled: meta.disabled }
}, children)
])
])
: body
])
},
__onClick: function __onClick (node, meta) {
if (this.hasSelection) {
if (meta.selectable) {
this.$emit('update:selected', meta.key !== this.selected ? meta.key : null);
}
}
else {
this.__onExpandClick(node, meta);
}
if (typeof node.handler === 'function') {
node.handler(node);
}
},
__onExpandClick: function __onExpandClick (node, meta, e) {
if (e !== void 0) {
e.stopPropagation();
}
this.setExpanded(meta.key, !meta.expanded, node, meta);
},
__onTickedClick: function __onTickedClick (node, meta, state) {
if (meta.indeterminate && state) {
state = false;
}
if (meta.strictTicking) {
this.setTicked([ meta.key ], state);
}
else if (meta.leafTicking) {
var keys = [];
var travel = function (meta) {
if (meta.isParent) {
if (!state && !meta.noTick && meta.tickable) {
keys.push(meta.key);
}
if (meta.leafTicking) {
meta.children.forEach(travel);
}
}
else if (!meta.noTick && meta.tickable && (!meta.leafFilteredTicking || meta.matchesFilter)) {
keys.push(meta.key);
}
};
travel(meta);
this.setTicked(keys, state);
}
}
},
render: function render (h) {
var children = this.__getChildren(h, this.nodes);
return h(
'div', {
staticClass: 'q-tree relative-position',
'class': this.classes
},
children.length === 0
? (
this.filter
? this.noResultsLabel || this.$q.i18n.tree.noResults
: this.noNodesLabel || this.$q.i18n.tree.noNodes
)
: children
)
},
created: function created () {
if (this.defaultExpandAll) {
this.expandAll();
}
}
}
function initFile (file) {
file.__doneUploading = false;
file.__failed = false;
file.__uploaded = 0;
file.__progress = 0;
}
var QUploader = {render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"q-uploader relative-position",on:{"dragover":function($event){$event.preventDefault();$event.stopPropagation();_vm.__onDragOver($event);}}},[_c('q-input-frame',{ref:"input",staticClass:"no-margin",attrs:{"prefix":_vm.prefix,"suffix":_vm.suffix,"stack-label":_vm.stackLabel,"float-label":_vm.floatLabel,"error":_vm.error,"warning":_vm.warning,"disable":_vm.disable,"inverted":_vm.inverted,"dark":_vm.dark,"hide-underline":_vm.hideUnderline,"before":_vm.before,"after":_vm.after,"color":_vm.color,"align":_vm.align,"length":_vm.queueLength,"additional-length":""}},[_c('div',{staticClass:"col row items-center q-input-target",domProps:{"innerHTML":_vm._s(_vm.label)}}),_vm._v(" "),(_vm.uploading)?_c('q-spinner',{staticClass:"q-if-control",attrs:{"slot":"after","size":"24px"},slot:"after"}):_vm._e(),_vm._v(" "),(_vm.uploading)?_c('q-icon',{staticClass:"q-if-control",attrs:{"slot":"after","name":_vm.$q.icon.uploader.clear},nativeOn:{"click":function($event){_vm.abort($event);}},slot:"after"}):_vm._e(),_vm._v(" "),(!_vm.uploading)?_c('q-icon',{staticClass:"q-uploader-pick-button q-if-control relative-position overflow-hidden",attrs:{"slot":"after","name":_vm.$q.icon.uploader.add,"disabled":_vm.addDisabled},nativeOn:{"click":function($event){_vm.__pick($event);}},slot:"after"},[_c('input',_vm._b({ref:"file",staticClass:"q-uploader-input absolute-full cursor-pointer",attrs:{"type":"file","accept":_vm.extensions},on:{"change":_vm.__add}},'input',{multiple: _vm.multiple},true))]):_vm._e(),_vm._v(" "),(!_vm.hideUploadButton && !_vm.uploading)?_c('q-icon',{staticClass:"q-if-control",attrs:{"slot":"after","name":_vm.$q.icon.uploader.upload,"disabled":_vm.queueLength === 0},nativeOn:{"click":function($event){_vm.upload($event);}},slot:"after"}):_vm._e(),_vm._v(" "),(_vm.hasExpandedContent)?_c('q-icon',{staticClass:"q-if-control generic_transition",class:{'rotate-180': _vm.expanded},attrs:{"slot":"after","name":_vm.$q.icon.uploader.expand},nativeOn:{"click":function($event){_vm.expanded = !_vm.expanded;}},slot:"after"}):_vm._e()],1),_vm._v(" "),_c('q-slide-transition',[_c('div',{directives:[{name:"show",rawName:"v-show",value:(_vm.expanded),expression:"expanded"}]},[_c('div',{staticClass:"q-uploader-files scroll",style:(_vm.filesStyle)},_vm._l((_vm.files),function(file){return _c('q-item',{key:file.name + file.__timestamp,staticClass:"q-uploader-file q-pa-xs"},[(!_vm.hideUploadProgress)?_c('q-progress',{staticClass:"q-uploader-progress-bg absolute-full",attrs:{"color":file.__failed ? 'negative' : 'grey',"percentage":file.__progress,"height":"100%"}}):_vm._e(),_vm._v(" "),(!_vm.hideUploadProgress)?_c('div',{staticClass:"q-uploader-progress-text absolute"},[_vm._v(" "+_vm._s(file.__progress)+"% ")]):_vm._e(),_vm._v(" "),(file.__img)?_c('q-item-side',{attrs:{"image":file.__img.src}}):_c('q-item-side',{attrs:{"icon":_vm.$q.icon.uploader.file,"color":_vm.color}}),_vm._v(" "),_c('q-item-main',{attrs:{"label":file.name,"sublabel":file.__size}}),_vm._v(" "),_c('q-item-side',{attrs:{"right":""}},[_c('q-item-tile',{staticClass:"cursor-pointer",attrs:{"icon":_vm.$q.icon.uploader[file.__doneUploading ? 'done' : 'clear'],"color":_vm.color},nativeOn:{"click":function($event){_vm.__remove(file);}}})],1)],1)}))])]),_vm._v(" "),(_vm.dnd)?_c('div',{staticClass:"q-uploader-dnd flex row items-center justify-center absolute-full",class:_vm.dndClass,on:{"dragenter":function($event){$event.preventDefault();$event.stopPropagation();},"dragover":function($event){$event.preventDefault();$event.stopPropagation();},"dragleave":function($event){$event.preventDefault();$event.stopPropagation();_vm.__onDragLeave($event);},"drop":function($event){$event.preventDefault();$event.stopPropagation();_vm.__onDrop($event);}}}):_vm._e()],1)},staticRenderFns: [],
name: 'q-uploader',
mixins: [FrameMixin],
components: {
QInputFrame: QInputFrame,
QSpinner: QSpinner,
QIcon: QIcon,
QProgress: QProgress,
QItem: QItem,
QItemSide: QItemSide,
QItemMain: QItemMain,
QItemTile: QItemTile,
QSlideTransition: QSlideTransition
},
props: {
name: {
type: String,
default: 'file'
},
headers: Object,
url: {
type: String,
required: true
},
urlFactory: {
type: Function,
required: false
},
additionalFields: {
type: Array,
default: function () { return []; }
},
method: {
type: String,
default: 'POST'
},
extensions: String,
multiple: Boolean,
hideUploadButton: Boolean,
hideUploadProgress: Boolean,
noThumbnails: Boolean,
autoExpand: Boolean,
expandStyle: [Array, String, Object],
expandClass: [Array, String, Object],
sendRaw: {
type: Boolean,
default: false
}
},
data: function data () {
return {
queue: [],
files: [],
uploading: false,
uploadedSize: 0,
totalSize: 0,
xhrs: [],
focused: false,
dnd: false,
expanded: false
}
},
computed: {
queueLength: function queueLength () {
return this.queue.length
},
hasExpandedContent: function hasExpandedContent () {
return this.files.length > 0
},
label: function label () {
var total = humanStorageSize(this.totalSize);
return this.uploading
? (((this.progress).toFixed(2)) + "% (" + (humanStorageSize(this.uploadedSize)) + " / " + total + ")")
: ((this.queueLength) + " (" + total + ")")
},
progress: function progress () {
return this.totalSize ? Math.min(99.99, this.uploadedSize / this.totalSize * 100) : 0
},
addDisabled: function addDisabled () {
return !this.multiple && this.queueLength >= 1
},
filesStyle: function filesStyle () {
if (this.maxHeight) {
return { maxHeight: this.maxHeight }
}
},
dndClass: function dndClass () {
var cls = [("text-" + (this.color))];
if (this.inverted) {
cls.push('inverted');
}
return cls
}
},
watch: {
hasExpandedContent: function hasExpandedContent (v) {
if (v === false) {
this.expanded = false;
}
else if (this.autoExpand) {
this.expanded = true;
}
}
},
methods: {
__onDragOver: function __onDragOver () {
this.dnd = true;
},
__onDragLeave: function __onDragLeave () {
this.dnd = false;
},
__onDrop: function __onDrop (e) {
this.dnd = false;
var
files = e.dataTransfer.files,
count = files.length;
if (count > 0) {
this.__add(null, this.multiple ? files : [ files[0] ]);
}
},
__add: function __add (e, files) {
var this$1 = this;
if (this.addDisabled) {
return
}
files = Array.prototype.slice.call(files || e.target.files);
this.$refs.file.value = '';
var filesReady = []; // List of image load promises
files = files.filter(function (file) { return !this$1.queue.some(function (f) { return file.name === f.name; }); })
.map(function (file) {
initFile(file);
file.__size = humanStorageSize(file.size);
file.__timestamp = new Date().getTime();
if (this$1.noThumbnails || !file.type.startsWith('image')) {
this$1.queue.push(file);
}
else {
var reader = new FileReader();
var p = new Promise(function (resolve, reject) {
reader.onload = function (e) {
var img = new Image();
img.src = e.target.result;
file.__img = img;
this$1.queue.push(file);
this$1.__computeTotalSize();
resolve(true);
};
reader.onerror = function (e) {
reject(e);
};
});
reader.readAsDataURL(file);
filesReady.push(p);
}
return file
});
if (files.length > 0) {
this.files = this.files.concat(files);
Promise.all(filesReady).then(function () {
this$1.$emit('add', files);
});
this.__computeTotalSize();
}
},
__computeTotalSize: function __computeTotalSize () {
this.totalSize = this.queueLength
? this.queue.map(function (f) { return f.size; }).reduce(function (total, size) { return total + size; })
: 0;
},
__remove: function __remove (file) {
var
name = file.name,
done = file.__doneUploading;
if (this.uploading && !done) {
this.$emit('remove:abort', file, file.xhr);
file.xhr.abort();
this.uploadedSize -= file.__uploaded;
}
else {
this.$emit(("remove:" + (done ? 'done' : 'cancel')), file, file.xhr);
}
if (!done) {
this.queue = this.queue.filter(function (obj) { return obj.name !== name; });
}
file.__removed = true;
this.files = this.files.filter(function (obj) { return obj.name !== name; });
this.__computeTotalSize();
},
__pick: function __pick () {
if (!this.addDisabled && this.$q.platform.is.mozilla) {
this.$refs.file.click();
}
},
__getUploadPromise: function __getUploadPromise (file) {
var this$1 = this;
var
form = new FormData(),
xhr = new XMLHttpRequest();
try {
this.additionalFields.forEach(function (field) {
form.append(field.name, field.value);
});
form.append('Content-Type', file.type || 'application/octet-stream');
form.append(this.name, file);
}
catch (e) {
return
}
initFile(file);
file.xhr = xhr;
return new Promise(function (resolve, reject) {
xhr.upload.addEventListener('progress', function (e) {
if (file.__removed) { return }
e.percent = e.total ? e.loaded / e.total : 0;
var uploaded = e.percent * file.size;
this$1.uploadedSize += uploaded - file.__uploaded;
file.__uploaded = uploaded;
file.__progress = Math.min(99, parseInt(e.percent * 100, 10));
}, false);
xhr.onreadystatechange = function () {
if (xhr.readyState < 4) {
return
}
if (xhr.status && xhr.status < 400) {
file.__doneUploading = true;
file.__progress = 100;
this$1.$emit('uploaded', file, xhr);
resolve(file);
}
else {
file.__failed = true;
this$1.$emit('fail', file, xhr);
reject(xhr);
}
};
xhr.onerror = function () {
file.__failed = true;
this$1.$emit('fail', file, xhr);
reject(xhr);
};
var resolver = this$1.urlFactory
? this$1.urlFactory(file)
: Promise.resolve(this$1.url);
resolver.then(function (url) {
xhr.open(this$1.method, url, true);
if (this$1.headers) {
Object.keys(this$1.headers).forEach(function (key) {
xhr.setRequestHeader(key, this$1.headers[key]);
});
}
this$1.xhrs.push(xhr);
if (this$1.sendRaw) {
xhr.send(file);
}
else {
xhr.send(form);
}
});
})
},
pick: function pick () {
if (!this.addDisabled) {
this.$refs.file.click();
}
},
upload: function upload () {
var this$1 = this;
var length = this.queueLength;
if (this.disable || length === 0) {
return
}
var filesDone = 0;
this.uploadedSize = 0;
this.uploading = true;
this.xhrs = [];
this.$emit('start');
var solved = function () {
filesDone++;
if (filesDone === length) {
this$1.uploading = false;
this$1.xhrs = [];
this$1.queue = this$1.queue.filter(function (f) { return !f.__doneUploading; });
this$1.__computeTotalSize();
this$1.$emit('finish');
}
};
this.queue
.map(function (file) { return this$1.__getUploadPromise(file); })
.forEach(function (promise) {
promise.then(solved).catch(solved);
});
},
abort: function abort () {
this.xhrs.forEach(function (xhr) { xhr.abort(); });
},
reset: function reset () {
this.abort();
this.files = [];
this.queue = [];
this.expanded = false;
this.__computeTotalSize();
this.$emit('reset');
}
}
}
var QVideo = {
name: 'q-video',
props: {
src: {
type: String,
required: true
}
},
computed: {
iframeData: function iframeData () {
return {
attrs: {
src: this.src,
frameborder: '0',
allowfullscreen: true
}
}
}
},
render: function render (h) {
return h('div', {
staticClass: 'q-video'
}, [
h('iframe', this.iframeData)
])
}
}
var components = Object.freeze({
QActionSheet: QActionSheet,
QAjaxBar: QAjaxBar,
QAlert: QAlert,
QAutocomplete: QAutocomplete,
QBreadcrumbs: QBreadcrumbs,
QBreadcrumbsEl: QBreadcrumbsEl,
QBtn: QBtn,
QBtnGroup: QBtnGroup,
QBtnDropdown: QBtnDropdown,
QBtnToggle: QBtnToggle,
QCard: QCard,
QCardTitle: QCardTitle,
QCardMain: QCardMain,
QCardActions: QCardActions,
QCardMedia: QCardMedia,
QCardSeparator: QCardSeparator,
QCarousel: QCarousel,
QCarouselSlide: QCarouselSlide,
QCarouselControl: QCarouselControl,
QChatMessage: QChatMessage,
QCheckbox: QCheckbox,
QChip: QChip,
QChipsInput: QChipsInput,
QCollapsible: QCollapsible,
QColor: QColor,
QColorPicker: QColorPicker,
QContextMenu: QContextMenu,
QDatetime: QDatetime,
QDatetimePicker: QDatetimePicker,
QDialog: QDialog,
QEditor: QEditor,
QFab: QFab,
QFabAction: QFabAction,
QField: QField,
QFieldReset: QFieldReset,
QIcon: QIcon,
QInfiniteScroll: QInfiniteScroll,
QInnerLoading: QInnerLoading,
QInput: QInput,
QInputFrame: QInputFrame,
QKnob: QKnob,
QLayout: QLayout,
QLayoutDrawer: QLayoutDrawer,
QLayoutFooter: QLayoutFooter,
QLayoutHeader: QLayoutHeader,
QPage: QPage,
QPageContainer: QPageContainer,
QPageSticky: QPageSticky,
QItem: QItem,
QItemSeparator: QItemSeparator,
QItemMain: QItemMain,
QItemSide: QItemSide,
QItemTile: QItemTile,
QItemWrapper: QItemWrapper,
QList: QList,
QListHeader: QListHeader,
QModal: QModal,
QModalLayout: QModalLayout,
QResizeObservable: QResizeObservable,
QScrollObservable: QScrollObservable,
QWindowResizeObservable: QWindowResizeObservable,
QOptionGroup: QOptionGroup,
QPagination: QPagination,
QParallax: QParallax,
QPopover: QPopover,
QProgress: QProgress,
QPullToRefresh: QPullToRefresh,
QRadio: QRadio,
QRange: QRange,
QRating: QRating,
QScrollArea: QScrollArea,
QSearch: QSearch,
QSelect: QSelect,
QSlideTransition: QSlideTransition,
QSlider: QSlider,
QSpinner: QSpinner,
QSpinnerAudio: audio,
QSpinnerBall: ball,
QSpinnerBars: bars,
QSpinnerCircles: circles,
QSpinnerComment: comment,
QSpinnerCube: cube,
QSpinnerDots: dots,
QSpinnerFacebook: facebook,
QSpinnerGears: gears,
QSpinnerGrid: grid,
QSpinnerHearts: hearts,
QSpinnerHourglass: hourglass,
QSpinnerInfinity: infinity,
QSpinnerIos: QSpinner_ios,
QSpinnerMat: DefaultSpinner,
QSpinnerOval: oval,
QSpinnerPie: pie,
QSpinnerPuff: puff,
QSpinnerRadio: radio,
QSpinnerRings: rings,
QSpinnerTail: tail,
QStep: QStep,
QStepper: QStepper,
QStepperNavigation: QStepperNavigation,
QRouteTab: QRouteTab,
QTab: QTab,
QTabPane: QTabPane,
QTabs: QTabs,
QTable: QTable,
QTh: QTh,
QTr: QTr,
QTd: QTd,
QTableColumns: QTableColumns,
QTimeline: QTimeline,
QTimelineEntry: QTimelineEntry,
QToggle: QToggle,
QToolbar: QToolbar,
QToolbarTitle: QToolbarTitle,
QTooltip: QTooltip,
QTree: QTree,
QUploader: QUploader,
QVideo: QVideo
});
function updateBinding (el, ref) {
var value = ref.value;
var modifiers = ref.modifiers;
var ctx = el.__qbacktotop;
if (!value) {
ctx.update();
return
}
if (typeof value === 'number') {
ctx.offset = value;
ctx.update();
return
}
if (value && Object(value) !== value) {
console.error('v-back-to-top requires an object {offset, duration} as parameter', el);
return
}
if (value.offset) {
if (typeof value.offset !== 'number') {
console.error('v-back-to-top requires a number as offset', el);
return
}
ctx.offset = value.offset;
}
if (value.duration) {
if (typeof value.duration !== 'number') {
console.error('v-back-to-top requires a number as duration', el);
return
}
ctx.duration = value.duration;
}
ctx.update();
}
var backToTop = {
name: 'back-to-top',
bind: function bind (el) {
var ctx = {
offset: 200,
duration: 300,
update: debounce(function () {
var trigger = getScrollPosition(ctx.scrollTarget) > ctx.offset;
if (ctx.visible !== trigger) {
ctx.visible = trigger;
el.classList[trigger ? 'remove' : 'add']('hidden');
}
}, 25),
goToTop: function goToTop () {
setScrollPosition(ctx.scrollTarget, 0, ctx.animate ? ctx.duration : 0);
}
};
el.classList.add('hidden');
el.__qbacktotop = ctx;
},
inserted: function inserted (el, binding) {
var ctx = el.__qbacktotop;
ctx.scrollTarget = getScrollTarget(el);
ctx.animate = binding.modifiers.animate;
updateBinding(el, binding);
ctx.scrollTarget.addEventListener('scroll', ctx.update);
window.addEventListener('resize', ctx.update);
el.addEventListener('click', ctx.goToTop);
},
update: function update (el, binding) {
if (binding.oldValue !== binding.value) {
updateBinding(el, binding);
}
},
unbind: function unbind (el) {
var ctx = el.__qbacktotop;
ctx.scrollTarget.removeEventListener('scroll', ctx.update);
window.removeEventListener('resize', ctx.update);
el.removeEventListener('click', ctx.goToTop);
delete el.__qbacktotop;
}
}
var closeOverlay = {
name: 'close-overlay',
bind: function bind (el, binding, vnode) {
var handler = function () {
var vm = vnode.componentInstance;
while ((vm = vm.$parent)) {
var name = vm.$options.name;
if (name === 'q-popover' || name === 'q-modal') {
vm.hide();
break
}
}
};
el.__qclose = { handler: handler };
el.addEventListener('click', handler);
},
unbind: function unbind (el) {
el.removeEventListener('click', el.__qclose.handler);
delete el.__qclose;
}
}
var goBack = {
name: 'go-back',
bind: function bind (el, ref, vnode) {
var value = ref.value;
var modifiers = ref.modifiers;
var ctx = { value: value, position: window.history.length - 1, single: modifiers.single };
if (Platform.is.cordova) {
ctx.goBack = function () {
vnode.context.$router.go(ctx.single ? -1 : ctx.position - window.history.length);
};
}
else {
ctx.goBack = function () {
vnode.context.$router.replace(ctx.value);
};
}
el.__qgoback = ctx;
el.addEventListener('click', ctx.goBack);
},
update: function update (el, binding) {
if (binding.oldValue !== binding.value) {
el.__qgoback.value = binding.value;
}
},
unbind: function unbind (el) {
el.removeEventListener('click', el.__qgoback.goBack);
delete el.__qgoback;
}
}
function updateBinding$1 (el, selector) {
var
ctx = el.__qmove,
parent = el.parentNode;
if (!ctx.target) {
ctx.target = document.querySelector(selector);
}
if (ctx.target) {
if (parent !== ctx.target) {
ctx.target.appendChild(el);
}
}
else if (parent) {
parent.removeChild(el);
}
}
var move = {
name: 'move',
bind: function bind (el, ref) {
var value = ref.value;
el.__qmove = {};
},
update: function update (el, ref) {
var oldValue = ref.oldValue;
var value = ref.value;
if (oldValue !== value) {
el.__qmove.target = document.querySelector(value);
updateBinding$1(el, value);
}
},
inserted: function inserted (el, ref) {
var value = ref.value;
updateBinding$1(el, value);
},
unbind: function unbind (el) {
var parent = el.parentNode;
if (parent) {
parent.removeChild(el);
}
delete el.__qmove;
}
}
function updateBinding$2 (el, binding) {
var ctx = el.__qscrollfire;
if (typeof binding.value !== 'function') {
ctx.scrollTarget.removeEventListener('scroll', ctx.scroll);
console.error('v-scroll-fire requires a function as parameter', el);
return
}
ctx.handler = binding.value;
if (typeof binding.oldValue !== 'function') {
ctx.scrollTarget.addEventListener('scroll', ctx.scroll);
ctx.scroll();
}
}
var scrollFire = {
name: 'scroll-fire',
bind: function bind (el, binding) {
var ctx = {
scroll: debounce(function () {
var containerBottom, elementBottom, fire;
if (ctx.scrollTarget === window) {
elementBottom = el.getBoundingClientRect().bottom;
fire = elementBottom < viewport().height;
}
else {
containerBottom = offset(ctx.scrollTarget).top + height(ctx.scrollTarget);
elementBottom = offset(el).top + height(el);
fire = elementBottom < containerBottom;
}
if (fire) {
ctx.scrollTarget.removeEventListener('scroll', ctx.scroll);
ctx.handler(el);
}
}, 25)
};
el.__qscrollfire = ctx;
},
inserted: function inserted (el, binding) {
var ctx = el.__qscrollfire;
ctx.scrollTarget = getScrollTarget(el);
updateBinding$2(el, binding);
},
update: function update (el, binding) {
if (binding.value !== binding.oldValue) {
updateBinding$2(el, binding);
}
},
unbind: function unbind (el) {
var ctx = el.__qscrollfire;
ctx.scrollTarget.removeEventListener('scroll', ctx.scroll);
delete el.__qscrollfire;
}
}
function updateBinding$3 (el, binding) {
var ctx = el.__qscroll;
if (typeof binding.value !== 'function') {
ctx.scrollTarget.removeEventListener('scroll', ctx.scroll);
console.error('v-scroll requires a function as parameter', el);
return
}
ctx.handler = binding.value;
if (typeof binding.oldValue !== 'function') {
ctx.scrollTarget.addEventListener('scroll', ctx.scroll);
}
}
var scroll$1 = {
name: 'scroll',
bind: function bind (el, binding) {
var ctx = {
scroll: function scroll () {
ctx.handler(getScrollPosition(ctx.scrollTarget));
}
};
el.__qscroll = ctx;
},
inserted: function inserted (el, binding) {
var ctx = el.__qscroll;
ctx.scrollTarget = getScrollTarget(el);
updateBinding$3(el, binding);
},
update: function update (el, binding) {
if (binding.oldValue !== binding.value) {
updateBinding$3(el, binding);
}
},
unbind: function unbind (el) {
var ctx = el.__qscroll;
ctx.scrollTarget.removeEventListener('scroll', ctx.scroll);
delete el.__qscroll;
}
}
function updateBinding$4 (el, binding) {
var ctx = el.__qtouchhold;
ctx.duration = parseInt(binding.arg, 10) || 800;
if (binding.oldValue !== binding.value) {
ctx.handler = binding.value;
}
}
var touchHold = {
name: 'touch-hold',
bind: function bind (el, binding) {
var mouse = !binding.modifiers.nomouse;
var ctx = {
start: function start (evt) {
var startTime = new Date().getTime();
ctx.timer = setTimeout(function () {
if (mouse) {
document.removeEventListener('mousemove', ctx.mouseAbort);
document.removeEventListener('mouseup', ctx.mouseAbort);
}
ctx.handler({
evt: evt,
position: position(evt),
duration: new Date().getTime() - startTime
});
}, ctx.duration);
},
mouseStart: function mouseStart (evt) {
if (mouse) {
document.addEventListener('mousemove', ctx.mouseAbort);
document.addEventListener('mouseup', ctx.mouseAbort);
}
ctx.start(evt);
},
abort: function abort (evt) {
clearTimeout(ctx.timer);
ctx.timer = null;
},
mouseAbort: function mouseAbort (evt) {
if (mouse) {
document.removeEventListener('mousemove', ctx.mouseAbort);
document.removeEventListener('mouseup', ctx.mouseAbort);
}
ctx.abort(evt);
}
};
el.__qtouchhold = ctx;
updateBinding$4(el, binding);
el.addEventListener('touchstart', ctx.start);
el.addEventListener('touchend', ctx.abort);
if (mouse) {
el.addEventListener('touchmove', ctx.abort);
el.addEventListener('mousedown', ctx.mouseStart);
}
},
update: function update (el, binding) {
updateBinding$4(el, binding);
},
unbind: function unbind (el, binding) {
var ctx = el.__qtouchhold;
el.removeEventListener('touchstart', ctx.start);
el.removeEventListener('touchend', ctx.abort);
el.removeEventListener('touchmove', ctx.abort);
el.removeEventListener('mousedown', ctx.mouseStart);
document.removeEventListener('mousemove', ctx.mouseAbort);
document.removeEventListener('mouseup', ctx.mouseAbort);
delete el.__qtouchhold;
}
}
var directives = Object.freeze({
BackToTop: backToTop,
CloseOverlay: closeOverlay,
GoBack: goBack,
Move: move,
Ripple: Ripple,
ScrollFire: scrollFire,
Scroll: scroll$1,
TouchHold: touchHold,
TouchPan: TouchPan,
TouchSwipe: TouchSwipe
});
function modalFn (Component, Vue$$1) {
return function (props) {
var node = document.createElement('div');
document.body.appendChild(node);
return new Promise(function (resolve, reject) {
var vm = new Vue$$1({
el: node,
data: function data () {
return { props: props }
},
render: function (h) { return h(Component, {
props: props,
ref: 'modal',
on: {
ok: function (data) {
resolve(data);
vm.$destroy();
},
cancel: function () {
reject(new Error());
vm.$destroy();
}
}
}); },
mounted: function mounted () {
this.$refs.modal.show();
}
});
})
}
}
var actionSheet = {
__installed: false,
install: function install (ref) {
var $q = ref.$q;
var Vue$$1 = ref.Vue;
if (this.__installed) { return }
this.__installed = true;
$q.actionSheet = modalFn(QActionSheet, Vue$$1);
}
}
function getPrimaryHex () {
var tempDiv = document.createElement('div');
tempDiv.style.height = '10px';
tempDiv.style.position = 'absolute';
tempDiv.style.top = '-100000px';
tempDiv.className = 'bg-primary';
document.body.appendChild(tempDiv);
var primaryColor = window.getComputedStyle(tempDiv).getPropertyValue('background-color');
document.body.removeChild(tempDiv);
var rgb = primaryColor.match(/\d+/g);
return ("#" + (rgbToHex(parseInt(rgb[0]), parseInt(rgb[1]), parseInt(rgb[2]))))
}
function setColor (hexColor) {
// http://stackoverflow.com/a/33193739
var metaTag = document.createElement('meta');
if (Platform.is.winphone) {
metaTag.setAttribute('name', 'msapplication-navbutton-color');
}
else if (Platform.is.safari) {
metaTag.setAttribute('name', 'apple-mobile-web-app-status-bar-style');
}
// Chrome, Firefox OS, Opera, Vivaldi
else {
metaTag.setAttribute('name', 'theme-color');
}
metaTag.setAttribute('content', hexColor);
document.getElementsByTagName('head')[0].appendChild(metaTag);
}
var addressbarColor = {
set: function set (hexColor) {
if (!Platform.is.mobile || Platform.is.cordova || isSSR) {
return
}
if (!Platform.is.winphone && !Platform.is.safari && !Platform.is.webkit && !Platform.is.vivaldi) {
return
}
ready(function () {
setColor(hexColor || getPrimaryHex());
});
}
}
var appFullscreen = {
isCapable: false,
isActive: false,
__prefixes: {},
request: function request (target) {
if (this.isCapable && !this.isActive) {
target = target || document.documentElement;
target[this.__prefixes.request]();
}
},
exit: function exit () {
if (this.isCapable && this.isActive) {
document[this.__prefixes.exit]();
}
},
toggle: function toggle (target) {
if (this.isActive) {
this.exit();
}
else {
this.request(target);
}
},
__installed: false,
install: function install (ref) {
var this$1 = this;
var $q = ref.$q;
var Vue$$1 = ref.Vue;
if (this.__installed) { return }
this.__installed = true;
if (isSSR) {
$q.fullscreen = this;
return
}
var request = [
'requestFullscreen',
'msRequestFullscreen', 'mozRequestFullScreen', 'webkitRequestFullscreen'
].find(function (request) { return document.documentElement[request]; });
this.isCapable = request !== undefined;
if (!this.isCapable) {
// it means the browser does NOT support it
return
}
var exit = [
'exitFullscreen',
'msExitFullscreen', 'mozCancelFullScreen', 'webkitExitFullscreen'
].find(function (exit) { return document[exit]; });
this.__prefixes = {
request: request,
exit: exit
};
this.isActive = (document.fullscreenElement ||
document.mozFullScreenElement ||
document.webkitFullscreenElement ||
document.msFullscreenElement) !== undefined
;[
'onfullscreenchange',
'MSFullscreenChange', 'onmozfullscreenchange', 'onwebkitfullscreenchange'
].forEach(function (evt) {
document[evt] = function () {
this$1.isActive = !this$1.isActive;
};
});
Vue$$1.util.defineReactive({}, 'isActive', this);
$q.fullscreen = this;
}
}
var appVisibility = {
appVisible: false,
__installed: false,
install: function install (ref) {
var this$1 = this;
var $q = ref.$q;
var Vue$$1 = ref.Vue;
if (this.__installed) { return }
this.__installed = true;
if (isSSR) {
this.appVisible = $q.appVisible = true;
return
}
var prop, evt;
if (typeof document.hidden !== 'undefined') { // Opera 12.10 and Firefox 18 and later support
prop = 'hidden';
evt = 'visibilitychange';
}
else if (typeof document.msHidden !== 'undefined') {
prop = 'msHidden';
evt = 'msvisibilitychange';
}
else if (typeof document.webkitHidden !== 'undefined') {
prop = 'webkitHidden';
evt = 'webkitvisibilitychange';
}
var update = function () {
this$1.appVisible = $q.appVisible = !document[prop];
};
update();
if (evt && typeof document[prop] !== 'undefined') {
Vue$$1.util.defineReactive({}, 'appVisible', $q);
document.addEventListener(evt, update, false);
}
}
}
function encode (string) {
return encodeURIComponent(string)
}
function decode (string) {
return decodeURIComponent(string)
}
function stringifyCookieValue (value) {
return encode(value === Object(value) ? JSON.stringify(value) : '' + value)
}
function read (string) {
if (string === '') {
return string
}
if (string.indexOf('"') === 0) {
// This is a quoted cookie as according to RFC2068, unescape...
string = string.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}
// Replace server-side written pluses with spaces.
// If we can't decode the cookie, ignore it, it's unusable.
// If we can't parse the cookie, ignore it, it's unusable.
string = decode(string.replace(/\+/g, ' '));
try {
string = JSON.parse(string);
}
catch (e) {}
return string
}
function set (key, val, opts) {
if ( opts === void 0 ) opts = {};
var time = opts.expires;
if (typeof opts.expires === 'number') {
time = new Date();
time.setMilliseconds(time.getMilliseconds() + opts.expires * 864e+5);
}
document.cookie = [
encode(key), '=', stringifyCookieValue(val),
time ? '; expires=' + time.toUTCString() : '', // use expires attribute, max-age is not supported by IE
opts.path ? '; path=' + opts.path : '',
opts.domain ? '; domain=' + opts.domain : '',
opts.secure ? '; secure' : ''
].join('');
}
function get (key) {
var
result = key ? undefined : {},
cookies = document.cookie ? document.cookie.split('; ') : [],
i = 0,
l = cookies.length,
parts,
name,
cookie;
for (; i < l; i++) {
parts = cookies[i].split('=');
name = decode(parts.shift());
cookie = parts.join('=');
if (!key) {
result[name] = cookie;
}
else if (key === name) {
result = read(cookie);
break
}
}
return result
}
function remove (key, options) {
set(key, '', extend(true, {}, options, {
expires: -1
}));
}
function has (key) {
return get(key) !== undefined
}
var cookies = {
get: get,
set: set,
has: has,
remove: remove,
all: function () { return get(); },
__installed: false,
install: function install (ref) {
var $q = ref.$q;
if (this.__installed) { return }
this.__installed = true;
if (isSSR) {
var noop = function () {};
this.get = noop;
this.set = noop;
this.has = noop;
this.remove = noop;
this.all = noop;
}
$q.cookies = this;
}
}
var dialog = {
__installed: false,
install: function install (ref) {
var $q = ref.$q;
var Vue$$1 = ref.Vue;
if (this.__installed) { return }
this.__installed = true;
$q.dialog = isSSR
? function () { return new Promise(); }
: modalFn(QDialog, Vue$$1);
}
}
var vm;
var timeout;
var props = {};
var staticClass = 'q-loading animate-fade fullscreen column flex-center z-max';
var Loading = {
isActive: false,
show: function show (ref) {
var this$1 = this;
if ( ref === void 0 ) ref = {};
var delay = ref.delay; if ( delay === void 0 ) delay = 500;
var message = ref.message; if ( message === void 0 ) message = false;
var spinnerSize = ref.spinnerSize; if ( spinnerSize === void 0 ) spinnerSize = 80;
var spinnerColor = ref.spinnerColor; if ( spinnerColor === void 0 ) spinnerColor = 'white';
var messageColor = ref.messageColor; if ( messageColor === void 0 ) messageColor = 'white';
var spinner = ref.spinner; if ( spinner === void 0 ) spinner = QSpinner;
var customClass = ref.customClass; if ( customClass === void 0 ) customClass = false;
if (isSSR) { return }
props.spinner = spinner;
props.message = message;
props.spinnerSize = spinnerSize;
props.spinnerColor = spinnerColor;
props.messageColor = messageColor;
if (typeof customClass === 'string') {
props.customClass = customClass.trim();
}
if (this.isActive) {
vm && vm.$forceUpdate();
return
}
timeout = setTimeout(function () {
timeout = null;
var node = document.createElement('div');
document.body.appendChild(node);
document.body.classList.add('with-loading');
vm = new this$1.__Vue({
name: 'q-loading',
el: node,
render: function render (h) {
return h('div', {
staticClass: staticClass,
'class': props.customClass
}, [
h(props.spinner, {
props: {
color: props.spinnerColor,
size: props.spinnerSize
}
}),
message
? h('div', {
'class': ("text-" + (props.messageColor)),
domProps: {
innerHTML: props.message
}
})
: null
])
}
});
}, delay);
this.isActive = true;
},
hide: function hide () {
if (!this.isActive) {
return
}
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
else {
vm.$destroy();
document.body.classList.remove('with-loading');
document.body.removeChild(vm.$el);
vm = null;
}
this.isActive = false;
},
__Vue: null,
__installed: false,
install: function install (ref) {
var $q = ref.$q;
var Vue$$1 = ref.Vue;
if (this.__installed) { return }
this.__installed = true;
$q.loading = Loading;
this.__Vue = Vue$$1;
}
};
var positionList = [
'top-left', 'top-right',
'bottom-left', 'bottom-right',
'top', 'bottom', 'left', 'right', 'center'
];
function init (ref) {
var $q = ref.$q;
var Vue$$1 = ref.Vue;
var node = document.createElement('div');
document.body.appendChild(node);
this.__vm = new Vue$$1({
name: 'q-notifications',
data: {
notifs: {
center: [],
left: [],
right: [],
top: [],
'top-left': [],
'top-right': [],
bottom: [],
'bottom-left': [],
'bottom-right': []
}
},
methods: {
add: function add (config) {
var this$1 = this;
if (!config) {
console.error('Notify: parameter required');
return false
}
var notif;
if (typeof config === 'string') {
notif = {
message: config,
position: 'bottom'
};
}
else {
notif = clone(config);
}
if (notif.position) {
if (!positionList.includes(notif.position)) {
console.error(("Notify: wrong position: " + (notif.position)));
return false
}
}
else {
notif.position = 'bottom';
}
notif.__uid = uid();
if (notif.timeout === void 0) {
notif.timeout = 5000;
}
var close = function () {
this$1.remove(notif);
};
if (notif.actions) {
notif.actions = config.actions.map(function (item) {
var
handler = item.handler,
action = clone(item);
action.handler = typeof handler === 'function'
? function () {
handler();
close();
}
: function () { return close(); };
return action
});
}
if (notif.closeBtn) {
var btn = [{
closeBtn: true,
label: notif.closeBtn,
handler: close
}];
notif.actions = notif.actions
? notif.actions.concat(btn)
: btn;
}
if (notif.timeout) {
notif.__timeout = setTimeout(function () {
close();
}, notif.timeout + /* show duration */ 1000);
}
var action = notif.position.indexOf('top') > -1 ? 'unshift' : 'push';
this.notifs[notif.position][action](notif);
return close
},
remove: function remove (notif) {
if (notif.__timeout) { clearTimeout(notif.__timeout); }
var index = this.notifs[notif.position].indexOf(notif);
if (index !== -1) {
var ref = this.$refs[("notif_" + (notif.__uid))];
if (ref && ref.$el) {
var el = ref.$el;
el.style.left = (el.offsetLeft) + "px";
el.style.width = getComputedStyle(el).width;
}
this.notifs[notif.position].splice(index, 1);
if (typeof notif.onDismiss === 'function') {
notif.onDismiss();
}
}
}
},
render: function render (h) {
var this$1 = this;
return h('div', { staticClass: 'q-notifications' }, positionList.map(function (pos) {
var
vert = ['left', 'center', 'right'].includes(pos) ? 'center' : (pos.indexOf('top') > -1 ? 'top' : 'bottom'),
align = pos.indexOf('left') > -1 ? 'start' : (pos.indexOf('right') > -1 ? 'end' : 'center'),
classes = ['left', 'right'].includes(pos) ? ("items-" + (pos === 'left' ? 'start' : 'end') + " justify-center") : (pos === 'center' ? 'flex-center' : ("items-" + align));
return h('transition-group', {
key: pos,
staticClass: ("q-notification-list q-notification-list-" + vert + " fixed column " + classes),
tag: 'div',
props: {
name: ("q-notification-" + pos),
mode: 'out-in'
}
}, this$1.notifs[pos].map(function (notif) {
return h(QAlert, {
ref: ("notif_" + (notif.__uid)),
key: notif.__uid,
staticClass: 'q-notification',
props: notif
}, [ notif.message ])
}))
}))
}
});
this.__vm.$mount(node);
$q.notify = this.create.bind(this);
}
var notify = {
create: function create (opts) {
var this$1 = this;
if (isSSR) {
return
}
if (this.__vm !== void 0) {
return this.__vm.add(opts)
}
ready(function () {
setTimeout(function () {
this$1.create(opts);
});
});
},
__installed: false,
install: function install (args) {
var this$1 = this;
if (this.__installed) { return }
this.__installed = true;
if (!isSSR) {
ready(function () {
init.call(this$1, args);
});
}
}
}
function encode$1 (value) {
if (Object.prototype.toString.call(value) === '[object Date]') {
return '__q_date|' + value.toUTCString()
}
if (Object.prototype.toString.call(value) === '[object RegExp]') {
return '__q_expr|' + value.source
}
if (typeof value === 'number') {
return '__q_numb|' + value
}
if (typeof value === 'boolean') {
return '__q_bool|' + (value ? '1' : '0')
}
if (typeof value === 'string') {
return '__q_strn|' + value
}
if (typeof value === 'function') {
return '__q_strn|' + value.toString()
}
if (value === Object(value)) {
return '__q_objt|' + JSON.stringify(value)
}
// hmm, we don't know what to do with it,
// so just return it as is
return value
}
function decode$1 (value) {
var type, length, source;
length = value.length;
if (length < 9) {
// then it wasn't encoded by us
return value
}
type = value.substr(0, 8);
source = value.substring(9);
switch (type) {
case '__q_date':
return new Date(source)
case '__q_expr':
return new RegExp(source)
case '__q_numb':
return Number(source)
case '__q_bool':
return Boolean(source === '1')
case '__q_strn':
return '' + source
case '__q_objt':
return JSON.parse(source)
default:
// hmm, we reached here, we don't know the type,
// then it means it wasn't encoded by us, so just
// return whatever value it is
return value
}
}
function getEmptyStorage () {
var fn = function () { return null; };
return {
has: fn,
get: {
length: fn,
item: fn,
index: fn,
all: fn
},
set: fn,
remove: fn,
clear: fn,
isEmpty: fn
}
}
function getStorage (type) {
var
webStorage = window[type + 'Storage'],
get = function (key) {
var item = webStorage.getItem(key);
return item
? decode$1(item)
: null
};
return {
has: function (key) { return webStorage.getItem(key) !== null; },
get: {
length: function () { return webStorage.length; },
item: get,
index: function (index) {
if (index < webStorage.length) {
return get(webStorage.key(index))
}
},
all: function () {
var result = {}, key, len = webStorage.length;
for (var i = 0; i < len; i++) {
key = webStorage.key(i);
result[key] = get(key);
}
return result
}
},
set: function (key, value) { webStorage.setItem(key, encode$1(value)); },
remove: function (key) { webStorage.removeItem(key); },
clear: function () { webStorage.clear(); },
isEmpty: function () { return webStorage.length === 0; }
}
}
var LocalStorage = {
__installed: false,
install: function install (ref) {
var $q = ref.$q;
if (this.__installed) { return }
this.__installed = true;
if ($q.platform.has.webStorage) {
var storage = getStorage('local');
$q.localStorage = storage;
extend(true, this, storage);
}
else {
$q.localStorage = getEmptyStorage();
}
}
};
var SessionStorage = {
__installed: false,
install: function install (ref) {
var $q = ref.$q;
if (this.__installed) { return }
this.__installed = true;
if ($q.platform.has.webStorage) {
var storage = getStorage('session');
$q.sessionStorage = storage;
extend(true, this, storage);
}
else {
$q.sessionStorage = getEmptyStorage();
}
}
};
var plugins = Object.freeze({
ActionSheet: actionSheet,
AddressbarColor: addressbarColor,
AppFullscreen: appFullscreen,
AppVisibility: appVisibility,
Cookies: cookies,
Dialog: dialog,
Loading: Loading,
Notify: notify,
Platform: Platform,
LocalStorage: LocalStorage,
SessionStorage: SessionStorage
});
function openUrl (url, reject) {
if (Platform.is.cordova && navigator && navigator.app) {
return navigator.app.loadUrl(url, {
openExternal: true
})
}
var win = window.open(url, '_blank');
if (win) {
win.focus();
return win
}
else {
reject();
}
}
function noop () {}
var utils = Object.freeze({
animate: animate,
clone: clone,
colors: colors,
date: date,
debounce: debounce,
frameDebounce: frameDebounce,
dom: dom,
easing: easing,
event: event,
extend: extend,
filter: filter,
format: format,
noop: noop,
openURL: openUrl,
scroll: scroll,
throttle: throttle,
uid: uid
});
if (Vue === void 0) {
console.error('[ Quasar ] Vue is required to run. Please add a script tag for it before loading Quasar.');
}
else {
Vue.use({ install: install }, {
components: components,
directives: directives,
plugins: plugins
});
}
var index_umd = {
version: version,
theme: "mat",
i18n: i18n,
icons: icons,
components: components,
directives: directives,
plugins: plugins,
utils: utils
}
return index_umd;
})));
|
App/Containers/MapviewExample.js
|
tetriseffect/activate
|
// import React from 'react'
// import { connect } from 'react-redux'
// import { View } from 'react-native'
// import MapView from 'react-native-maps'
// import { calculateRegion } from '../Lib/MapHelpers'
// import MapCallout from '../Components/MapCallout'
// import Styles from './Styles/MapviewExampleStyle'
// /* ***********************************************************
// * IMPORTANT!!! Before you get started, if you are going to support Android,
// * PLEASE generate your own API key and add it to android/app/src/main/AndroidManifest.xml
// * We've included our API key for demonstration purposes only, and it will be regenerated from
// * time to time. As such, neglecting to complete this step could potentially break your app in production!
// * https://console.developers.google.com/apis/credentials
// * Also, you'll need to enable Google Maps Android API for your project:
// * https://console.developers.google.com/apis/api/maps_android_backend/
// *************************************************************/
// class MapviewExample extends React.Component {
// /* ***********************************************************
// * This example is only intended to get you started with the basics.
// * There are TONS of options available from traffic to buildings to indoors to compass and more!
// * For full documentation, see https://github.com/lelandrichardson/react-native-maps
// *************************************************************/
// constructor (props) {
// super(props)
// /* ***********************************************************
// * STEP 1
// * Set the array of locations to be displayed on your map. You'll need to define at least
// * a latitude and longitude as well as any additional information you wish to display.
// *************************************************************/
// const locations = [
// { title: 'Location A', latitude: 37.78825, longitude: -122.4324 },
// { title: 'Location B', latitude: 37.75825, longitude: -122.4624 }
// ]
// /* ***********************************************************
// * STEP 2
// * Set your initial region either by dynamically calculating from a list of locations (as below)
// * or as a fixed point, eg: { latitude: 123, longitude: 123, latitudeDelta: 0.1, longitudeDelta: 0.1}
// *************************************************************/
// const region = calculateRegion(locations, { latPadding: 0.05, longPadding: 0.05 })
// this.state = {
// region,
// locations,
// showUserLocation: true
// }
// this.renderMapMarkers = this.renderMapMarkers.bind(this)
// this.onRegionChange = this.onRegionChange.bind(this)
// }
// componentWillReceiveProps (newProps) {
// /* ***********************************************************
// * STEP 3
// * If you wish to recenter the map on new locations any time the
// * Redux props change, do something like this:
// *************************************************************/
// // this.setState({
// // region: calculateRegion(newProps.locations, { latPadding: 0.1, longPadding: 0.1 })
// // })
// }
// onRegionChange (newRegion) {
// /* ***********************************************************
// * STEP 4
// * If you wish to fetch new locations when the user changes the
// * currently visible region, do something like this:
// *************************************************************/
// // const searchRegion = {
// // ne_lat: newRegion.latitude + newRegion.latitudeDelta,
// // ne_long: newRegion.longitude + newRegion.longitudeDelta,
// // sw_lat: newRegion.latitude - newRegion.latitudeDelta,
// // sw_long: newRegion.longitude - newRegion.longitudeDelta
// // }
// // Fetch new data...
// }
// calloutPress (location) {
// /* ***********************************************************
// * STEP 5
// * Configure what will happen (if anything) when the user
// * presses your callout.
// *************************************************************/
// console.tron.log(location)
// }
// renderMapMarkers (location) {
// /* ***********************************************************
// * STEP 6
// * Customize the appearance and location of the map marker.
// * Customize the callout in ../Components/MapCallout.js
// *************************************************************/
// return (
// <MapView.Marker key={location.title} coordinate={{latitude: location.latitude, longitude: location.longitude}}>
// <MapCallout location={location} onPress={this.calloutPress} />
// </MapView.Marker>
// )
// }
// render () {
// return (
// <View style={Styles.container}>
// <MapView
// style={Styles.map}
// initialRegion={this.state.region}
// onRegionChangeComplete={this.onRegionChange}
// showsUserLocation={this.state.showUserLocation}
// >
// {this.state.locations.map((location) => this.renderMapMarkers(location))}
// </MapView>
// </View>
// )
// }
// }
// const mapStateToProps = (state) => {
// return {
// // ...redux state to props here
// }
// }
// export default connect(mapStateToProps)(MapviewExample)
|
client/modules/App/__tests__/App.spec.js
|
AlinaNor/ReactAuction
|
import React from 'react';
import test from 'ava';
import sinon from 'sinon';
import { shallow, mount } from 'enzyme';
import { App } from '../App';
import styles from '../App.css';
import { intlShape } from 'react-intl';
import { intl } from '../../../util/react-intl-test-helper';
import { toggleAddPost } from '../AppActions';
const intlProp = { ...intl, enabledLanguages: ['en', 'fr'] };
const children = <h1>Test</h1>;
const dispatch = sinon.spy();
const props = {
children,
dispatch,
intl: intlProp,
};
test('renders properly', t => {
const wrapper = shallow(
<App {...props} />
);
// t.is(wrapper.find('Helmet').length, 1);
t.is(wrapper.find('Header').length, 1);
t.is(wrapper.find('Footer').length, 1);
t.is(wrapper.find('Header').prop('toggleAddPost'), wrapper.instance().toggleAddPostSection);
t.truthy(wrapper.find('Header + div').hasClass(styles.container));
t.truthy(wrapper.find('Header + div').children(), children);
});
test('calls componentDidMount', t => {
sinon.spy(App.prototype, 'componentDidMount');
mount(
<App {...props} />,
{
context: {
router: {
isActive: sinon.stub().returns(true),
push: sinon.stub(),
replace: sinon.stub(),
go: sinon.stub(),
goBack: sinon.stub(),
goForward: sinon.stub(),
setRouteLeaveHook: sinon.stub(),
createHref: sinon.stub(),
},
intl,
},
childContextTypes: {
router: React.PropTypes.object,
intl: intlShape,
},
},
);
t.truthy(App.prototype.componentDidMount.calledOnce);
App.prototype.componentDidMount.restore();
});
test('calling toggleAddPostSection dispatches toggleAddPost', t => {
const wrapper = shallow(
<App {...props} />
);
wrapper.instance().toggleAddPostSection();
t.truthy(dispatch.calledOnce);
t.truthy(dispatch.calledWith(toggleAddPost()));
});
|
src/main.js
|
Grobim/eggheadReduxTutorial
|
import React from 'react';
import ReactDOM from 'react-dom';
import { createHistory, useBasename } from 'history';
import { syncReduxAndRouter } from 'redux-simple-router';
import routes from './routes';
import Root from './containers/Root';
import configureStore from './redux/configureStore';
const history = useBasename(createHistory)({
basename : __BASENAME__
});
const store = configureStore(window.__INITIAL_STATE__);
syncReduxAndRouter(history, store, (state) => state.router);
// Render the React application to the DOM
ReactDOM.render(
<Root history={history} routes={routes} store={store} />,
document.getElementById('root')
);
|
src/collections/Message/MessageItem.js
|
shengnian/shengnian-ui-react
|
import cx from 'classnames'
import PropTypes from 'prop-types'
import React from 'react'
import {
childrenUtils,
createShorthandFactory,
customPropTypes,
getElementType,
getUnhandledProps,
META,
} from '../../lib'
/**
* A message list can contain an item.
*/
function MessageItem(props) {
const { children, className, content } = props
const classes = cx('content', className)
const rest = getUnhandledProps(MessageItem, props)
const ElementType = getElementType(MessageItem, props)
return (
<ElementType {...rest} className={classes}>
{childrenUtils.isNil(children) ? content : children}
</ElementType>
)
}
MessageItem._meta = {
name: 'MessageItem',
parent: 'Message',
type: META.TYPES.COLLECTION,
}
MessageItem.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Shorthand for primary content. */
content: customPropTypes.contentShorthand,
}
MessageItem.defaultProps = {
as: 'li',
}
MessageItem.create = createShorthandFactory(MessageItem, content => ({ content }))
export default MessageItem
|
ajax/libs/material-ui/4.9.6/Modal/Modal.js
|
cdnjs/cdnjs
|
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.styles = void 0;
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var React = _interopRequireWildcard(require("react"));
var ReactDOM = _interopRequireWildcard(require("react-dom"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _styles = require("@material-ui/styles");
var _utils = require("@material-ui/utils");
var _ownerDocument = _interopRequireDefault(require("../utils/ownerDocument"));
var _Portal = _interopRequireDefault(require("../Portal"));
var _createChainedFunction = _interopRequireDefault(require("../utils/createChainedFunction"));
var _useForkRef = _interopRequireDefault(require("../utils/useForkRef"));
var _useEventCallback = _interopRequireDefault(require("../utils/useEventCallback"));
var _zIndex = _interopRequireDefault(require("../styles/zIndex"));
var _ModalManager = _interopRequireWildcard(require("./ModalManager"));
var _TrapFocus = _interopRequireDefault(require("./TrapFocus"));
var _SimpleBackdrop = _interopRequireDefault(require("./SimpleBackdrop"));
function getContainer(container) {
container = typeof container === 'function' ? container() : container;
return ReactDOM.findDOMNode(container);
}
function getHasTransition(props) {
return props.children ? props.children.props.hasOwnProperty('in') : false;
} // A modal manager used to track and manage the state of open Modals.
// Modals don't open on the server so this won't conflict with concurrent requests.
var defaultManager = new _ModalManager.default();
var styles = function styles(theme) {
return {
/* Styles applied to the root element. */
root: {
position: 'fixed',
zIndex: theme.zIndex.modal,
right: 0,
bottom: 0,
top: 0,
left: 0
},
/* Styles applied to the root element if the `Modal` has exited. */
hidden: {
visibility: 'hidden'
}
};
};
/**
* Modal is a lower-level construct that is leveraged by the following components:
*
* - [Dialog](/api/dialog/)
* - [Drawer](/api/drawer/)
* - [Menu](/api/menu/)
* - [Popover](/api/popover/)
*
* If you are creating a modal dialog, you probably want to use the [Dialog](/api/dialog/) component
* rather than directly using Modal.
*
* This component shares many concepts with [react-overlays](https://react-bootstrap.github.io/react-overlays/#modals).
*/
exports.styles = styles;
var Modal = React.forwardRef(function Modal(inProps, ref) {
var theme = (0, _styles.useTheme)();
var props = (0, _styles.getThemeProps)({
name: 'MuiModal',
props: (0, _extends2.default)({}, inProps),
theme: theme
});
var _props$BackdropCompon = props.BackdropComponent,
BackdropComponent = _props$BackdropCompon === void 0 ? _SimpleBackdrop.default : _props$BackdropCompon,
BackdropProps = props.BackdropProps,
children = props.children,
_props$closeAfterTran = props.closeAfterTransition,
closeAfterTransition = _props$closeAfterTran === void 0 ? false : _props$closeAfterTran,
container = props.container,
_props$disableAutoFoc = props.disableAutoFocus,
disableAutoFocus = _props$disableAutoFoc === void 0 ? false : _props$disableAutoFoc,
_props$disableBackdro = props.disableBackdropClick,
disableBackdropClick = _props$disableBackdro === void 0 ? false : _props$disableBackdro,
_props$disableEnforce = props.disableEnforceFocus,
disableEnforceFocus = _props$disableEnforce === void 0 ? false : _props$disableEnforce,
_props$disableEscapeK = props.disableEscapeKeyDown,
disableEscapeKeyDown = _props$disableEscapeK === void 0 ? false : _props$disableEscapeK,
_props$disablePortal = props.disablePortal,
disablePortal = _props$disablePortal === void 0 ? false : _props$disablePortal,
_props$disableRestore = props.disableRestoreFocus,
disableRestoreFocus = _props$disableRestore === void 0 ? false : _props$disableRestore,
_props$disableScrollL = props.disableScrollLock,
disableScrollLock = _props$disableScrollL === void 0 ? false : _props$disableScrollL,
_props$hideBackdrop = props.hideBackdrop,
hideBackdrop = _props$hideBackdrop === void 0 ? false : _props$hideBackdrop,
_props$keepMounted = props.keepMounted,
keepMounted = _props$keepMounted === void 0 ? false : _props$keepMounted,
_props$manager = props.manager,
manager = _props$manager === void 0 ? defaultManager : _props$manager,
onBackdropClick = props.onBackdropClick,
onClose = props.onClose,
onEscapeKeyDown = props.onEscapeKeyDown,
onRendered = props.onRendered,
open = props.open,
other = (0, _objectWithoutProperties2.default)(props, ["BackdropComponent", "BackdropProps", "children", "closeAfterTransition", "container", "disableAutoFocus", "disableBackdropClick", "disableEnforceFocus", "disableEscapeKeyDown", "disablePortal", "disableRestoreFocus", "disableScrollLock", "hideBackdrop", "keepMounted", "manager", "onBackdropClick", "onClose", "onEscapeKeyDown", "onRendered", "open"]);
var _React$useState = React.useState(true),
exited = _React$useState[0],
setExited = _React$useState[1];
var modal = React.useRef({});
var mountNodeRef = React.useRef(null);
var modalRef = React.useRef(null);
var handleRef = (0, _useForkRef.default)(modalRef, ref);
var hasTransition = getHasTransition(props);
var getDoc = function getDoc() {
return (0, _ownerDocument.default)(mountNodeRef.current);
};
var getModal = function getModal() {
modal.current.modalRef = modalRef.current;
modal.current.mountNode = mountNodeRef.current;
return modal.current;
};
var handleMounted = function handleMounted() {
manager.mount(getModal(), {
disableScrollLock: disableScrollLock
}); // Fix a bug on Chrome where the scroll isn't initially 0.
modalRef.current.scrollTop = 0;
};
var handleOpen = (0, _useEventCallback.default)(function () {
var resolvedContainer = getContainer(container) || getDoc().body;
manager.add(getModal(), resolvedContainer); // The element was already mounted.
if (modalRef.current) {
handleMounted();
}
});
var isTopModal = React.useCallback(function () {
return manager.isTopModal(getModal());
}, [manager]);
var handlePortalRef = (0, _useEventCallback.default)(function (node) {
mountNodeRef.current = node;
if (!node) {
return;
}
if (onRendered) {
onRendered();
}
if (open && isTopModal()) {
handleMounted();
} else {
(0, _ModalManager.ariaHidden)(modalRef.current, true);
}
});
var handleClose = React.useCallback(function () {
manager.remove(getModal());
}, [manager]);
React.useEffect(function () {
return function () {
handleClose();
};
}, [handleClose]);
React.useEffect(function () {
if (open) {
handleOpen();
} else if (!hasTransition || !closeAfterTransition) {
handleClose();
}
}, [open, handleClose, hasTransition, closeAfterTransition, handleOpen]);
if (!keepMounted && !open && (!hasTransition || exited)) {
return null;
}
var handleEnter = function handleEnter() {
setExited(false);
};
var handleExited = function handleExited() {
setExited(true);
if (closeAfterTransition) {
handleClose();
}
};
var handleBackdropClick = function handleBackdropClick(event) {
if (event.target !== event.currentTarget) {
return;
}
if (onBackdropClick) {
onBackdropClick(event);
}
if (!disableBackdropClick && onClose) {
onClose(event, 'backdropClick');
}
};
var handleKeyDown = function handleKeyDown(event) {
// The handler doesn't take event.defaultPrevented into account:
//
// event.preventDefault() is meant to stop default behaviours like
// clicking a checkbox to check it, hitting a button to submit a form,
// and hitting left arrow to move the cursor in a text input etc.
// Only special HTML elements have these default behaviors.
if (event.key !== 'Escape' || !isTopModal()) {
return;
} // Swallow the event, in case someone is listening for the escape key on the body.
event.stopPropagation();
if (onEscapeKeyDown) {
onEscapeKeyDown(event);
}
if (!disableEscapeKeyDown && onClose) {
onClose(event, 'escapeKeyDown');
}
};
var inlineStyle = styles(theme || {
zIndex: _zIndex.default
});
var childProps = {};
if (children.props.tabIndex === undefined) {
childProps.tabIndex = children.props.tabIndex || '-1';
} // It's a Transition like component
if (hasTransition) {
childProps.onEnter = (0, _createChainedFunction.default)(handleEnter, children.props.onEnter);
childProps.onExited = (0, _createChainedFunction.default)(handleExited, children.props.onExited);
}
return React.createElement(_Portal.default, {
ref: handlePortalRef,
container: container,
disablePortal: disablePortal
}, React.createElement("div", (0, _extends2.default)({
ref: handleRef,
onKeyDown: handleKeyDown,
role: "presentation"
}, other, {
style: (0, _extends2.default)({}, inlineStyle.root, {}, !open && exited ? inlineStyle.hidden : {}, {}, other.style)
}), hideBackdrop ? null : React.createElement(BackdropComponent, (0, _extends2.default)({
open: open,
onClick: handleBackdropClick
}, BackdropProps)), React.createElement(_TrapFocus.default, {
disableEnforceFocus: disableEnforceFocus,
disableAutoFocus: disableAutoFocus,
disableRestoreFocus: disableRestoreFocus,
getDoc: getDoc,
isEnabled: isTopModal,
open: open
}, React.cloneElement(children, childProps))));
});
process.env.NODE_ENV !== "production" ? Modal.propTypes = {
/**
* A backdrop component. This prop enables custom backdrop rendering.
*/
BackdropComponent: _propTypes.default.elementType,
/**
* Props applied to the [`Backdrop`](/api/backdrop/) element.
*/
BackdropProps: _propTypes.default.object,
/**
* A single child content element.
*/
children: _utils.elementAcceptingRef.isRequired,
/**
* When set to true the Modal waits until a nested Transition is completed before closing.
*/
closeAfterTransition: _propTypes.default.bool,
/**
* A node, component instance, or function that returns either.
* The `container` will have the portal children appended to it.
*/
container: _propTypes.default.oneOfType([_propTypes.default.object, _propTypes.default.func]),
/**
* If `true`, the modal will not automatically shift focus to itself when it opens, and
* replace it to the last focused element when it closes.
* This also works correctly with any modal children that have the `disableAutoFocus` prop.
*
* Generally this should never be set to `true` as it makes the modal less
* accessible to assistive technologies, like screen readers.
*/
disableAutoFocus: _propTypes.default.bool,
/**
* If `true`, clicking the backdrop will not fire any callback.
*/
disableBackdropClick: _propTypes.default.bool,
/**
* If `true`, the modal will not prevent focus from leaving the modal while open.
*
* Generally this should never be set to `true` as it makes the modal less
* accessible to assistive technologies, like screen readers.
*/
disableEnforceFocus: _propTypes.default.bool,
/**
* If `true`, hitting escape will not fire any callback.
*/
disableEscapeKeyDown: _propTypes.default.bool,
/**
* Disable the portal behavior.
* The children stay within it's parent DOM hierarchy.
*/
disablePortal: _propTypes.default.bool,
/**
* If `true`, the modal will not restore focus to previously focused element once
* modal is hidden.
*/
disableRestoreFocus: _propTypes.default.bool,
/**
* Disable the scroll lock behavior.
*/
disableScrollLock: _propTypes.default.bool,
/**
* If `true`, the backdrop is not rendered.
*/
hideBackdrop: _propTypes.default.bool,
/**
* Always keep the children in the DOM.
* This prop can be useful in SEO situation or
* when you want to maximize the responsiveness of the Modal.
*/
keepMounted: _propTypes.default.bool,
/**
* @ignore
*/
manager: _propTypes.default.object,
/**
* Callback fired when the backdrop is clicked.
*/
onBackdropClick: _propTypes.default.func,
/**
* Callback fired when the component requests to be closed.
* The `reason` parameter can optionally be used to control the response to `onClose`.
*
* @param {object} event The event source of the callback.
* @param {string} reason Can be: `"escapeKeyDown"`, `"backdropClick"`.
*/
onClose: _propTypes.default.func,
/**
* Callback fired when the escape key is pressed,
* `disableEscapeKeyDown` is false and the modal is in focus.
*/
onEscapeKeyDown: _propTypes.default.func,
/**
* Callback fired once the children has been mounted into the `container`.
* It signals that the `open={true}` prop took effect.
*
* This prop will be deprecated and removed in v5, the ref can be used instead.
*/
onRendered: _propTypes.default.func,
/**
* If `true`, the modal is open.
*/
open: _propTypes.default.bool.isRequired
} : void 0;
var _default = Modal;
exports.default = _default;
|
Team4of5/src/Team4of5_App/ProjectManagement/ProjectSummary.js
|
Team4Of5/Project
|
import React from 'react';
import ReactDOM from 'react-dom';
import * as ChatProj from '../../Team4of5_Service/ChatProject.js';
import * as Users from '../../Team4of5_Service/Users.js';
import CreateProject from '../Chat/CreateProject';
import ChartistGraph from 'react-chartist';
import './chartist.css';
import './chart.css';
import {
BrowserRouter as Router,
Route,
Link,
Redirect,
Switch,
withRouter
} from 'react-router-dom';
class ProjectSummary extends React.Component {
constructor(props) {
super(props);
this.state = {
projdata: [],
thisUser: '',
projectList: []
};
this.getData = this.getData.bind(this);
}
componentDidMount() {
let self = this;
this.state.thisUser = Users.getCurrentUser().uid;
ChatProj.getProjects().then(function (data) {
self.getData(data);
},
function (err) {
//Error occur
console.log("Promise Error");
console.log(err);
}
);
}
getData(data) {
const projdata = data.val();
var projArray = []
const keys = Object.keys(projdata);
var listProjArray = []
projArray.push({ name: 'Project Name', id: '0' })
for (var i = 0; i < keys.length; i++) {
var members = []
var projname = ''
var user_in_proj = false
const k = keys[i];
projname = projdata[k].name
for (var x = 0; x < projdata[k].members.length; x++) {
if (projdata[k].members[x] == this.state.thisUser) {
user_in_proj = true
}
}
if (user_in_proj == true) {
projArray.push({ name: projname, id: k });
projdata[k].key = k;
listProjArray.push(projdata[k]);
}
}
this.setState({ projdata: projArray });
this.setState({ projectList: listProjArray });
console.log("outside");
console.log(this.state.projectList);
//this.displayedCards(this.state.projectList[0])
}
render() {
function data(item) {
var labels = ['Backlog', 'Next', 'In Progress', 'Staged', 'QA', 'Live'];
var series = [];
if (item.data != undefined) {
for (var i = 0; i < item.data.lanes.length; i++) {
if (item.data.lanes[i] != undefined) {
if (item.data.lanes[i].cards != undefined) {
series.push(item.data.lanes[i].cards.length);
}
else {
series.push(0);
}
}
}
}
//var series = [item.data.lanes[0].cards.length, item.data.lanes[1].cards.length, item.data.lanes[2].cards.length, item.data.lanes[3].cards.length, item.data.lanes[4].cards.length, item.data.lanes[5].cards.length];
var data = {};
data.labels = labels;
data.series = series;
return data;
};
var type = 'Pie';
var style = {
height: 300,
width: 300
}
return (
<div>
<ul className="projectList">
{this.state.projectList.map(item => <li className="projects" onClick={() => { /*this.displayedCards(item);*/ console.log(item); console.log("MY ITEMS") }}>
<Link to={{
pathname: '/menu/ProjectManagement',
state: { startingProject: item }
}}>
{item.name}
{console.log("info")}
{console.log(item)}
</Link>
</li>)}
</ul>
<div className="mydummyname">
{this.state.projectList.map(item => <div className="chartImage panel panel-primary" >
<div className="panel-heading clearfix">
<h1 className='panel-title pull-left'>
{item.name}
</h1>
</div>
<div className='panel-body'>
<ChartistGraph
data={data(item)}
type={'Pie'}
style={style}
/>
</div>
</div>)}
</div>
<div className="createProjectContainer">
<CreateProject />
</div>
</div>
);
}
}
export default ProjectSummary;
|
example/with-mock-auth/src/routes.js
|
iansinnott/react-static-webpack-plugin
|
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import { App, Home, About, NotFound } from './App.js';
import {
Products,
Product,
ProductColors,
ProductColor,
} from './Products.js';
const loggedIn = () => {
/**
* TODO: Implement your auth logic to determine if a user is logged in
* already...
*
* You can also check out the Auth0 example for a more complete
* implementation.
*/
return false;
};
const requireAuth = (nextState, replace) => {
if (!loggedIn()) {
replace({ pathname: '/login' });
}
};
export const routes = (
<Route path='/' title='App' component={App}>
<IndexRoute component={Home} />
<Route path='products' title='App - Products' component={Products}>
<Route path='first' title='App - Products - First' component={Product} />
<Route path='second' title='App - Products - Second' component={Product} />
{/* All routes here require auth */}
<Route
path='third'
title='App - Products - Third'
onEnter={requireAuth}
component={Product}>
<Route path='colors' title='App - Products - Third - Colors' component={ProductColors}>
<Route path='green' title='App - Products - Third - Colors - Green' component={ProductColor} />
<Route path='blue' title='App - Products - Third - Colors - Blue' component={ProductColor} />
</Route>
</Route>
</Route>
<Route path='about' title='App - About' component={About} />
<Route path='*' title='404: Not Found' component={NotFound} />
</Route>
);
export default routes;
|
index.android.js
|
jefflanzi/rn-app-template
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class appTemplate extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Double tap R on your keyboard to reload,{'\n'}
Shake or press menu button for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('appTemplate', () => appTemplate);
|
packages/material-ui-icons/src/BluetoothAudio.js
|
AndriusBil/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let BluetoothAudio = props =>
<SvgIcon {...props}>
<path d="M14.24 12.01l2.32 2.32c.28-.72.44-1.51.44-2.33 0-.82-.16-1.59-.43-2.31l-2.33 2.32zm5.29-5.3l-1.26 1.26c.63 1.21.98 2.57.98 4.02s-.36 2.82-.98 4.02l1.2 1.2c.97-1.54 1.54-3.36 1.54-5.31-.01-1.89-.55-3.67-1.48-5.19zm-3.82 1L10 2H9v7.59L4.41 5 3 6.41 8.59 12 3 17.59 4.41 19 9 14.41V22h1l5.71-5.71-4.3-4.29 4.3-4.29zM11 5.83l1.88 1.88L11 9.59V5.83zm1.88 10.46L11 18.17v-3.76l1.88 1.88z" />
</SvgIcon>;
BluetoothAudio = pure(BluetoothAudio);
BluetoothAudio.muiName = 'SvgIcon';
export default BluetoothAudio;
|
app/javascript/mastodon/components/loading_indicator.js
|
h3zjp/mastodon
|
import React from 'react';
import { FormattedMessage } from 'react-intl';
const LoadingIndicator = () => (
<div className='loading-indicator'>
<div className='loading-indicator__figure' />
<FormattedMessage id='loading_indicator.label' defaultMessage='Loading...' />
</div>
);
export default LoadingIndicator;
|
src/components/layout/AppLayout.js
|
GustavoKatel/franz
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { observer, PropTypes as MobxPropTypes } from 'mobx-react';
import { defineMessages, intlShape } from 'react-intl';
import { TitleBar } from 'electron-react-titlebar';
import InfoBar from '../ui/InfoBar';
import { Component as DelayApp } from '../../features/delayApp';
import { Component as BasicAuth } from '../../features/basicAuth';
import ErrorBoundary from '../util/ErrorBoundary';
// import globalMessages from '../../i18n/globalMessages';
import { isWindows } from '../../environment';
function createMarkup(HTMLString) {
return { __html: HTMLString };
}
const messages = defineMessages({
servicesUpdated: {
id: 'infobar.servicesUpdated',
defaultMessage: '!!!Your services have been updated.',
},
updateAvailable: {
id: 'infobar.updateAvailable',
defaultMessage: '!!!A new update for Franz is available.',
},
buttonReloadServices: {
id: 'infobar.buttonReloadServices',
defaultMessage: '!!!Reload services',
},
changelog: {
id: 'infobar.buttonChangelog',
defaultMessage: '!!!Changelog',
},
buttonInstallUpdate: {
id: 'infobar.buttonInstallUpdate',
defaultMessage: '!!!Restart & install update',
},
requiredRequestsFailed: {
id: 'infobar.requiredRequestsFailed',
defaultMessage: '!!!Could not load services and user information',
},
});
export default @observer class AppLayout extends Component {
static propTypes = {
isFullScreen: PropTypes.bool.isRequired,
sidebar: PropTypes.element.isRequired,
services: PropTypes.element.isRequired,
children: PropTypes.element,
news: MobxPropTypes.arrayOrObservableArray.isRequired,
// isOnline: PropTypes.bool.isRequired,
showServicesUpdatedInfoBar: PropTypes.bool.isRequired,
appUpdateIsDownloaded: PropTypes.bool.isRequired,
removeNewsItem: PropTypes.func.isRequired,
reloadServicesAfterUpdate: PropTypes.func.isRequired,
installAppUpdate: PropTypes.func.isRequired,
showRequiredRequestsError: PropTypes.bool.isRequired,
areRequiredRequestsSuccessful: PropTypes.bool.isRequired,
retryRequiredRequests: PropTypes.func.isRequired,
areRequiredRequestsLoading: PropTypes.bool.isRequired,
darkMode: PropTypes.bool.isRequired,
isDelayAppScreenVisible: PropTypes.bool.isRequired,
};
static defaultProps = {
children: [],
};
static contextTypes = {
intl: intlShape,
};
render() {
const {
isFullScreen,
sidebar,
services,
children,
// isOnline,
news,
showServicesUpdatedInfoBar,
appUpdateIsDownloaded,
removeNewsItem,
reloadServicesAfterUpdate,
installAppUpdate,
showRequiredRequestsError,
areRequiredRequestsSuccessful,
retryRequiredRequests,
areRequiredRequestsLoading,
darkMode,
isDelayAppScreenVisible,
} = this.props;
const { intl } = this.context;
return (
<ErrorBoundary>
<div className={(darkMode ? 'theme__dark' : '')}>
<div className="app">
{isWindows && !isFullScreen && <TitleBar menu={window.franz.menu.template} icon="assets/images/logo.svg" />}
<div className="app__content">
{sidebar}
<div className="app__service">
{news.length > 0 && news.map(item => (
<InfoBar
key={item.id}
position="top"
type={item.type}
sticky={item.sticky}
onHide={() => removeNewsItem({ newsId: item.id })}
>
<span dangerouslySetInnerHTML={createMarkup(item.message)} />
</InfoBar>
))}
{/* {!isOnline && (
<InfoBar
type="danger"
sticky
>
<span className="mdi mdi-flash" />
{intl.formatMessage(globalMessages.notConnectedToTheInternet)}
</InfoBar>
)} */}
{!areRequiredRequestsSuccessful && showRequiredRequestsError && (
<InfoBar
type="danger"
ctaLabel="Try again"
ctaLoading={areRequiredRequestsLoading}
sticky
onClick={retryRequiredRequests}
>
<span className="mdi mdi-flash" />
{intl.formatMessage(messages.requiredRequestsFailed)}
</InfoBar>
)}
{showServicesUpdatedInfoBar && (
<InfoBar
type="primary"
ctaLabel={intl.formatMessage(messages.buttonReloadServices)}
onClick={reloadServicesAfterUpdate}
sticky
>
<span className="mdi mdi-power-plug" />
{intl.formatMessage(messages.servicesUpdated)}
</InfoBar>
)}
{appUpdateIsDownloaded && (
<InfoBar
type="primary"
ctaLabel={intl.formatMessage(messages.buttonInstallUpdate)}
onClick={installAppUpdate}
sticky
>
<span className="mdi mdi-information" />
{intl.formatMessage(messages.updateAvailable)}
{' '}
<a href="https://meetfranz.com/changelog" target="_blank">
<u>{intl.formatMessage(messages.changelog)}</u>
</a>
</InfoBar>
)}
{isDelayAppScreenVisible && (<DelayApp />)}
<BasicAuth />
{services}
</div>
</div>
</div>
{children}
</div>
</ErrorBoundary>
);
}
}
|
src/Portal.js
|
adampickeral/react-bootstrap
|
import deprecationWarning from './utils/deprecationWarning';
import Portal from 'react-overlays/lib/Portal';
export default deprecationWarning.wrapper(Portal, {
message:
'The Portal component is deprecated in react-bootstrap. It has been moved to a more generic library: react-overlays. ' +
'You can read more at: ' +
'http://react-bootstrap.github.io/react-overlays/examples/#portal and ' +
'https://github.com/react-bootstrap/react-bootstrap/issues/1084'
});
|
src/IconButton/IconButton.spec.js
|
manchesergit/material-ui
|
/* eslint-env mocha */
import React from 'react';
import PropTypes from 'prop-types';
import {mount, shallow} from 'enzyme';
import {assert} from 'chai';
import IconButton from './IconButton';
import FontIcon from '../FontIcon';
import getMuiTheme from '../styles/getMuiTheme';
import TouchRipple from '../internal/TouchRipple';
import mute from 'mute';
const dummy = <div />;
describe('<IconButton />', () => {
const muiTheme = getMuiTheme();
const shallowWithContext = (node) => shallow(node, {context: {muiTheme}});
const mountWithContext = (node) => mount(node, {
context: {muiTheme},
childContextTypes: {muiTheme: PropTypes.object},
});
it('renders an enhanced button', () => {
const wrapper = shallowWithContext(
<IconButton>Button</IconButton>
);
assert.strictEqual(wrapper.is('EnhancedButton'), true);
});
it('renders children', () => {
const wrapper = shallowWithContext(
<IconButton>{dummy}</IconButton>
);
assert.strictEqual(wrapper.containsMatchingElement(dummy), true, 'should contain the children');
});
it('should render children with custom color', () => {
const wrapper = shallowWithContext(
<IconButton>
<FontIcon className="material-icons" color="red">home</FontIcon>
</IconButton>
);
assert.strictEqual(wrapper.find(FontIcon).length, 1, 'should contain the FontIcon child');
assert.strictEqual(wrapper.find(FontIcon).props().color, 'red', 'FontIcon should have color set to red');
assert.strictEqual(
wrapper.find(FontIcon).props().style.color,
undefined,
'FontIcon style object has no color property'
);
});
describe('prop: hoveredStyle', () => {
it('should apply the style when hovered', () => {
const hoveredStyle = {
backgroundColor: 'blue',
};
const wrapper = shallowWithContext(
<IconButton hoveredStyle={hoveredStyle} />
);
wrapper.simulate('mouseEnter');
assert.include(wrapper.props().style, hoveredStyle);
});
it('should override the style prop', () => {
const buttonStyle = {
backgroundColor: 'blue',
};
const hoveredStyle = {
backgroundColor: 'green',
};
const wrapper = shallowWithContext(
<IconButton style={buttonStyle} hoveredStyle={hoveredStyle} />
);
wrapper.simulate('mouseEnter');
assert.include(wrapper.props().style, hoveredStyle);
});
});
describe('prop: disabled', () => {
it('should disable the ripple effect', () => {
const wrapper = mountWithContext(
<IconButton disabled={true} />
);
assert.strictEqual(wrapper.find(TouchRipple).length, 0, 'should not contain a TouchRipple descendent');
});
it('should not disable the ripple effect if false', () => {
const wrapper = mountWithContext(
<IconButton disabled={false} />
);
assert.strictEqual(wrapper.find(TouchRipple).length, 1, 'should contain a TouchRipple descendent');
});
});
describe('a11y warning checks', () => {
it('throws an error if no for attribute on input', () => {
const inputId = 'test-input-htmlFor';
const buttonId = 'test-button-htmlFor';
const unmute = mute(); // turn off the stdout and stderr so the warning isn't shown on the console output
assert.throws(() => mountWithContext(
<IconButton label="test-button" id={buttonId}>
<input type="text" id={inputId} />
</IconButton>
), Error);
unmute(); // stdout and error back on again
});
it('throws error for no aria-labelledby', () => {
const inputId = 'test-input-labbelledby';
const buttonId = 'test-button-labbelledby';
const unmute = mute(); // turn off the stdout and stderr so the warning isn't shown on the console output
assert.throws(() => mountWithContext(
<IconButton label="test-button" id={buttonId} htmlFor={inputId}>
<input type="text" id={inputId} />
</IconButton>
), Error);
unmute(); // stdout and error back on again
});
it('throws error for no aria-describedby', () => {
const inputId = 'test-input-describedby';
const buttonId = 'test-button-describedby';
const unmute = mute(); // turn off the stdout and stderr so the warning isn't shown on the console output
assert.throws(() => mountWithContext(
<IconButton label="test-button" id={buttonId} htmlFor={inputId}>
<input type="text" id={inputId} aria-labelledby={buttonId} />
</IconButton>
), Error);
unmute(); // stdout and error back on again
});
it('No a11y check errors', () => {
const inputId = 'test-input-noError';
const buttonId = 'test-button-noError';
const wrapper = mountWithContext(
<IconButton label="test-button" id={buttonId} htmlFor={inputId}>
<input
type="text"
id={inputId}
aria-labelledby={buttonId}
aria-describedby={buttonId}
/>
</IconButton>
);
assert.ok(wrapper.find(buttonId));
});
});
describe('ID handeling and generation', () => {
it('should use the supplied id without overriding', () => {
const id = '12345';
const wrapper = shallowWithContext(
<IconButton id={id} label="idPassthough" />
);
assert.strictEqual(wrapper.prop('id'), id, 'should use provided id');
});
it('should generate an id if one not supplied', () => {
const classname = 'abcde';
const wrapper = shallowWithContext(
<IconButton name={classname} label="idGeneration" />
);
assert.ok(wrapper.prop('id'), 'should generate an id if not supplied');
});
});
});
|
test/js/release_test/GroupTestBasicEvents.js
|
viromedia/viro
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import {
ViroAnimatedComponent,
ViroScene,
ViroBox,
ViroMaterials,
ViroNode,
ViroImage,
ViroVideo,
ViroFlexView,
ViroUtils,
ViroText,
ViroQuad,
ViroSkyBox,
ViroSphere,
Viro3DObject,
ViroButton,
ViroSpinner,
ViroOmniLight,
ViroAnimations,
ViroDirectionalLight,
ViroController,
} from 'react-viro';
let polarToCartesian = ViroUtils.polarToCartesian;
var LocalButtonImage = require("./res/icon_live.jpg");
var ReleaseMenu = require("./ReleaseMenu.js");
var createReactClass = require('create-react-class');
var GroupTestBasicEvents = createReactClass({
getInitialState() {
return {
reticleVisibility:true,
transformFlag: 1,
transformBehaviors:["billboard"],
showImage:true
};
},
onHover(objectTag) {
return (isHovering, source) => {
console.log("GroupTest: " + objectTag + " isHovering" + isHovering+ " onHover: " + source);
}
},
onClick(objectTag) {
return (source) => {
console.log("GroupTest: " + objectTag + " onClick source:" + source);
}
},
onClickState(objectTag) {
return (state, source) => {
console.log("GroupTest: " + objectTag + " source " + source+ " onClickState: " + state);
}
},
onTouch(objectTag){
return (touchState, touchPos, source) => {
console.log("GroupTest:" + objectTag + " onTouch touchState " + touchState + ", touchpos: " + touchPos[0] +"," + touchPos[1] + " source: " + source);
}
},
onScroll(objectTag){
return (scrollPos, source) => {
console.log("GroupTest:" + objectTag + " onScroll scrollPos " + scrollPos[0] + "," + scrollPos[1] + " source:" + source);
}
},
onSwipe(objectTag){
return (swipeState, source) => {
console.log("GroupTest:" + objectTag + " onSwipe swipeState" + swipeState + " source: " + source);
}
},
onDrag(objectTag){
return (dragtoPos, source) => {
console.log("GroupTest:" + objectTag + " onDrag dragtoPos" +
dragtoPos[0] +","+ dragtoPos[1]+","+ dragtoPos[2] + " source: " + source);
}
},
onFuse(objectTag){
return (source) => {
console.log("GroupTest:" + objectTag + " onFuse");
}
},
_getImage() {
if (this.state.showImage) {
return (
<ViroImage position={[0.0, 2, -3.5]}
transformBehaviors={["billboard"]}
source={{uri: "https://images.sftcdn.net/images/t_optimized,f_auto/p/50d2f4ce-96d1-11e6-8a53-00163ed833e7/3980672443/google-earth-screenshot.jpg"}}
onFuse={()=>{this.setState({showImage : false})}} />
);
} else {
return;
}
},
toggleReticle(){
this.setState({reticleVisibility:!this.state.reticleVisibility});
},
render: function() {
return (
<ViroScene onHover={this.onHover("ViroScene")}
onClick={this.onClick("ViroScene")}
onClickState={this.onClickState("ViroScene")}
onTouch={this.onTouch("ViroScene")}
onScroll={this.onScroll("ViroScene")}
onFuse={this.onFuse("ViroScene")}
onSwipe={this.onSwipe("ViroScene")}>
<ViroController
onClick={this.onClick("ViroController")}
onClickState={this.onClickState("ViroController")}
onTouch={this.onTouch("ViroController")}
onScroll={this.onScroll("ViroController")}
onFuse={this.onFuse("ViroController")}
onSwipe={this.onSwipe("ViroController")}
reticleVisibility={this.state.reticleVisibility} />
<ViroImage source={require('./res/poi_dot.png')} position={[-1, 0, 0]} transformBehaviors={["billboard"]} onClick={this._showNext} />
<ReleaseMenu sceneNavigator={this.props.sceneNavigator}/>
{this._getImage()}
<ViroOmniLight position={[0, 0, 0]}
color={"#FFFFFF"}
attenuationStartDistance={30}
attenuationEndDistance={40}/>
<ViroNode position={[0.8, 0, -3.5]}>
<Viro3DObject source={require('../res/heart.obj')}
scale={[1.8, 1.8, 1.8]}
position={[-3.2, 2.5, -4.5]}
materials={["heart"]}
type="OBJ"
onHover={this.onHover("3dObject")}
onClick={this.onClick("3dObject")}
onFuse={{callback:this.onFuse("3dObject"), timeToFuse:1000}}
onClickState={this.onClickState("3dObject")}
onTouch={this.onTouch("3dObject")}
onScroll={this.onScroll("3dObject")}
onSwipe={this.onSwipe("3dObject")}/>
<ViroBox
position={[-1, 1, 0]}
scale={[0.4 , 0.4 , 0.4]}
materials={["redColor","blue","redColor","blue","redColor","blue"]}
height={1}
width={1}
length={1}
onHover={this.onHover("ViroBox")}
onClick={this.onClick("ViroBox")}
onFuse={{callback:this.onFuse("ViroBox"), timeToFuse:1000}}
onClickState={this.onClickState("ViroBox")}
onTouch={this.onTouch("ViroBox")}
onScroll={this.onScroll("ViroBox")}
onSwipe={this.onSwipe("ViroBox")}/>
<ViroButton
position={[0, 1, 0]}
scale={[0.08, 0.08, 0.1]}
source={LocalButtonImage}
hoverSource={LocalButtonImage}
clickSource={LocalButtonImage}
onHover={this.onHover("ViroButton")}
onClick={this.onClick("ViroButton")}
onFuse={this.onFuse("ViroButton")}
onClickState={this.onClickState("ViroButton")}
onTouch={this.onTouch("ViroButton")}
onScroll={this.onScroll("ViroButton")}
onSwipe={this.onSwipe("ViroButton")}/>
<ViroFlexView
position={[1, 1, 0]}
scale={[0.2, 0.2, 0.1]}
materials={["redColor"]}
width={3}
height={2}
onHover={this.onHover("ViroFlexView")}
onClick={this.onClick("ViroFlexView")}
onFuse={this.onFuse("ViroFlexView")}
onClickState={this.onClickState("ViroFlexView")}
onTouch={this.onTouch("ViroFlexView")}
onScroll={this.onScroll("ViroFlexView")}
onSwipe={this.onSwipe("ViroFlexView")}/>
<ViroImage
width={1} height={1}
format="RGBA8" mipmap={true}
position={[-2, 0, 0]}
scale={[0.5, 0.5, 0.1]}
source={{uri: "https://upload.wikimedia.org/wikipedia/commons/7/74/Earth_poster_large.jpg"}}
onHover={this.onHover("ViroImage")}
onClick={this.onClick("ViroImage")}
onClickState={this.onClickState("ViroImage")}
onFuse={{callback:this.onFuse("ViroImage"), timeToFuse:1000}}
onTouch={this.onTouch("ViroImage")}
onScroll={this.onScroll("ViroImage")}
onSwipe={this.onSwipe("ViroImage")}/>
<ViroNode
position={[-1, 0, 0]}
scale={[0.5, 0.5, 0.1]}
rotation={[0,0,0]}
onHover={this.onHover("ViroNode")}
onClick={this.onClick("ViroNode")}
onFuse={{callback:this.onFuse("ViroImage"), timeToFuse:1000}}
onClickState={this.onClickState("ViroNode")}
onTouch={this.onTouch("ViroNode")}
onScroll={this.onScroll("ViroNode")}
onSwipe={this.onSwipe("ViroNode")}>
<ViroText
style={styles.baseTextTwo}
text="This is a text in a ViroNode"/>
</ViroNode>
<ViroSphere
position={[0, 0, 0]}
scale={[0.3, 0.3, 0.3]}
widthSegmentCount={5}
heightSegmentCount={5}
radius={1}
materials={["redColor"]}
onHover={this.onHover("ViroSphere")}
onFuse={this.onFuse("ViroSphere")}
onClick={this.onClick("ViroSphere")}
onClickState={this.onClickState("ViroSphere")}
onTouch={this.onTouch("ViroSphere")}
onScroll={this.onScroll("ViroSphere")}
onSwipe={this.onSwipe("ViroSphere")}
/>
<ViroSpinner
position={[1, 0, 0]}
scale={[0.3, 0.3, 0.1]}
onHover={this.onHover("ViroSpinner")}
onClick={this.onClick("ViroSpinner")}
onClickState={this.onClickState("ViroSpinner")}
onTouch={this.onTouch("ViroSpinner")}
onFuse={this.onFuse("ViroSpinner")}
onScroll={this.onScroll("ViroSpinner")}
onSwipe={this.onSwipe("ViroSpinner")}/>
<ViroQuad
position={[-2, -1, 0]}
scale={[0.5, 0.5, 0.1]}
materials={["redColor"]}
width={1}
height={1}
onHover={this.onHover("ViroQuad")}
onClick={this.onClick("ViroQuad")}
onFuse={{callback:this.onFuse("ViroQuad"), timeToFuse:1000}}
onClickState={this.onClickState("ViroQuad")}
onTouch={this.onTouch("ViroQuad")}
onScroll={this.onScroll("ViroQuad")}
onSwipe={this.onSwipe("ViroQuad")}/>
<ViroText
position={[-1, -1, 0]}
scale={[0.5 , 0.5, 0.1]}
style={styles.baseTextTwo}
text="This is a Viro Text"
onHover={this.onHover("ViroText")}
onFuse={this.onFuse("ViroText")}
onClick={this.onClick("ViroText")}
onClickState={this.onClickState("ViroText")}
onTouch={this.onTouch("ViroText")}
onScroll={this.onScroll("ViroText")}
onSwipe={this.onSwipe("ViroText")}/>
<ViroVideo
position={[0 , -1,0]}
scale={[0.1, 0.1, 0.1]}
height={4} width={4}
onHover={this.onHover("ViroVideo")}
onFuse={this.onFuse("ViroVideo")}
onClick={this.onClick("ViroVideo")}
onClickState={this.onClickState("ViroVideo")}
onTouch={this.onTouch("ViroVideo")}
onScroll={this.onScroll("ViroVideo")}
onSwipe={this.onSwipe("ViroVideo")}
source={{"uri":"https://s3-us-west-2.amazonaws.com/viro/Climber1Top.mp4"}} />
<ViroText
position={[0, -2, 0]}
scale={[0.5 , 0.5, 0.1]}
style={styles.baseTextTwo}
text="Toggle Reticle Visibility"
onClick={this.toggleReticle}/>
</ViroNode>
</ViroScene>
);
},
_showNext() {
this.props.sceneNavigator.replace({scene:require('./GroupTestDragEvents')});
},
_toggleTransform() {
var newtransformflag = this.state.transformFlag + 1;
if (newtransformflag > 5) {
newtransformflag = 0;
}
this.setState({
transformFlag:newtransformflag
});
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
elementText: {
fontFamily: 'HelveticaNeue-Medium',
fontSize: 30,
color: '#ffffff',
textAlign: 'center',
},
baseTextTwo: {
fontFamily: 'Arial',
fontSize: 20,
color: '#ffffff',
flex: 1,
textAlignVertical: 'center',
textAlign: 'center',
},
});
ViroMaterials.createMaterials({
redColor: {
fresnelExponent: .5,
shininess: 2.0,
diffuseColor: "#ff0000"
},
blue: {
shininess: 2.0,
lightingModel: "Lambert",
diffuseColor: "#0000ff"
},
heart: {
lightingModel: "Constant",
diffuseTexture: require('../res/heart_d.jpg'),
},
});
module.exports = GroupTestBasicEvents;
|
src/plugins/epl-dashboard/components/SystemInfo.js
|
erlanglab/erlangpl-ui
|
// @flow
import React from 'react';
import { connect } from 'react-redux';
import { Row, Col, ListGroup, ListGroupItem } from 'react-bootstrap';
import './SystemInfo.css';
const SystemInfo = ({ info }) => {
const systemInfo = [
['OTP release', info.otpRelease],
['ERTS version', info.version],
['node PID', info.nodePid],
['schedulers', info.schedulers],
['build type', info.buildType],
['wordsize', info.wordsize]
];
const ertsSettings = [
['kernel poll', info.kernelPoll ? 'true' : 'false'],
['SMP support', info.smpSupport ? 'true' : 'false'],
[
'full sweep',
info.garbageCollection ? info.garbageCollection.fullsweepAfter : undefined
],
['process limit', info.processLimit],
['thread', info.threads ? 'true' : 'false'],
['async threads', info.threadPoolSize],
['port limit', info.portLimit]
];
return (
<Row>
<Col xs={4}>
<h5 className="SystemInfo-list-header">System info</h5>
<ListGroup className="SystemInfo-list">
{systemInfo.map(([name, value], i) => (
<ListGroupItem key={i}>
<span>{name}</span>
<span className="value">{value || 'N/A'}</span>
</ListGroupItem>
))}
</ListGroup>
</Col>
<Col xs={4}>
<h5 className="SystemInfo-list-header">ERTS settings</h5>
<ListGroup className="SystemInfo-list">
{ertsSettings.map(([name, value], i) => (
<ListGroupItem key={i}>
<span>{name}</span>
<span className="value">{value || 'N/A'}</span>
</ListGroupItem>
))}
</ListGroup>
</Col>
</Row>
);
};
export default connect(
state => {
return { info: state.eplDashboard.systemInfo };
},
{}
)(SystemInfo);
|
app/javascript/mastodon/features/favourited_statuses/index.js
|
honpya/taketodon
|
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { fetchFavouritedStatuses, expandFavouritedStatuses } from '../../actions/favourites';
import Column from '../ui/components/column';
import ColumnHeader from '../../components/column_header';
import { addColumn, removeColumn, moveColumn } from '../../actions/columns';
import StatusList from '../../components/status_list';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { debounce } from 'lodash';
const messages = defineMessages({
heading: { id: 'column.favourites', defaultMessage: 'Favourites' },
});
const mapStateToProps = state => ({
statusIds: state.getIn(['status_lists', 'favourites', 'items']),
isLoading: state.getIn(['status_lists', 'favourites', 'isLoading'], true),
hasMore: !!state.getIn(['status_lists', 'favourites', 'next']),
});
@connect(mapStateToProps)
@injectIntl
export default class Favourites extends ImmutablePureComponent {
static propTypes = {
dispatch: PropTypes.func.isRequired,
statusIds: ImmutablePropTypes.list.isRequired,
intl: PropTypes.object.isRequired,
columnId: PropTypes.string,
multiColumn: PropTypes.bool,
hasMore: PropTypes.bool,
isLoading: PropTypes.bool,
};
componentWillMount () {
this.props.dispatch(fetchFavouritedStatuses());
}
handlePin = () => {
const { columnId, dispatch } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn('FAVOURITES', {}));
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
setRef = c => {
this.column = c;
}
handleLoadMore = debounce(() => {
this.props.dispatch(expandFavouritedStatuses());
}, 300, { leading: true })
render () {
const { intl, statusIds, columnId, multiColumn, hasMore, isLoading } = this.props;
const pinned = !!columnId;
return (
<Column ref={this.setRef}>
<ColumnHeader
icon='star'
title={intl.formatMessage(messages.heading)}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
showBackButton
/>
<StatusList
trackScroll={!pinned}
statusIds={statusIds}
scrollKey={`favourited_statuses-${columnId}`}
hasMore={hasMore}
isLoading={isLoading}
onLoadMore={this.handleLoadMore}
/>
</Column>
);
}
}
|
test/helpers/shallowRenderHelper.js
|
Yangqin0607/gallery
|
/**
* Function to get the shallow output for a given component
* As we are using phantom.js, we also need to include the fn.proto.bind shim!
*
* @see http://simonsmith.io/unit-testing-react-components-without-a-dom/
* @author somonsmith
*/
import React from 'react';
import TestUtils from 'react-addons-test-utils';
/**
* Get the shallow rendered component
*
* @param {Object} component The component to return the output for
* @param {Object} props [optional] The components properties
* @param {Mixed} ...children [optional] List of children
* @return {Object} Shallow rendered output
*/
export default function createComponent(component, props = {}, ...children) {
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0]));
return shallowRenderer.getRenderOutput();
}
|
docs/src/app/components/pages/components/Snackbar/ExampleAction.js
|
manchesergit/material-ui
|
import React from 'react';
import Snackbar from 'material-ui/Snackbar';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
export default class SnackbarExampleSimple extends React.Component {
constructor(props) {
super(props);
this.state = {
autoHideDuration: 4000,
message: 'Event added to your calendar',
open: false,
};
}
handleClick = () => {
this.setState({
open: true,
});
};
handleActionClick = () => {
this.setState({
open: false,
});
alert('Event removed from your calendar.');
};
handleChangeDuration = (event) => {
const value = event.target.value;
this.setState({
autoHideDuration: value.length > 0 ? parseInt(value) : 0,
});
};
handleRequestClose = () => {
this.setState({
open: false,
});
};
render() {
return (
<div>
<RaisedButton
onClick={this.handleClick}
label="Add to my calendar"
/>
<br />
<TextField
floatingLabelText="Auto Hide Duration in ms"
value={this.state.autoHideDuration}
onChange={this.handleChangeDuration}
/>
<Snackbar
open={this.state.open}
message={this.state.message}
action="undo"
autoHideDuration={this.state.autoHideDuration}
onActionClick={this.handleActionClick}
onRequestClose={this.handleRequestClose}
/>
</div>
);
}
}
|
src/components/Button/Base/__tests__/Button.spec.js
|
propertybase/react-lds
|
import React from 'react';
import { shallow } from 'enzyme';
import Button from '../Button';
import ButtonIcon from '../ButtonIcon';
const getComponent = (props = {}) => shallow(<Button {...props}>Download</Button>);
describe('<Button />', () => {
it('applies rest props and additional classes', () => {
const mounted = getComponent({ className: 'foo', 'aria-hidden': true });
const el = mounted.find('.slds-button');
expect(el.prop('aria-hidden')).toBeTruthy();
expect(el.hasClass('foo')).toBeTruthy();
});
it('renders children', () => {
const mounted = getComponent();
expect(mounted.text()).toEqual('Download');
});
it('uses title as children if no children are set', () => {
const mounted = getComponent({ title: 'foo' });
mounted.setProps({ children: null });
expect(mounted.find('button').text()).toEqual('foo');
});
it('renders as button by default', () => {
const mounted = getComponent();
const el = mounted.find('button');
expect(el.exists()).toBeTruthy();
});
it('renders as link', () => {
const mounted = getComponent({ href: '#derp' });
const el = mounted.find('a');
expect(el.exists()).toBeTruthy();
});
it('renders a button with icon via a shortcut', () => {
const mounted = getComponent({ icon: 'foo', sprite: 'standard' });
const el = mounted.find('.slds-button');
expect(el.hasClass('slds-button_neutral')).toBeTruthy();
const iconEl = el.find(ButtonIcon);
expect(iconEl.prop('icon')).toEqual('foo');
expect(iconEl.prop('sprite')).toEqual('standard');
expect(iconEl.prop('position')).toEqual('left');
mounted.setProps({ iconPosition: 'right' });
expect(mounted.find(ButtonIcon).prop('position')).toEqual('right');
});
it('renders flavors', () => {
const mounted = getComponent({ flavor: 'success' });
expect(mounted.hasClass('slds-button_success')).toBeTruthy();
});
it('renders neutral', () => {
const mounted = getComponent({ flavor: 'success' });
expect(mounted.hasClass('slds-button_success')).toBeTruthy();
});
it('renders without a flavor', () => {
const mounted = getComponent({ flavor: 'none' });
expect(mounted.hasClass('slds-button_none')).not.toBeTruthy();
mounted.setProps({ flavor: null });
expect(mounted.hasClass('slds-button_neutral')).not.toBeTruthy();
});
});
|
client/extensions/woocommerce/woocommerce-services/views/packages/edit-package.js
|
Automattic/woocommerce-connect-client
|
/** @format */
/**
* External dependencies
*/
import React from 'react';
import PropTypes from 'prop-types';
import { localize } from 'i18n-calypso';
import { omit, trim } from 'lodash';
/**
* Internal dependencies
*/
import FormDimensionsInput from 'woocommerce/components/form-dimensions-input';
import FormFieldset from 'components/forms/form-fieldset';
import FormLabel from 'components/forms/form-label';
import FormSelect from 'components/forms/form-select';
import FormTextInput from 'components/forms/form-text-input';
import FormTextInputWithAffixes from 'components/forms/form-text-input-with-affixes';
import FieldError from '../../components/field-error';
import inputFilters from './input-filters';
const renderDimensionsInput = ( dimensionsName, dimensionsStr, dimensionsUnit, updateField ) => {
const { length, width, height } = inputFilters.parseDimensions( dimensionsStr );
const onChange = event => {
const name = event.target.name;
const value = event.target.value;
const allDimensions = [
'length' === name ? value : length,
'width' === name ? value : width,
'height' === name ? value : height,
];
updateField( dimensionsName, allDimensions.join( ' x ' ) );
};
return (
<FormDimensionsInput
dimensionsUnit={ dimensionsUnit }
dimensions={ { width, height, length } }
onChange={ onChange }
/>
);
};
const EditPackage = props => {
const {
siteId,
form,
setModalErrors,
updatePackagesField,
translate,
} = props;
const { mode, modalErrors, dimensionUnit, weightUnit, packageData } = form;
const {
name,
inner_dimensions,
box_weight,
is_letter,
} = packageData;
const updateField = ( key, value ) => {
setModalErrors( siteId, omit( modalErrors, key ) );
updatePackagesField( siteId, { [ key ]: value } );
};
const updateTextField = event => {
const key = event.target.name;
const value = event.target.value;
updateField( key, value );
};
const fieldInfo = ( field, nonEmptyText ) => {
const altText = nonEmptyText || translate( 'Invalid value.' );
const text =
'' === trim( packageData[ field ] ) ? translate( 'This field is required.' ) : altText;
return modalErrors[ field ] ? <FieldError text={ text } /> : null;
};
const onPackageTypeSelect = event => {
updatePackagesField( siteId, { is_letter: 'envelope' === event.target.value } );
};
const renderTypeSelection = () => {
return (
<FormFieldset>
<FormLabel htmlFor="package_type">{ translate( 'Type of package' ) }</FormLabel>
<FormSelect
id="package_type"
onChange={ onPackageTypeSelect }
value={ is_letter ? 'envelope' : 'box' }
>
<option value="box">{ translate( 'Box' ) }</option>
<option value="envelope">{ translate( 'Envelope' ) }</option>
</FormSelect>
</FormFieldset>
);
};
return (
<div className="packages__properties-group">
{ 'add-custom' === mode ? renderTypeSelection() : null }
<FormFieldset>
<FormLabel htmlFor="name">{ translate( 'Package name' ) }</FormLabel>
<FormTextInput
id="name"
name="name"
placeholder={ translate( 'Unique package name' ) }
value={ name || '' }
onChange={ updateTextField }
isError={ modalErrors.name }
/>
{ fieldInfo( 'name', translate( 'This field must be unique' ) ) }
</FormFieldset>
<FormFieldset className="packages__add-package-weight-group">
<div className="packages__add-package-weight">
<FormLabel>
{ translate( 'Dimensions (L x W x H)' ) }
</FormLabel>
{ renderDimensionsInput(
'inner_dimensions',
inner_dimensions,
dimensionUnit,
updateField
) }
{ fieldInfo( 'inner_dimensions' ) }
</div>
<div className="packages__add-package-weight">
<FormLabel htmlFor="box_weight">{ translate( 'Weight of empty package' ) }</FormLabel>
<FormTextInputWithAffixes
id="box_weight"
name="box_weight"
placeholder={ translate( '0.0' ) }
value={ box_weight || '' }
onChange={ updateTextField }
isError={ modalErrors.box_weight }
type="number"
noWrap
suffix={ weightUnit }
/>
{ fieldInfo( 'box_weight' ) }
</div>
</FormFieldset>
</div>
);
};
EditPackage.propTypes = {
siteId: PropTypes.number.isRequired,
form: PropTypes.object.isRequired,
updatePackagesField: PropTypes.func.isRequired,
packageData: PropTypes.shape( {
name: PropTypes.string.isRequired,
inner_dimensions: PropTypes.string.isRequired,
box_weight: PropTypes.number.isRequired,
is_user_defined: PropTypes.bool.isRequired,
is_letter: PropTypes.bool.isRequired,
} ),
setModalErrors: PropTypes.func.isRequired,
};
export default localize( EditPackage );
|
packages/shared/forks/consoleWithStackDev.www.js
|
billfeller/react
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// This refers to a WWW module.
const warningWWW = require('warning');
export function warn(format, ...args) {
if (__DEV__) {
printWarning('warn', format, args);
}
}
export function error(format, ...args) {
if (__DEV__) {
printWarning('error', format, args);
}
}
function printWarning(level, format, args) {
if (__DEV__) {
const React = require('react');
const ReactSharedInternals =
React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
// Defensive in case this is fired before React is initialized.
if (ReactSharedInternals != null) {
const ReactDebugCurrentFrame =
ReactSharedInternals.ReactDebugCurrentFrame;
const stack = ReactDebugCurrentFrame.getStackAddendum();
if (stack !== '') {
format += '%s';
args.push(stack);
}
}
// TODO: don't ignore level and pass it down somewhere too.
args.unshift(format);
args.unshift(false);
warningWWW.apply(null, args);
}
}
|
src/components/Messages/Error/Error.specs.js
|
auth0-extensions/auth0-extension-ui
|
import React from 'react';
import { mount } from 'enzyme';
import { expect } from 'chai';
import sinon from 'sinon';
import Error from './';
const { describe, it } = global;
describe('Error', () => {
const field = {
message: 'This is the error message'
};
let wrapper;
describe('test elements', () => {
beforeEach((done) => {
wrapper = mount(<Error message={field.message} onDismiss={field.onDismiss} />);
done();
});
it('should show error message', () => {
expect(wrapper.find('.alert').text()).to.contain(field.message);
});
});
describe('test function', () => {
it('should call onDismiss if alert is closed', () => {
const onDismiss = sinon.spy();
wrapper = mount(<Error message={field.message} onDismiss={onDismiss} />);
wrapper.find('button.close').first().simulate('click');
expect(onDismiss.calledOnce).to.equal(true);
});
});
describe('test show attr', () => {
it('should not show anything', () => {
wrapper = mount(<Error message={field.message} show={false} />);
expect(wrapper.find('.alert')).to.have.length(0);
});
it('should show alert', () => {
wrapper = mount(<Error message={field.message} show={true} />);
expect(wrapper.find('.alert')).to.have.length(1);
});
});
});
|
ajax/libs/react-virtualized/9.14.0/react-virtualized.js
|
jonobr1/cdnjs
|
!function(root, factory) {
"object" == typeof exports && "object" == typeof module ? module.exports = factory(require("React"), require("ReactDOM")) : "function" == typeof define && define.amd ? define([ "React", "ReactDOM" ], factory) : "object" == typeof exports ? exports.ReactVirtualized = factory(require("React"), require("ReactDOM")) : root.ReactVirtualized = factory(root.React, root.ReactDOM);
}(this, function(__WEBPACK_EXTERNAL_MODULE_89__, __WEBPACK_EXTERNAL_MODULE_96__) {
/******/
return function(modules) {
/******/
/******/
// 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: !1
};
/******/
/******/
// Return the exports of the module
/******/
/******/
/******/
// Execute the module function
/******/
/******/
/******/
// Flag the module as loaded
/******/
return modules[moduleId].call(module.exports, module, module.exports, __webpack_require__),
module.loaded = !0, module.exports;
}
// webpackBootstrap
/******/
// The module cache
/******/
var installedModules = {};
/******/
/******/
// Load entry module and return exports
/******/
/******/
/******/
/******/
// expose the modules object (__webpack_modules__)
/******/
/******/
/******/
// expose the module cache
/******/
/******/
/******/
// __webpack_public_path__
/******/
return __webpack_require__.m = modules, __webpack_require__.c = installedModules,
__webpack_require__.p = "", __webpack_require__(0);
}([ /* 0 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _ArrowKeyStepper = __webpack_require__(1);
Object.defineProperty(exports, "ArrowKeyStepper", {
enumerable: !0,
get: function() {
return _ArrowKeyStepper.ArrowKeyStepper;
}
});
var _AutoSizer = __webpack_require__(90);
Object.defineProperty(exports, "AutoSizer", {
enumerable: !0,
get: function() {
return _AutoSizer.AutoSizer;
}
});
var _CellMeasurer = __webpack_require__(93);
Object.defineProperty(exports, "CellMeasurer", {
enumerable: !0,
get: function() {
return _CellMeasurer.CellMeasurer;
}
}), Object.defineProperty(exports, "CellMeasurerCache", {
enumerable: !0,
get: function() {
return _CellMeasurer.CellMeasurerCache;
}
});
var _Collection = __webpack_require__(98);
Object.defineProperty(exports, "Collection", {
enumerable: !0,
get: function() {
return _Collection.Collection;
}
});
var _ColumnSizer = __webpack_require__(125);
Object.defineProperty(exports, "ColumnSizer", {
enumerable: !0,
get: function() {
return _ColumnSizer.ColumnSizer;
}
});
var _Grid = __webpack_require__(127);
Object.defineProperty(exports, "accessibilityOverscanIndicesGetter", {
enumerable: !0,
get: function() {
return _Grid.accessibilityOverscanIndicesGetter;
}
}), Object.defineProperty(exports, "defaultCellRangeRenderer", {
enumerable: !0,
get: function() {
return _Grid.defaultCellRangeRenderer;
}
}), Object.defineProperty(exports, "defaultOverscanIndicesGetter", {
enumerable: !0,
get: function() {
return _Grid.defaultOverscanIndicesGetter;
}
}), Object.defineProperty(exports, "Grid", {
enumerable: !0,
get: function() {
return _Grid.Grid;
}
});
var _InfiniteLoader = __webpack_require__(139);
Object.defineProperty(exports, "InfiniteLoader", {
enumerable: !0,
get: function() {
return _InfiniteLoader.InfiniteLoader;
}
});
var _List = __webpack_require__(141);
Object.defineProperty(exports, "List", {
enumerable: !0,
get: function() {
return _List.List;
}
});
var _Masonry = __webpack_require__(146);
Object.defineProperty(exports, "createMasonryCellPositioner", {
enumerable: !0,
get: function() {
return _Masonry.createCellPositioner;
}
}), Object.defineProperty(exports, "Masonry", {
enumerable: !0,
get: function() {
return _Masonry.Masonry;
}
});
var _MultiGrid = __webpack_require__(161);
Object.defineProperty(exports, "MultiGrid", {
enumerable: !0,
get: function() {
return _MultiGrid.MultiGrid;
}
});
var _ScrollSync = __webpack_require__(164);
Object.defineProperty(exports, "ScrollSync", {
enumerable: !0,
get: function() {
return _ScrollSync.ScrollSync;
}
});
var _Table = __webpack_require__(166);
Object.defineProperty(exports, "defaultTableCellDataGetter", {
enumerable: !0,
get: function() {
return _Table.defaultCellDataGetter;
}
}), Object.defineProperty(exports, "defaultTableCellRenderer", {
enumerable: !0,
get: function() {
return _Table.defaultCellRenderer;
}
}), Object.defineProperty(exports, "defaultTableHeaderRenderer", {
enumerable: !0,
get: function() {
return _Table.defaultHeaderRenderer;
}
}), Object.defineProperty(exports, "defaultTableHeaderRowRenderer", {
enumerable: !0,
get: function() {
return _Table.defaultHeaderRowRenderer;
}
}), Object.defineProperty(exports, "defaultTableRowRenderer", {
enumerable: !0,
get: function() {
return _Table.defaultRowRenderer;
}
}), Object.defineProperty(exports, "Table", {
enumerable: !0,
get: function() {
return _Table.Table;
}
}), Object.defineProperty(exports, "Column", {
enumerable: !0,
get: function() {
return _Table.Column;
}
}), Object.defineProperty(exports, "SortDirection", {
enumerable: !0,
get: function() {
return _Table.SortDirection;
}
}), Object.defineProperty(exports, "SortIndicator", {
enumerable: !0,
get: function() {
return _Table.SortIndicator;
}
});
var _WindowScroller = __webpack_require__(176);
Object.defineProperty(exports, "WindowScroller", {
enumerable: !0,
get: function() {
return _WindowScroller.WindowScroller;
}
});
}, /* 1 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _ArrowKeyStepper = __webpack_require__(2);
Object.defineProperty(exports, "default", {
enumerable: !0,
get: function() {
return _interopRequireDefault(_ArrowKeyStepper).default;
}
}), Object.defineProperty(exports, "ArrowKeyStepper", {
enumerable: !0,
get: function() {
return _interopRequireDefault(_ArrowKeyStepper).default;
}
});
}, /* 2 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _react = __webpack_require__(89), _react2 = _interopRequireDefault(_react), ArrowKeyStepper = function(_React$PureComponent) {
function ArrowKeyStepper(props) {
(0, _classCallCheck3.default)(this, ArrowKeyStepper);
var _this = (0, _possibleConstructorReturn3.default)(this, (ArrowKeyStepper.__proto__ || (0,
_getPrototypeOf2.default)(ArrowKeyStepper)).call(this, props));
return _this._columnStartIndex = 0, _this._columnStopIndex = 0, _this._rowStartIndex = 0,
_this._rowStopIndex = 0, _this._onKeyDown = function(event) {
var _this$props = _this.props, columnCount = _this$props.columnCount, disabled = _this$props.disabled, mode = _this$props.mode, rowCount = _this$props.rowCount;
if (!disabled) {
var _this$_getScrollState = _this._getScrollState(), scrollToColumnPrevious = _this$_getScrollState.scrollToColumn, scrollToRowPrevious = _this$_getScrollState.scrollToRow, _this$_getScrollState2 = _this._getScrollState(), scrollToColumn = _this$_getScrollState2.scrollToColumn, scrollToRow = _this$_getScrollState2.scrollToRow;
switch (event.key) {
case "ArrowDown":
scrollToRow = "cells" === mode ? Math.min(scrollToRow + 1, rowCount - 1) : Math.min(_this._rowStopIndex + 1, rowCount - 1);
break;
case "ArrowLeft":
scrollToColumn = "cells" === mode ? Math.max(scrollToColumn - 1, 0) : Math.max(_this._columnStartIndex - 1, 0);
break;
case "ArrowRight":
scrollToColumn = "cells" === mode ? Math.min(scrollToColumn + 1, columnCount - 1) : Math.min(_this._columnStopIndex + 1, columnCount - 1);
break;
case "ArrowUp":
scrollToRow = "cells" === mode ? Math.max(scrollToRow - 1, 0) : Math.max(_this._rowStartIndex - 1, 0);
}
scrollToColumn === scrollToColumnPrevious && scrollToRow === scrollToRowPrevious || (event.preventDefault(),
_this._updateScrollState({
scrollToColumn: scrollToColumn,
scrollToRow: scrollToRow
}));
}
}, _this._onSectionRendered = function(_ref) {
var columnStartIndex = _ref.columnStartIndex, columnStopIndex = _ref.columnStopIndex, rowStartIndex = _ref.rowStartIndex, rowStopIndex = _ref.rowStopIndex;
_this._columnStartIndex = columnStartIndex, _this._columnStopIndex = columnStopIndex,
_this._rowStartIndex = rowStartIndex, _this._rowStopIndex = rowStopIndex;
}, _this.state = {
scrollToColumn: props.scrollToColumn,
scrollToRow: props.scrollToRow
}, _this;
}
return (0, _inherits3.default)(ArrowKeyStepper, _React$PureComponent), (0, _createClass3.default)(ArrowKeyStepper, [ {
key: "componentWillReceiveProps",
value: function(nextProps) {
if (!this.props.isControlled) {
var scrollToColumn = nextProps.scrollToColumn, scrollToRow = nextProps.scrollToRow, _props = this.props, prevScrollToColumn = _props.scrollToColumn, prevScrollToRow = _props.scrollToRow;
prevScrollToColumn !== scrollToColumn && prevScrollToRow !== scrollToRow ? this.setState({
scrollToColumn: scrollToColumn,
scrollToRow: scrollToRow
}) : prevScrollToColumn !== scrollToColumn ? this.setState({
scrollToColumn: scrollToColumn
}) : prevScrollToRow !== scrollToRow && this.setState({
scrollToRow: scrollToRow
});
}
}
}, {
key: "setScrollIndexes",
value: function(_ref2) {
var scrollToColumn = _ref2.scrollToColumn, scrollToRow = _ref2.scrollToRow;
this.setState({
scrollToRow: scrollToRow,
scrollToColumn: scrollToColumn
});
}
}, {
key: "render",
value: function() {
var _props2 = this.props, className = _props2.className, children = _props2.children, _getScrollState2 = this._getScrollState(), scrollToColumn = _getScrollState2.scrollToColumn, scrollToRow = _getScrollState2.scrollToRow;
return _react2.default.createElement("div", {
className: className,
onKeyDown: this._onKeyDown
}, children({
onSectionRendered: this._onSectionRendered,
scrollToColumn: scrollToColumn,
scrollToRow: scrollToRow
}));
}
}, {
key: "_getScrollState",
value: function() {
return this.props.isControlled ? this.props : this.state;
}
}, {
key: "_updateScrollState",
value: function(_ref3) {
var scrollToColumn = _ref3.scrollToColumn, scrollToRow = _ref3.scrollToRow, _props3 = this.props, isControlled = _props3.isControlled, onScrollToChange = _props3.onScrollToChange;
"function" == typeof onScrollToChange && onScrollToChange({
scrollToColumn: scrollToColumn,
scrollToRow: scrollToRow
}), isControlled || this.setState({
scrollToColumn: scrollToColumn,
scrollToRow: scrollToRow
});
}
} ]), ArrowKeyStepper;
}(_react2.default.PureComponent);
ArrowKeyStepper.defaultProps = {
disabled: !1,
isControlled: !1,
mode: "edges",
scrollToColumn: 0,
scrollToRow: 0
}, exports.default = ArrowKeyStepper;
}, /* 3 */
/***/
function(module, exports, __webpack_require__) {
module.exports = {
default: __webpack_require__(4),
__esModule: !0
};
}, /* 4 */
/***/
function(module, exports, __webpack_require__) {
__webpack_require__(5), module.exports = __webpack_require__(16).Object.getPrototypeOf;
}, /* 5 */
/***/
function(module, exports, __webpack_require__) {
// 19.1.2.9 Object.getPrototypeOf(O)
var toObject = __webpack_require__(6), $getPrototypeOf = __webpack_require__(8);
__webpack_require__(14)("getPrototypeOf", function() {
return function(it) {
return $getPrototypeOf(toObject(it));
};
});
}, /* 6 */
/***/
function(module, exports, __webpack_require__) {
// 7.1.13 ToObject(argument)
var defined = __webpack_require__(7);
module.exports = function(it) {
return Object(defined(it));
};
}, /* 7 */
/***/
function(module, exports) {
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function(it) {
if (void 0 == it) throw TypeError("Can't call method on " + it);
return it;
};
}, /* 8 */
/***/
function(module, exports, __webpack_require__) {
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = __webpack_require__(9), toObject = __webpack_require__(6), IE_PROTO = __webpack_require__(10)("IE_PROTO"), ObjectProto = Object.prototype;
module.exports = Object.getPrototypeOf || function(O) {
return O = toObject(O), has(O, IE_PROTO) ? O[IE_PROTO] : "function" == typeof O.constructor && O instanceof O.constructor ? O.constructor.prototype : O instanceof Object ? ObjectProto : null;
};
}, /* 9 */
/***/
function(module, exports) {
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function(it, key) {
return hasOwnProperty.call(it, key);
};
}, /* 10 */
/***/
function(module, exports, __webpack_require__) {
var shared = __webpack_require__(11)("keys"), uid = __webpack_require__(13);
module.exports = function(key) {
return shared[key] || (shared[key] = uid(key));
};
}, /* 11 */
/***/
function(module, exports, __webpack_require__) {
var global = __webpack_require__(12), SHARED = "__core-js_shared__", store = global[SHARED] || (global[SHARED] = {});
module.exports = function(key) {
return store[key] || (store[key] = {});
};
}, /* 12 */
/***/
function(module, exports) {
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = "undefined" != typeof window && window.Math == Math ? window : "undefined" != typeof self && self.Math == Math ? self : Function("return this")();
"number" == typeof __g && (__g = global);
}, /* 13 */
/***/
function(module, exports) {
var id = 0, px = Math.random();
module.exports = function(key) {
return "Symbol(".concat(void 0 === key ? "" : key, ")_", (++id + px).toString(36));
};
}, /* 14 */
/***/
function(module, exports, __webpack_require__) {
// most Object methods by ES6 should accept primitives
var $export = __webpack_require__(15), core = __webpack_require__(16), fails = __webpack_require__(25);
module.exports = function(KEY, exec) {
var fn = (core.Object || {})[KEY] || Object[KEY], exp = {};
exp[KEY] = exec(fn), $export($export.S + $export.F * fails(function() {
fn(1);
}), "Object", exp);
};
}, /* 15 */
/***/
function(module, exports, __webpack_require__) {
var global = __webpack_require__(12), core = __webpack_require__(16), ctx = __webpack_require__(17), hide = __webpack_require__(19), PROTOTYPE = "prototype", $export = function(type, name, source) {
var key, own, out, IS_FORCED = type & $export.F, IS_GLOBAL = type & $export.G, IS_STATIC = type & $export.S, IS_PROTO = type & $export.P, IS_BIND = type & $export.B, IS_WRAP = type & $export.W, exports = IS_GLOBAL ? core : core[name] || (core[name] = {}), expProto = exports[PROTOTYPE], target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE];
IS_GLOBAL && (source = name);
for (key in source) // contains in native
own = !IS_FORCED && target && void 0 !== target[key], own && key in exports || (// export native or passed
out = own ? target[key] : source[key], // prevent global pollution for namespaces
exports[key] = IS_GLOBAL && "function" != typeof target[key] ? source[key] : IS_BIND && own ? ctx(out, global) : IS_WRAP && target[key] == out ? function(C) {
var F = function(a, b, c) {
if (this instanceof C) {
switch (arguments.length) {
case 0:
return new C();
case 1:
return new C(a);
case 2:
return new C(a, b);
}
return new C(a, b, c);
}
return C.apply(this, arguments);
};
return F[PROTOTYPE] = C[PROTOTYPE], F;
}(out) : IS_PROTO && "function" == typeof out ? ctx(Function.call, out) : out, // export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
IS_PROTO && ((exports.virtual || (exports.virtual = {}))[key] = out, // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
type & $export.R && expProto && !expProto[key] && hide(expProto, key, out)));
};
// type bitmap
$export.F = 1, // forced
$export.G = 2, // global
$export.S = 4, // static
$export.P = 8, // proto
$export.B = 16, // bind
$export.W = 32, // wrap
$export.U = 64, // safe
$export.R = 128, // real proto method for `library`
module.exports = $export;
}, /* 16 */
/***/
function(module, exports) {
var core = module.exports = {
version: "2.4.0"
};
"number" == typeof __e && (__e = core);
}, /* 17 */
/***/
function(module, exports, __webpack_require__) {
// optional / simple context binding
var aFunction = __webpack_require__(18);
module.exports = function(fn, that, length) {
if (aFunction(fn), void 0 === that) return fn;
switch (length) {
case 1:
return function(a) {
return fn.call(that, a);
};
case 2:
return function(a, b) {
return fn.call(that, a, b);
};
case 3:
return function(a, b, c) {
return fn.call(that, a, b, c);
};
}
return function() {
return fn.apply(that, arguments);
};
};
}, /* 18 */
/***/
function(module, exports) {
module.exports = function(it) {
if ("function" != typeof it) throw TypeError(it + " is not a function!");
return it;
};
}, /* 19 */
/***/
function(module, exports, __webpack_require__) {
var dP = __webpack_require__(20), createDesc = __webpack_require__(28);
module.exports = __webpack_require__(24) ? function(object, key, value) {
return dP.f(object, key, createDesc(1, value));
} : function(object, key, value) {
return object[key] = value, object;
};
}, /* 20 */
/***/
function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(21), IE8_DOM_DEFINE = __webpack_require__(23), toPrimitive = __webpack_require__(27), dP = Object.defineProperty;
exports.f = __webpack_require__(24) ? Object.defineProperty : function(O, P, Attributes) {
if (anObject(O), P = toPrimitive(P, !0), anObject(Attributes), IE8_DOM_DEFINE) try {
return dP(O, P, Attributes);
} catch (e) {}
if ("get" in Attributes || "set" in Attributes) throw TypeError("Accessors not supported!");
return "value" in Attributes && (O[P] = Attributes.value), O;
};
}, /* 21 */
/***/
function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(22);
module.exports = function(it) {
if (!isObject(it)) throw TypeError(it + " is not an object!");
return it;
};
}, /* 22 */
/***/
function(module, exports) {
module.exports = function(it) {
return "object" == typeof it ? null !== it : "function" == typeof it;
};
}, /* 23 */
/***/
function(module, exports, __webpack_require__) {
module.exports = !__webpack_require__(24) && !__webpack_require__(25)(function() {
return 7 != Object.defineProperty(__webpack_require__(26)("div"), "a", {
get: function() {
return 7;
}
}).a;
});
}, /* 24 */
/***/
function(module, exports, __webpack_require__) {
// Thank's IE8 for his funny defineProperty
module.exports = !__webpack_require__(25)(function() {
return 7 != Object.defineProperty({}, "a", {
get: function() {
return 7;
}
}).a;
});
}, /* 25 */
/***/
function(module, exports) {
module.exports = function(exec) {
try {
return !!exec();
} catch (e) {
return !0;
}
};
}, /* 26 */
/***/
function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(22), document = __webpack_require__(12).document, is = isObject(document) && isObject(document.createElement);
module.exports = function(it) {
return is ? document.createElement(it) : {};
};
}, /* 27 */
/***/
function(module, exports, __webpack_require__) {
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = __webpack_require__(22);
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function(it, S) {
if (!isObject(it)) return it;
var fn, val;
if (S && "function" == typeof (fn = it.toString) && !isObject(val = fn.call(it))) return val;
if ("function" == typeof (fn = it.valueOf) && !isObject(val = fn.call(it))) return val;
if (!S && "function" == typeof (fn = it.toString) && !isObject(val = fn.call(it))) return val;
throw TypeError("Can't convert object to primitive value");
};
}, /* 28 */
/***/
function(module, exports) {
module.exports = function(bitmap, value) {
return {
enumerable: !(1 & bitmap),
configurable: !(2 & bitmap),
writable: !(4 & bitmap),
value: value
};
};
}, /* 29 */
/***/
function(module, exports) {
"use strict";
exports.__esModule = !0, exports.default = function(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
};
}, /* 30 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
exports.__esModule = !0;
var _defineProperty = __webpack_require__(31), _defineProperty2 = _interopRequireDefault(_defineProperty);
exports.default = function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0,
"value" in descriptor && (descriptor.writable = !0), (0, _defineProperty2.default)(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps),
Constructor;
};
}();
}, /* 31 */
/***/
function(module, exports, __webpack_require__) {
module.exports = {
default: __webpack_require__(32),
__esModule: !0
};
}, /* 32 */
/***/
function(module, exports, __webpack_require__) {
__webpack_require__(33);
var $Object = __webpack_require__(16).Object;
module.exports = function(it, key, desc) {
return $Object.defineProperty(it, key, desc);
};
}, /* 33 */
/***/
function(module, exports, __webpack_require__) {
var $export = __webpack_require__(15);
// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
$export($export.S + $export.F * !__webpack_require__(24), "Object", {
defineProperty: __webpack_require__(20).f
});
}, /* 34 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
exports.__esModule = !0;
var _typeof2 = __webpack_require__(35), _typeof3 = _interopRequireDefault(_typeof2);
exports.default = function(self, call) {
if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return !call || "object" !== ("undefined" == typeof call ? "undefined" : (0, _typeof3.default)(call)) && "function" != typeof call ? self : call;
};
}, /* 35 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
exports.__esModule = !0;
var _iterator = __webpack_require__(36), _iterator2 = _interopRequireDefault(_iterator), _symbol = __webpack_require__(65), _symbol2 = _interopRequireDefault(_symbol), _typeof = "function" == typeof _symbol2.default && "symbol" == typeof _iterator2.default ? function(obj) {
return typeof obj;
} : function(obj) {
return obj && "function" == typeof _symbol2.default && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj;
};
exports.default = "function" == typeof _symbol2.default && "symbol" === _typeof(_iterator2.default) ? function(obj) {
return "undefined" == typeof obj ? "undefined" : _typeof(obj);
} : function(obj) {
return obj && "function" == typeof _symbol2.default && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : "undefined" == typeof obj ? "undefined" : _typeof(obj);
};
}, /* 36 */
/***/
function(module, exports, __webpack_require__) {
module.exports = {
default: __webpack_require__(37),
__esModule: !0
};
}, /* 37 */
/***/
function(module, exports, __webpack_require__) {
__webpack_require__(38), __webpack_require__(60), module.exports = __webpack_require__(64).f("iterator");
}, /* 38 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
var $at = __webpack_require__(39)(!0);
// 21.1.3.27 String.prototype[@@iterator]()
__webpack_require__(41)(String, "String", function(iterated) {
this._t = String(iterated), // target
this._i = 0;
}, function() {
var point, O = this._t, index = this._i;
return index >= O.length ? {
value: void 0,
done: !0
} : (point = $at(O, index), this._i += point.length, {
value: point,
done: !1
});
});
}, /* 39 */
/***/
function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(40), defined = __webpack_require__(7);
// true -> String#at
// false -> String#codePointAt
module.exports = function(TO_STRING) {
return function(that, pos) {
var a, b, s = String(defined(that)), i = toInteger(pos), l = s.length;
return i < 0 || i >= l ? TO_STRING ? "" : void 0 : (a = s.charCodeAt(i), a < 55296 || a > 56319 || i + 1 === l || (b = s.charCodeAt(i + 1)) < 56320 || b > 57343 ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 55296 << 10) + (b - 56320) + 65536);
};
};
}, /* 40 */
/***/
function(module, exports) {
// 7.1.4 ToInteger
var ceil = Math.ceil, floor = Math.floor;
module.exports = function(it) {
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
}, /* 41 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
var LIBRARY = __webpack_require__(42), $export = __webpack_require__(15), redefine = __webpack_require__(43), hide = __webpack_require__(19), has = __webpack_require__(9), Iterators = __webpack_require__(44), $iterCreate = __webpack_require__(45), setToStringTag = __webpack_require__(58), getPrototypeOf = __webpack_require__(8), ITERATOR = __webpack_require__(59)("iterator"), BUGGY = !([].keys && "next" in [].keys()), FF_ITERATOR = "@@iterator", KEYS = "keys", VALUES = "values", returnThis = function() {
return this;
};
module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) {
$iterCreate(Constructor, NAME, next);
var methods, key, IteratorPrototype, getMethod = function(kind) {
if (!BUGGY && kind in proto) return proto[kind];
switch (kind) {
case KEYS:
return function() {
return new Constructor(this, kind);
};
case VALUES:
return function() {
return new Constructor(this, kind);
};
}
return function() {
return new Constructor(this, kind);
};
}, TAG = NAME + " Iterator", DEF_VALUES = DEFAULT == VALUES, VALUES_BUG = !1, proto = Base.prototype, $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT], $default = $native || getMethod(DEFAULT), $entries = DEFAULT ? DEF_VALUES ? getMethod("entries") : $default : void 0, $anyNative = "Array" == NAME ? proto.entries || $native : $native;
if (// Fix native
$anyNative && (IteratorPrototype = getPrototypeOf($anyNative.call(new Base())),
IteratorPrototype !== Object.prototype && (// Set @@toStringTag to native iterators
setToStringTag(IteratorPrototype, TAG, !0), // fix for some old engines
LIBRARY || has(IteratorPrototype, ITERATOR) || hide(IteratorPrototype, ITERATOR, returnThis))),
// fix Array#{values, @@iterator}.name in V8 / FF
DEF_VALUES && $native && $native.name !== VALUES && (VALUES_BUG = !0, $default = function() {
return $native.call(this);
}), // Define iterator
LIBRARY && !FORCED || !BUGGY && !VALUES_BUG && proto[ITERATOR] || hide(proto, ITERATOR, $default),
// Plug for library
Iterators[NAME] = $default, Iterators[TAG] = returnThis, DEFAULT) if (methods = {
values: DEF_VALUES ? $default : getMethod(VALUES),
keys: IS_SET ? $default : getMethod(KEYS),
entries: $entries
}, FORCED) for (key in methods) key in proto || redefine(proto, key, methods[key]); else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
return methods;
};
}, /* 42 */
/***/
function(module, exports) {
module.exports = !0;
}, /* 43 */
/***/
function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(19);
}, /* 44 */
/***/
function(module, exports) {
module.exports = {};
}, /* 45 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
var create = __webpack_require__(46), descriptor = __webpack_require__(28), setToStringTag = __webpack_require__(58), IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
__webpack_require__(19)(IteratorPrototype, __webpack_require__(59)("iterator"), function() {
return this;
}), module.exports = function(Constructor, NAME, next) {
Constructor.prototype = create(IteratorPrototype, {
next: descriptor(1, next)
}), setToStringTag(Constructor, NAME + " Iterator");
};
}, /* 46 */
/***/
function(module, exports, __webpack_require__) {
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = __webpack_require__(21), dPs = __webpack_require__(47), enumBugKeys = __webpack_require__(56), IE_PROTO = __webpack_require__(10)("IE_PROTO"), Empty = function() {}, PROTOTYPE = "prototype", createDict = function() {
// Thrash, waste and sodomy: IE GC bug
var iframeDocument, iframe = __webpack_require__(26)("iframe"), i = enumBugKeys.length, lt = "<", gt = ">";
for (iframe.style.display = "none", __webpack_require__(57).appendChild(iframe),
iframe.src = "javascript:", // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document, iframeDocument.open(), iframeDocument.write(lt + "script" + gt + "document.F=Object" + lt + "/script" + gt),
iframeDocument.close(), createDict = iframeDocument.F; i--; ) delete createDict[PROTOTYPE][enumBugKeys[i]];
return createDict();
};
module.exports = Object.create || function(O, Properties) {
var result;
// add "__proto__" for Object.getPrototypeOf polyfill
return null !== O ? (Empty[PROTOTYPE] = anObject(O), result = new Empty(), Empty[PROTOTYPE] = null,
result[IE_PROTO] = O) : result = createDict(), void 0 === Properties ? result : dPs(result, Properties);
};
}, /* 47 */
/***/
function(module, exports, __webpack_require__) {
var dP = __webpack_require__(20), anObject = __webpack_require__(21), getKeys = __webpack_require__(48);
module.exports = __webpack_require__(24) ? Object.defineProperties : function(O, Properties) {
anObject(O);
for (var P, keys = getKeys(Properties), length = keys.length, i = 0; length > i; ) dP.f(O, P = keys[i++], Properties[P]);
return O;
};
}, /* 48 */
/***/
function(module, exports, __webpack_require__) {
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = __webpack_require__(49), enumBugKeys = __webpack_require__(56);
module.exports = Object.keys || function(O) {
return $keys(O, enumBugKeys);
};
}, /* 49 */
/***/
function(module, exports, __webpack_require__) {
var has = __webpack_require__(9), toIObject = __webpack_require__(50), arrayIndexOf = __webpack_require__(53)(!1), IE_PROTO = __webpack_require__(10)("IE_PROTO");
module.exports = function(object, names) {
var key, O = toIObject(object), i = 0, result = [];
for (key in O) key != IE_PROTO && has(O, key) && result.push(key);
// Don't enum bug & hidden keys
for (;names.length > i; ) has(O, key = names[i++]) && (~arrayIndexOf(result, key) || result.push(key));
return result;
};
}, /* 50 */
/***/
function(module, exports, __webpack_require__) {
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = __webpack_require__(51), defined = __webpack_require__(7);
module.exports = function(it) {
return IObject(defined(it));
};
}, /* 51 */
/***/
function(module, exports, __webpack_require__) {
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = __webpack_require__(52);
module.exports = Object("z").propertyIsEnumerable(0) ? Object : function(it) {
return "String" == cof(it) ? it.split("") : Object(it);
};
}, /* 52 */
/***/
function(module, exports) {
var toString = {}.toString;
module.exports = function(it) {
return toString.call(it).slice(8, -1);
};
}, /* 53 */
/***/
function(module, exports, __webpack_require__) {
// false -> Array#indexOf
// true -> Array#includes
var toIObject = __webpack_require__(50), toLength = __webpack_require__(54), toIndex = __webpack_require__(55);
module.exports = function(IS_INCLUDES) {
return function($this, el, fromIndex) {
var value, O = toIObject($this), length = toLength(O.length), index = toIndex(fromIndex, length);
// Array#includes uses SameValueZero equality algorithm
if (IS_INCLUDES && el != el) {
for (;length > index; ) if (value = O[index++], value != value) return !0;
} else for (;length > index; index++) if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
return !IS_INCLUDES && -1;
};
};
}, /* 54 */
/***/
function(module, exports, __webpack_require__) {
// 7.1.15 ToLength
var toInteger = __webpack_require__(40), min = Math.min;
module.exports = function(it) {
return it > 0 ? min(toInteger(it), 9007199254740991) : 0;
};
}, /* 55 */
/***/
function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(40), max = Math.max, min = Math.min;
module.exports = function(index, length) {
return index = toInteger(index), index < 0 ? max(index + length, 0) : min(index, length);
};
}, /* 56 */
/***/
function(module, exports) {
// IE 8- don't enum bug keys
module.exports = "constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",");
}, /* 57 */
/***/
function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(12).document && document.documentElement;
}, /* 58 */
/***/
function(module, exports, __webpack_require__) {
var def = __webpack_require__(20).f, has = __webpack_require__(9), TAG = __webpack_require__(59)("toStringTag");
module.exports = function(it, tag, stat) {
it && !has(it = stat ? it : it.prototype, TAG) && def(it, TAG, {
configurable: !0,
value: tag
});
};
}, /* 59 */
/***/
function(module, exports, __webpack_require__) {
var store = __webpack_require__(11)("wks"), uid = __webpack_require__(13), Symbol = __webpack_require__(12).Symbol, USE_SYMBOL = "function" == typeof Symbol, $exports = module.exports = function(name) {
return store[name] || (store[name] = USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)("Symbol." + name));
};
$exports.store = store;
}, /* 60 */
/***/
function(module, exports, __webpack_require__) {
__webpack_require__(61);
for (var global = __webpack_require__(12), hide = __webpack_require__(19), Iterators = __webpack_require__(44), TO_STRING_TAG = __webpack_require__(59)("toStringTag"), collections = [ "NodeList", "DOMTokenList", "MediaList", "StyleSheetList", "CSSRuleList" ], i = 0; i < 5; i++) {
var NAME = collections[i], Collection = global[NAME], proto = Collection && Collection.prototype;
proto && !proto[TO_STRING_TAG] && hide(proto, TO_STRING_TAG, NAME), Iterators[NAME] = Iterators.Array;
}
}, /* 61 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
var addToUnscopables = __webpack_require__(62), step = __webpack_require__(63), Iterators = __webpack_require__(44), toIObject = __webpack_require__(50);
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = __webpack_require__(41)(Array, "Array", function(iterated, kind) {
this._t = toIObject(iterated), // target
this._i = 0, // next index
this._k = kind;
}, function() {
var O = this._t, kind = this._k, index = this._i++;
return !O || index >= O.length ? (this._t = void 0, step(1)) : "keys" == kind ? step(0, index) : "values" == kind ? step(0, O[index]) : step(0, [ index, O[index] ]);
}, "values"), // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array, addToUnscopables("keys"), addToUnscopables("values"),
addToUnscopables("entries");
}, /* 62 */
/***/
function(module, exports) {
module.exports = function() {};
}, /* 63 */
/***/
function(module, exports) {
module.exports = function(done, value) {
return {
value: value,
done: !!done
};
};
}, /* 64 */
/***/
function(module, exports, __webpack_require__) {
exports.f = __webpack_require__(59);
}, /* 65 */
/***/
function(module, exports, __webpack_require__) {
module.exports = {
default: __webpack_require__(66),
__esModule: !0
};
}, /* 66 */
/***/
function(module, exports, __webpack_require__) {
__webpack_require__(67), __webpack_require__(78), __webpack_require__(79), __webpack_require__(80),
module.exports = __webpack_require__(16).Symbol;
}, /* 67 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
// ECMAScript 6 symbols shim
var global = __webpack_require__(12), has = __webpack_require__(9), DESCRIPTORS = __webpack_require__(24), $export = __webpack_require__(15), redefine = __webpack_require__(43), META = __webpack_require__(68).KEY, $fails = __webpack_require__(25), shared = __webpack_require__(11), setToStringTag = __webpack_require__(58), uid = __webpack_require__(13), wks = __webpack_require__(59), wksExt = __webpack_require__(64), wksDefine = __webpack_require__(69), keyOf = __webpack_require__(70), enumKeys = __webpack_require__(71), isArray = __webpack_require__(74), anObject = __webpack_require__(21), toIObject = __webpack_require__(50), toPrimitive = __webpack_require__(27), createDesc = __webpack_require__(28), _create = __webpack_require__(46), gOPNExt = __webpack_require__(75), $GOPD = __webpack_require__(77), $DP = __webpack_require__(20), $keys = __webpack_require__(48), gOPD = $GOPD.f, dP = $DP.f, gOPN = gOPNExt.f, $Symbol = global.Symbol, $JSON = global.JSON, _stringify = $JSON && $JSON.stringify, PROTOTYPE = "prototype", HIDDEN = wks("_hidden"), TO_PRIMITIVE = wks("toPrimitive"), isEnum = {}.propertyIsEnumerable, SymbolRegistry = shared("symbol-registry"), AllSymbols = shared("symbols"), OPSymbols = shared("op-symbols"), ObjectProto = Object[PROTOTYPE], USE_NATIVE = "function" == typeof $Symbol, QObject = global.QObject, setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild, setSymbolDesc = DESCRIPTORS && $fails(function() {
return 7 != _create(dP({}, "a", {
get: function() {
return dP(this, "a", {
value: 7
}).a;
}
})).a;
}) ? function(it, key, D) {
var protoDesc = gOPD(ObjectProto, key);
protoDesc && delete ObjectProto[key], dP(it, key, D), protoDesc && it !== ObjectProto && dP(ObjectProto, key, protoDesc);
} : dP, wrap = function(tag) {
var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
return sym._k = tag, sym;
}, isSymbol = USE_NATIVE && "symbol" == typeof $Symbol.iterator ? function(it) {
return "symbol" == typeof it;
} : function(it) {
return it instanceof $Symbol;
}, $defineProperty = function(it, key, D) {
return it === ObjectProto && $defineProperty(OPSymbols, key, D), anObject(it), key = toPrimitive(key, !0),
anObject(D), has(AllSymbols, key) ? (D.enumerable ? (has(it, HIDDEN) && it[HIDDEN][key] && (it[HIDDEN][key] = !1),
D = _create(D, {
enumerable: createDesc(0, !1)
})) : (has(it, HIDDEN) || dP(it, HIDDEN, createDesc(1, {})), it[HIDDEN][key] = !0),
setSymbolDesc(it, key, D)) : dP(it, key, D);
}, $defineProperties = function(it, P) {
anObject(it);
for (var key, keys = enumKeys(P = toIObject(P)), i = 0, l = keys.length; l > i; ) $defineProperty(it, key = keys[i++], P[key]);
return it;
}, $create = function(it, P) {
return void 0 === P ? _create(it) : $defineProperties(_create(it), P);
}, $propertyIsEnumerable = function(key) {
var E = isEnum.call(this, key = toPrimitive(key, !0));
return !(this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) && (!(E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key]) || E);
}, $getOwnPropertyDescriptor = function(it, key) {
if (it = toIObject(it), key = toPrimitive(key, !0), it !== ObjectProto || !has(AllSymbols, key) || has(OPSymbols, key)) {
var D = gOPD(it, key);
return !D || !has(AllSymbols, key) || has(it, HIDDEN) && it[HIDDEN][key] || (D.enumerable = !0),
D;
}
}, $getOwnPropertyNames = function(it) {
for (var key, names = gOPN(toIObject(it)), result = [], i = 0; names.length > i; ) has(AllSymbols, key = names[i++]) || key == HIDDEN || key == META || result.push(key);
return result;
}, $getOwnPropertySymbols = function(it) {
for (var key, IS_OP = it === ObjectProto, names = gOPN(IS_OP ? OPSymbols : toIObject(it)), result = [], i = 0; names.length > i; ) !has(AllSymbols, key = names[i++]) || IS_OP && !has(ObjectProto, key) || result.push(AllSymbols[key]);
return result;
};
// 19.4.1.1 Symbol([description])
USE_NATIVE || ($Symbol = function() {
if (this instanceof $Symbol) throw TypeError("Symbol is not a constructor!");
var tag = uid(arguments.length > 0 ? arguments[0] : void 0), $set = function(value) {
this === ObjectProto && $set.call(OPSymbols, value), has(this, HIDDEN) && has(this[HIDDEN], tag) && (this[HIDDEN][tag] = !1),
setSymbolDesc(this, tag, createDesc(1, value));
};
return DESCRIPTORS && setter && setSymbolDesc(ObjectProto, tag, {
configurable: !0,
set: $set
}), wrap(tag);
}, redefine($Symbol[PROTOTYPE], "toString", function() {
return this._k;
}), $GOPD.f = $getOwnPropertyDescriptor, $DP.f = $defineProperty, __webpack_require__(76).f = gOPNExt.f = $getOwnPropertyNames,
__webpack_require__(73).f = $propertyIsEnumerable, __webpack_require__(72).f = $getOwnPropertySymbols,
DESCRIPTORS && !__webpack_require__(42) && redefine(ObjectProto, "propertyIsEnumerable", $propertyIsEnumerable, !0),
wksExt.f = function(name) {
return wrap(wks(name));
}), $export($export.G + $export.W + $export.F * !USE_NATIVE, {
Symbol: $Symbol
});
for (var symbols = "hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","), i = 0; symbols.length > i; ) wks(symbols[i++]);
for (var symbols = $keys(wks.store), i = 0; symbols.length > i; ) wksDefine(symbols[i++]);
$export($export.S + $export.F * !USE_NATIVE, "Symbol", {
// 19.4.2.1 Symbol.for(key)
for: function(key) {
return has(SymbolRegistry, key += "") ? SymbolRegistry[key] : SymbolRegistry[key] = $Symbol(key);
},
// 19.4.2.5 Symbol.keyFor(sym)
keyFor: function(key) {
if (isSymbol(key)) return keyOf(SymbolRegistry, key);
throw TypeError(key + " is not a symbol!");
},
useSetter: function() {
setter = !0;
},
useSimple: function() {
setter = !1;
}
}), $export($export.S + $export.F * !USE_NATIVE, "Object", {
// 19.1.2.2 Object.create(O [, Properties])
create: $create,
// 19.1.2.4 Object.defineProperty(O, P, Attributes)
defineProperty: $defineProperty,
// 19.1.2.3 Object.defineProperties(O, Properties)
defineProperties: $defineProperties,
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
// 19.1.2.7 Object.getOwnPropertyNames(O)
getOwnPropertyNames: $getOwnPropertyNames,
// 19.1.2.8 Object.getOwnPropertySymbols(O)
getOwnPropertySymbols: $getOwnPropertySymbols
}), // 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function() {
var S = $Symbol();
// MS Edge converts symbol values to JSON as {}
// WebKit converts symbol values to JSON as null
// V8 throws on boxed symbols
return "[null]" != _stringify([ S ]) || "{}" != _stringify({
a: S
}) || "{}" != _stringify(Object(S));
})), "JSON", {
stringify: function(it) {
if (void 0 !== it && !isSymbol(it)) {
for (// IE8 returns string on undefined
var replacer, $replacer, args = [ it ], i = 1; arguments.length > i; ) args.push(arguments[i++]);
return replacer = args[1], "function" == typeof replacer && ($replacer = replacer),
!$replacer && isArray(replacer) || (replacer = function(key, value) {
if ($replacer && (value = $replacer.call(this, key, value)), !isSymbol(value)) return value;
}), args[1] = replacer, _stringify.apply($JSON, args);
}
}
}), // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
$Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(19)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf),
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setToStringTag($Symbol, "Symbol"), // 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, "Math", !0), // 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, "JSON", !0);
}, /* 68 */
/***/
function(module, exports, __webpack_require__) {
var META = __webpack_require__(13)("meta"), isObject = __webpack_require__(22), has = __webpack_require__(9), setDesc = __webpack_require__(20).f, id = 0, isExtensible = Object.isExtensible || function() {
return !0;
}, FREEZE = !__webpack_require__(25)(function() {
return isExtensible(Object.preventExtensions({}));
}), setMeta = function(it) {
setDesc(it, META, {
value: {
i: "O" + ++id,
// object ID
w: {}
}
});
}, fastKey = function(it, create) {
// return primitive with prefix
if (!isObject(it)) return "symbol" == typeof it ? it : ("string" == typeof it ? "S" : "P") + it;
if (!has(it, META)) {
// can't set metadata to uncaught frozen object
if (!isExtensible(it)) return "F";
// not necessary to add metadata
if (!create) return "E";
// add missing metadata
setMeta(it);
}
return it[META].i;
}, getWeak = function(it, create) {
if (!has(it, META)) {
// can't set metadata to uncaught frozen object
if (!isExtensible(it)) return !0;
// not necessary to add metadata
if (!create) return !1;
// add missing metadata
setMeta(it);
}
return it[META].w;
}, onFreeze = function(it) {
return FREEZE && meta.NEED && isExtensible(it) && !has(it, META) && setMeta(it),
it;
}, meta = module.exports = {
KEY: META,
NEED: !1,
fastKey: fastKey,
getWeak: getWeak,
onFreeze: onFreeze
};
}, /* 69 */
/***/
function(module, exports, __webpack_require__) {
var global = __webpack_require__(12), core = __webpack_require__(16), LIBRARY = __webpack_require__(42), wksExt = __webpack_require__(64), defineProperty = __webpack_require__(20).f;
module.exports = function(name) {
var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
"_" == name.charAt(0) || name in $Symbol || defineProperty($Symbol, name, {
value: wksExt.f(name)
});
};
}, /* 70 */
/***/
function(module, exports, __webpack_require__) {
var getKeys = __webpack_require__(48), toIObject = __webpack_require__(50);
module.exports = function(object, el) {
for (var key, O = toIObject(object), keys = getKeys(O), length = keys.length, index = 0; length > index; ) if (O[key = keys[index++]] === el) return key;
};
}, /* 71 */
/***/
function(module, exports, __webpack_require__) {
// all enumerable object keys, includes symbols
var getKeys = __webpack_require__(48), gOPS = __webpack_require__(72), pIE = __webpack_require__(73);
module.exports = function(it) {
var result = getKeys(it), getSymbols = gOPS.f;
if (getSymbols) for (var key, symbols = getSymbols(it), isEnum = pIE.f, i = 0; symbols.length > i; ) isEnum.call(it, key = symbols[i++]) && result.push(key);
return result;
};
}, /* 72 */
/***/
function(module, exports) {
exports.f = Object.getOwnPropertySymbols;
}, /* 73 */
/***/
function(module, exports) {
exports.f = {}.propertyIsEnumerable;
}, /* 74 */
/***/
function(module, exports, __webpack_require__) {
// 7.2.2 IsArray(argument)
var cof = __webpack_require__(52);
module.exports = Array.isArray || function(arg) {
return "Array" == cof(arg);
};
}, /* 75 */
/***/
function(module, exports, __webpack_require__) {
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = __webpack_require__(50), gOPN = __webpack_require__(76).f, toString = {}.toString, windowNames = "object" == typeof window && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : [], getWindowNames = function(it) {
try {
return gOPN(it);
} catch (e) {
return windowNames.slice();
}
};
module.exports.f = function(it) {
return windowNames && "[object Window]" == toString.call(it) ? getWindowNames(it) : gOPN(toIObject(it));
};
}, /* 76 */
/***/
function(module, exports, __webpack_require__) {
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var $keys = __webpack_require__(49), hiddenKeys = __webpack_require__(56).concat("length", "prototype");
exports.f = Object.getOwnPropertyNames || function(O) {
return $keys(O, hiddenKeys);
};
}, /* 77 */
/***/
function(module, exports, __webpack_require__) {
var pIE = __webpack_require__(73), createDesc = __webpack_require__(28), toIObject = __webpack_require__(50), toPrimitive = __webpack_require__(27), has = __webpack_require__(9), IE8_DOM_DEFINE = __webpack_require__(23), gOPD = Object.getOwnPropertyDescriptor;
exports.f = __webpack_require__(24) ? gOPD : function(O, P) {
if (O = toIObject(O), P = toPrimitive(P, !0), IE8_DOM_DEFINE) try {
return gOPD(O, P);
} catch (e) {}
if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]);
};
}, /* 78 */
/***/
function(module, exports) {}, /* 79 */
/***/
function(module, exports, __webpack_require__) {
__webpack_require__(69)("asyncIterator");
}, /* 80 */
/***/
function(module, exports, __webpack_require__) {
__webpack_require__(69)("observable");
}, /* 81 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
exports.__esModule = !0;
var _setPrototypeOf = __webpack_require__(82), _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf), _create = __webpack_require__(86), _create2 = _interopRequireDefault(_create), _typeof2 = __webpack_require__(35), _typeof3 = _interopRequireDefault(_typeof2);
exports.default = function(subClass, superClass) {
if ("function" != typeof superClass && null !== superClass) throw new TypeError("Super expression must either be null or a function, not " + ("undefined" == typeof superClass ? "undefined" : (0,
_typeof3.default)(superClass)));
subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: !1,
writable: !0,
configurable: !0
}
}), superClass && (_setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass);
};
}, /* 82 */
/***/
function(module, exports, __webpack_require__) {
module.exports = {
default: __webpack_require__(83),
__esModule: !0
};
}, /* 83 */
/***/
function(module, exports, __webpack_require__) {
__webpack_require__(84), module.exports = __webpack_require__(16).Object.setPrototypeOf;
}, /* 84 */
/***/
function(module, exports, __webpack_require__) {
// 19.1.3.19 Object.setPrototypeOf(O, proto)
var $export = __webpack_require__(15);
$export($export.S, "Object", {
setPrototypeOf: __webpack_require__(85).set
});
}, /* 85 */
/***/
function(module, exports, __webpack_require__) {
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var isObject = __webpack_require__(22), anObject = __webpack_require__(21), check = function(O, proto) {
if (anObject(O), !isObject(proto) && null !== proto) throw TypeError(proto + ": can't set as prototype!");
};
module.exports = {
set: Object.setPrototypeOf || ("__proto__" in {} ? // eslint-disable-line
function(test, buggy, set) {
try {
set = __webpack_require__(17)(Function.call, __webpack_require__(77).f(Object.prototype, "__proto__").set, 2),
set(test, []), buggy = !(test instanceof Array);
} catch (e) {
buggy = !0;
}
return function(O, proto) {
return check(O, proto), buggy ? O.__proto__ = proto : set(O, proto), O;
};
}({}, !1) : void 0),
check: check
};
}, /* 86 */
/***/
function(module, exports, __webpack_require__) {
module.exports = {
default: __webpack_require__(87),
__esModule: !0
};
}, /* 87 */
/***/
function(module, exports, __webpack_require__) {
__webpack_require__(88);
var $Object = __webpack_require__(16).Object;
module.exports = function(P, D) {
return $Object.create(P, D);
};
}, /* 88 */
/***/
function(module, exports, __webpack_require__) {
var $export = __webpack_require__(15);
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
$export($export.S, "Object", {
create: __webpack_require__(46)
});
}, /* 89 */
/***/
function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_89__;
}, /* 90 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _AutoSizer = __webpack_require__(91);
Object.defineProperty(exports, "default", {
enumerable: !0,
get: function() {
return _interopRequireDefault(_AutoSizer).default;
}
}), Object.defineProperty(exports, "AutoSizer", {
enumerable: !0,
get: function() {
return _interopRequireDefault(_AutoSizer).default;
}
});
}, /* 91 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _react = __webpack_require__(89), _react2 = _interopRequireDefault(_react), _detectElementResize = __webpack_require__(92), _detectElementResize2 = _interopRequireDefault(_detectElementResize), AutoSizer = function(_React$PureComponent) {
function AutoSizer() {
var _ref, _temp, _this, _ret;
(0, _classCallCheck3.default)(this, AutoSizer);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
return _temp = _this = (0, _possibleConstructorReturn3.default)(this, (_ref = AutoSizer.__proto__ || (0,
_getPrototypeOf2.default)(AutoSizer)).call.apply(_ref, [ this ].concat(args))),
_this.state = {
height: _this.props.defaultHeight || 0,
width: _this.props.defaultWidth || 0
}, _this._onResize = function() {
var _this$props = _this.props, disableHeight = _this$props.disableHeight, disableWidth = _this$props.disableWidth, onResize = _this$props.onResize;
if (_this._parentNode) {
var height = _this._parentNode.offsetHeight || 0, width = _this._parentNode.offsetWidth || 0, style = window.getComputedStyle(_this._parentNode) || {}, paddingLeft = parseInt(style.paddingLeft, 10) || 0, paddingRight = parseInt(style.paddingRight, 10) || 0, paddingTop = parseInt(style.paddingTop, 10) || 0, paddingBottom = parseInt(style.paddingBottom, 10) || 0, newHeight = height - paddingTop - paddingBottom, newWidth = width - paddingLeft - paddingRight;
(!disableHeight && _this.state.height !== newHeight || !disableWidth && _this.state.width !== newWidth) && (_this.setState({
height: height - paddingTop - paddingBottom,
width: width - paddingLeft - paddingRight
}), onResize({
height: height,
width: width
}));
}
}, _this._setRef = function(autoSizer) {
_this._autoSizer = autoSizer;
}, _ret = _temp, (0, _possibleConstructorReturn3.default)(_this, _ret);
}
return (0, _inherits3.default)(AutoSizer, _React$PureComponent), (0, _createClass3.default)(AutoSizer, [ {
key: "componentDidMount",
value: function() {
var nonce = this.props.nonce;
this._autoSizer && this._autoSizer.parentNode instanceof HTMLElement && (this._parentNode = this._autoSizer.parentNode,
this._detectElementResize = (0, _detectElementResize2.default)(nonce), this._detectElementResize.addResizeListener(this._parentNode, this._onResize),
this._onResize());
}
}, {
key: "componentWillUnmount",
value: function() {
this._detectElementResize && this._parentNode && this._detectElementResize.removeResizeListener(this._parentNode, this._onResize);
}
}, {
key: "render",
value: function() {
var _props = this.props, children = _props.children, disableHeight = _props.disableHeight, disableWidth = _props.disableWidth, _state = this.state, height = _state.height, width = _state.width, outerStyle = {
overflow: "visible"
}, childParams = {};
return disableHeight || (outerStyle.height = 0, childParams.height = height), disableWidth || (outerStyle.width = 0,
childParams.width = width), _react2.default.createElement("div", {
ref: this._setRef,
style: outerStyle
}, children(childParams));
}
} ]), AutoSizer;
}(_react2.default.PureComponent);
AutoSizer.defaultProps = {
onResize: function() {},
disableHeight: !1,
disableWidth: !1
}, exports.default = AutoSizer;
}, /* 92 */
/***/
function(module, exports) {
"use strict";
function createDetectElementResize(nonce) {
var _window;
_window = "undefined" != typeof window ? window : "undefined" != typeof self ? self : this;
var attachEvent = "undefined" != typeof document && document.attachEvent;
if (!attachEvent) {
var requestFrame = function() {
var raf = _window.requestAnimationFrame || _window.mozRequestAnimationFrame || _window.webkitRequestAnimationFrame || function(fn) {
return _window.setTimeout(fn, 20);
};
return function(fn) {
return raf(fn);
};
}(), cancelFrame = function() {
var cancel = _window.cancelAnimationFrame || _window.mozCancelAnimationFrame || _window.webkitCancelAnimationFrame || _window.clearTimeout;
return function(id) {
return cancel(id);
};
}(), resetTriggers = function(element) {
var triggers = element.__resizeTriggers__, expand = triggers.firstElementChild, contract = triggers.lastElementChild, expandChild = expand.firstElementChild;
contract.scrollLeft = contract.scrollWidth, contract.scrollTop = contract.scrollHeight,
expandChild.style.width = expand.offsetWidth + 1 + "px", expandChild.style.height = expand.offsetHeight + 1 + "px",
expand.scrollLeft = expand.scrollWidth, expand.scrollTop = expand.scrollHeight;
}, checkTriggers = function(element) {
return element.offsetWidth != element.__resizeLast__.width || element.offsetHeight != element.__resizeLast__.height;
}, scrollListener = function(e) {
if (!(e.target.className.indexOf("contract-trigger") < 0 && e.target.className.indexOf("expand-trigger") < 0)) {
var element = this;
resetTriggers(this), this.__resizeRAF__ && cancelFrame(this.__resizeRAF__), this.__resizeRAF__ = requestFrame(function() {
checkTriggers(element) && (element.__resizeLast__.width = element.offsetWidth, element.__resizeLast__.height = element.offsetHeight,
element.__resizeListeners__.forEach(function(fn) {
fn.call(element, e);
}));
});
}
}, animation = !1, keyframeprefix = "", animationstartevent = "animationstart", domPrefixes = "Webkit Moz O ms".split(" "), startEvents = "webkitAnimationStart animationstart oAnimationStart MSAnimationStart".split(" "), pfx = "", elm = document.createElement("fakeelement");
if (void 0 !== elm.style.animationName && (animation = !0), animation === !1) for (var i = 0; i < domPrefixes.length; i++) if (void 0 !== elm.style[domPrefixes[i] + "AnimationName"]) {
pfx = domPrefixes[i], keyframeprefix = "-" + pfx.toLowerCase() + "-", animationstartevent = startEvents[i],
animation = !0;
break;
}
var animationName = "resizeanim", animationKeyframes = "@" + keyframeprefix + "keyframes " + animationName + " { from { opacity: 0; } to { opacity: 0; } } ", animationStyle = keyframeprefix + "animation: 1ms " + animationName + "; ";
}
var createStyles = function() {
if (!document.getElementById("detectElementResize")) {
var css = (animationKeyframes ? animationKeyframes : "") + ".resize-triggers { " + (animationStyle ? animationStyle : "") + '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; z-index: -1; } .resize-triggers > div { background: #eee; overflow: auto; } .contract-trigger:before { width: 200%; height: 200%; }', head = document.head || document.getElementsByTagName("head")[0], style = document.createElement("style");
style.id = "detectElementResize", style.type = "text/css", null != nonce && style.setAttribute("nonce", nonce),
style.styleSheet ? style.styleSheet.cssText = css : style.appendChild(document.createTextNode(css)),
head.appendChild(style);
}
}, addResizeListener = function(element, fn) {
if (attachEvent) element.attachEvent("onresize", fn); else {
if (!element.__resizeTriggers__) {
var elementStyle = _window.getComputedStyle(element);
elementStyle && "static" == elementStyle.position && (element.style.position = "relative"),
createStyles(), element.__resizeLast__ = {}, element.__resizeListeners__ = [], (element.__resizeTriggers__ = document.createElement("div")).className = "resize-triggers",
element.__resizeTriggers__.innerHTML = '<div class="expand-trigger"><div></div></div><div class="contract-trigger"></div>',
element.appendChild(element.__resizeTriggers__), resetTriggers(element), element.addEventListener("scroll", scrollListener, !0),
animationstartevent && (element.__resizeTriggers__.__animationListener__ = function(e) {
e.animationName == animationName && resetTriggers(element);
}, element.__resizeTriggers__.addEventListener(animationstartevent, element.__resizeTriggers__.__animationListener__));
}
element.__resizeListeners__.push(fn);
}
}, removeResizeListener = function(element, fn) {
if (attachEvent) element.detachEvent("onresize", fn); else if (element.__resizeListeners__.splice(element.__resizeListeners__.indexOf(fn), 1),
!element.__resizeListeners__.length) {
element.removeEventListener("scroll", scrollListener, !0), element.__resizeTriggers__.__animationListener__ && (element.__resizeTriggers__.removeEventListener(animationstartevent, element.__resizeTriggers__.__animationListener__),
element.__resizeTriggers__.__animationListener__ = null);
try {
element.__resizeTriggers__ = !element.removeChild(element.__resizeTriggers__);
} catch (e) {}
}
};
return {
addResizeListener: addResizeListener,
removeResizeListener: removeResizeListener
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.default = createDetectElementResize;
}, /* 93 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.CellMeasurerCache = exports.CellMeasurer = void 0;
var _CellMeasurer = __webpack_require__(94), _CellMeasurer2 = _interopRequireDefault(_CellMeasurer), _CellMeasurerCache = __webpack_require__(97), _CellMeasurerCache2 = _interopRequireDefault(_CellMeasurerCache);
exports.default = _CellMeasurer2.default, exports.CellMeasurer = _CellMeasurer2.default,
exports.CellMeasurerCache = _CellMeasurerCache2.default;
}, /* 94 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _react = __webpack_require__(89), _react2 = _interopRequireDefault(_react), _reactDom = __webpack_require__(96), _CellMeasurerCache = __webpack_require__(97), CellMeasurer = (_interopRequireDefault(_CellMeasurerCache),
function(_React$PureComponent) {
function CellMeasurer() {
var _ref, _temp, _this, _ret;
(0, _classCallCheck3.default)(this, CellMeasurer);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
return _temp = _this = (0, _possibleConstructorReturn3.default)(this, (_ref = CellMeasurer.__proto__ || (0,
_getPrototypeOf2.default)(CellMeasurer)).call.apply(_ref, [ this ].concat(args))),
_this._measure = function() {
var _this$props = _this.props, cache = _this$props.cache, _this$props$columnInd = _this$props.columnIndex, columnIndex = void 0 === _this$props$columnInd ? 0 : _this$props$columnInd, parent = _this$props.parent, _this$props$rowIndex = _this$props.rowIndex, rowIndex = void 0 === _this$props$rowIndex ? _this.props.index || 0 : _this$props$rowIndex, _this$_getCellMeasure = _this._getCellMeasurements(), height = _this$_getCellMeasure.height, width = _this$_getCellMeasure.width;
height === cache.getHeight(rowIndex, columnIndex) && width === cache.getWidth(rowIndex, columnIndex) || (cache.set(rowIndex, columnIndex, width, height),
parent && "function" == typeof parent.recomputeGridSize && parent.recomputeGridSize({
columnIndex: columnIndex,
rowIndex: rowIndex
}));
}, _ret = _temp, (0, _possibleConstructorReturn3.default)(_this, _ret);
}
return (0, _inherits3.default)(CellMeasurer, _React$PureComponent), (0, _createClass3.default)(CellMeasurer, [ {
key: "componentDidMount",
value: function() {
this._maybeMeasureCell();
}
}, {
key: "componentDidUpdate",
value: function() {
this._maybeMeasureCell();
}
}, {
key: "render",
value: function() {
var children = this.props.children;
return "function" == typeof children ? children({
measure: this._measure
}) : children;
}
}, {
key: "_getCellMeasurements",
value: function() {
var cache = this.props.cache, node = (0, _reactDom.findDOMNode)(this);
if (node instanceof HTMLElement) {
var styleWidth = node.style.width, styleHeight = node.style.height;
cache.hasFixedWidth() || (node.style.width = "auto"), cache.hasFixedHeight() || (node.style.height = "auto");
var height = Math.ceil(node.offsetHeight), width = Math.ceil(node.offsetWidth);
return styleWidth && (node.style.width = styleWidth), styleHeight && (node.style.height = styleHeight),
{
height: height,
width: width
};
}
return {
height: 0,
width: 0
};
}
}, {
key: "_maybeMeasureCell",
value: function() {
var _props = this.props, cache = _props.cache, _props$columnIndex = _props.columnIndex, columnIndex = void 0 === _props$columnIndex ? 0 : _props$columnIndex, parent = _props.parent, _props$rowIndex = _props.rowIndex, rowIndex = void 0 === _props$rowIndex ? this.props.index || 0 : _props$rowIndex;
if (!cache.has(rowIndex, columnIndex)) {
var _getCellMeasurements2 = this._getCellMeasurements(), height = _getCellMeasurements2.height, width = _getCellMeasurements2.width;
cache.set(rowIndex, columnIndex, width, height), parent && "function" == typeof parent.invalidateCellSizeAfterRender && parent.invalidateCellSizeAfterRender({
columnIndex: columnIndex,
rowIndex: rowIndex
});
}
}
} ]), CellMeasurer;
}(_react2.default.PureComponent));
CellMeasurer.__internalCellMeasurerFlag = !1, exports.default = CellMeasurer, "production" !== process.env.NODE_ENV && (CellMeasurer.__internalCellMeasurerFlag = !0);
}).call(exports, __webpack_require__(95));
}, /* 95 */
/***/
function(module, exports) {
function defaultSetTimout() {
throw new Error("setTimeout has not been defined");
}
function defaultClearTimeout() {
throw new Error("clearTimeout has not been defined");
}
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) return cachedSetTimeout = setTimeout,
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) return cachedClearTimeout = clearTimeout,
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);
}
}
}
function cleanUpNextTick() {
draining && currentQueue && (draining = !1, currentQueue.length ? queue = currentQueue.concat(queue) : queueIndex = -1,
queue.length && drainQueue());
}
function drainQueue() {
if (!draining) {
var timeout = runTimeout(cleanUpNextTick);
draining = !0;
for (var len = queue.length; len; ) {
for (currentQueue = queue, queue = []; ++queueIndex < len; ) currentQueue && currentQueue[queueIndex].run();
queueIndex = -1, len = queue.length;
}
currentQueue = null, draining = !1, runClearTimeout(timeout);
}
}
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun, this.array = array;
}
function noop() {}
// shim for using process in browser
var cachedSetTimeout, cachedClearTimeout, process = module.exports = {};
!function() {
try {
cachedSetTimeout = "function" == typeof setTimeout ? setTimeout : defaultSetTimout;
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
cachedClearTimeout = "function" == typeof clearTimeout ? clearTimeout : defaultClearTimeout;
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
}();
var currentQueue, queue = [], draining = !1, queueIndex = -1;
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)), 1 !== queue.length || draining || runTimeout(drainQueue);
}, Item.prototype.run = function() {
this.fun.apply(null, this.array);
}, process.title = "browser", process.browser = !0, process.env = {}, process.argv = [],
process.version = "", // empty string to avoid regexp issues
process.versions = {}, 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;
};
}, /* 96 */
/***/
function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_96__;
}, /* 97 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function defaultKeyMapper(rowIndex, columnIndex) {
return rowIndex + "-" + columnIndex;
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.DEFAULT_WIDTH = exports.DEFAULT_HEIGHT = void 0;
var _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), DEFAULT_HEIGHT = exports.DEFAULT_HEIGHT = 30, DEFAULT_WIDTH = exports.DEFAULT_WIDTH = 100, CellMeasurerCache = function() {
function CellMeasurerCache() {
var _this = this, params = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
(0, _classCallCheck3.default)(this, CellMeasurerCache), this._cellHeightCache = {},
this._cellWidthCache = {}, this._columnWidthCache = {}, this._rowHeightCache = {},
this._columnCount = 0, this._rowCount = 0, this.columnWidth = function(_ref) {
var index = _ref.index, key = _this._keyMapper(0, index);
return _this._columnWidthCache.hasOwnProperty(key) ? _this._columnWidthCache[key] : _this._defaultWidth;
}, this.rowHeight = function(_ref2) {
var index = _ref2.index, key = _this._keyMapper(index, 0);
return _this._rowHeightCache.hasOwnProperty(key) ? _this._rowHeightCache[key] : _this._defaultHeight;
};
var defaultHeight = params.defaultHeight, defaultWidth = params.defaultWidth, fixedHeight = params.fixedHeight, fixedWidth = params.fixedWidth, keyMapper = params.keyMapper, minHeight = params.minHeight, minWidth = params.minWidth;
this._hasFixedHeight = fixedHeight === !0, this._hasFixedWidth = fixedWidth === !0,
this._minHeight = minHeight || 0, this._minWidth = minWidth || 0, this._keyMapper = keyMapper || defaultKeyMapper,
this._defaultHeight = Math.max(this._minHeight, "number" == typeof defaultHeight ? defaultHeight : DEFAULT_HEIGHT),
this._defaultWidth = Math.max(this._minWidth, "number" == typeof defaultWidth ? defaultWidth : DEFAULT_WIDTH),
"production" !== process.env.NODE_ENV && (this._hasFixedHeight === !1 && this._hasFixedWidth === !1 && console.warn("CellMeasurerCache should only measure a cell's width or height. You have configured CellMeasurerCache to measure both. This will result in poor performance."),
this._hasFixedHeight === !1 && 0 === this._defaultHeight && console.warn("Fixed height CellMeasurerCache should specify a :defaultHeight greater than 0. Failing to do so will lead to unnecessary layout and poor performance."),
this._hasFixedWidth === !1 && 0 === this._defaultWidth && console.warn("Fixed width CellMeasurerCache should specify a :defaultWidth greater than 0. Failing to do so will lead to unnecessary layout and poor performance."));
}
return (0, _createClass3.default)(CellMeasurerCache, [ {
key: "clear",
value: function(rowIndex) {
var columnIndex = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0, key = this._keyMapper(rowIndex, columnIndex);
delete this._cellHeightCache[key], delete this._cellWidthCache[key], this._updateCachedColumnAndRowSizes(rowIndex, columnIndex);
}
}, {
key: "clearAll",
value: function() {
this._cellHeightCache = {}, this._cellWidthCache = {}, this._columnWidthCache = {},
this._rowHeightCache = {}, this._rowCount = 0, this._columnCount = 0;
}
}, {
key: "hasFixedHeight",
value: function() {
return this._hasFixedHeight;
}
}, {
key: "hasFixedWidth",
value: function() {
return this._hasFixedWidth;
}
}, {
key: "getHeight",
value: function(rowIndex) {
var columnIndex = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0;
if (this._hasFixedHeight) return this._defaultHeight;
var _key = this._keyMapper(rowIndex, columnIndex);
return this._cellHeightCache.hasOwnProperty(_key) ? Math.max(this._minHeight, this._cellHeightCache[_key]) : this._defaultHeight;
}
}, {
key: "getWidth",
value: function(rowIndex) {
var columnIndex = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0;
if (this._hasFixedWidth) return this._defaultWidth;
var _key2 = this._keyMapper(rowIndex, columnIndex);
return this._cellWidthCache.hasOwnProperty(_key2) ? Math.max(this._minWidth, this._cellWidthCache[_key2]) : this._defaultWidth;
}
}, {
key: "has",
value: function(rowIndex) {
var columnIndex = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0, key = this._keyMapper(rowIndex, columnIndex);
return this._cellHeightCache.hasOwnProperty(key);
}
}, {
key: "set",
value: function(rowIndex, columnIndex, width, height) {
var key = this._keyMapper(rowIndex, columnIndex);
columnIndex >= this._columnCount && (this._columnCount = columnIndex + 1), rowIndex >= this._rowCount && (this._rowCount = rowIndex + 1),
this._cellHeightCache[key] = height, this._cellWidthCache[key] = width, this._updateCachedColumnAndRowSizes(rowIndex, columnIndex);
}
}, {
key: "_updateCachedColumnAndRowSizes",
value: function(rowIndex, columnIndex) {
if (!this._hasFixedWidth) {
for (var columnWidth = 0, i = 0; i < this._rowCount; i++) columnWidth = Math.max(columnWidth, this.getWidth(i, columnIndex));
var columnKey = this._keyMapper(0, columnIndex);
this._columnWidthCache[columnKey] = columnWidth;
}
if (!this._hasFixedHeight) {
for (var rowHeight = 0, _i = 0; _i < this._columnCount; _i++) rowHeight = Math.max(rowHeight, this.getHeight(rowIndex, _i));
var rowKey = this._keyMapper(rowIndex, 0);
this._rowHeightCache[rowKey] = rowHeight;
}
}
}, {
key: "defaultHeight",
get: function() {
return this._defaultHeight;
}
}, {
key: "defaultWidth",
get: function() {
return this._defaultWidth;
}
} ]), CellMeasurerCache;
}();
exports.default = CellMeasurerCache;
}).call(exports, __webpack_require__(95));
}, /* 98 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.Collection = void 0;
var _Collection = __webpack_require__(99), _Collection2 = _interopRequireDefault(_Collection);
exports.default = _Collection2.default, exports.Collection = _Collection2.default;
}, /* 99 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function defaultCellGroupRenderer(_ref4) {
var cellCache = _ref4.cellCache, cellRenderer = _ref4.cellRenderer, cellSizeAndPositionGetter = _ref4.cellSizeAndPositionGetter, indices = _ref4.indices, isScrolling = _ref4.isScrolling;
return indices.map(function(index) {
var cellMetadata = cellSizeAndPositionGetter({
index: index
}), cellRendererProps = {
index: index,
isScrolling: isScrolling,
key: index,
style: {
height: cellMetadata.height,
left: cellMetadata.x,
position: "absolute",
top: cellMetadata.y,
width: cellMetadata.width
}
};
return isScrolling ? (index in cellCache || (cellCache[index] = cellRenderer(cellRendererProps)),
cellCache[index]) : cellRenderer(cellRendererProps);
}).filter(function(renderedCell) {
return !!renderedCell;
});
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _extends2 = __webpack_require__(100), _extends3 = _interopRequireDefault(_extends2), _objectWithoutProperties2 = __webpack_require__(105), _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2), _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _propTypes = __webpack_require__(106), _propTypes2 = _interopRequireDefault(_propTypes), _react = __webpack_require__(89), _react2 = _interopRequireDefault(_react), _CollectionView = __webpack_require__(113), _CollectionView2 = _interopRequireDefault(_CollectionView), _calculateSizeAndPositionData2 = __webpack_require__(121), _calculateSizeAndPositionData3 = _interopRequireDefault(_calculateSizeAndPositionData2), _getUpdatedOffsetForIndex = __webpack_require__(124), _getUpdatedOffsetForIndex2 = _interopRequireDefault(_getUpdatedOffsetForIndex), Collection = function(_PureComponent) {
function Collection(props, context) {
(0, _classCallCheck3.default)(this, Collection);
var _this = (0, _possibleConstructorReturn3.default)(this, (Collection.__proto__ || (0,
_getPrototypeOf2.default)(Collection)).call(this, props, context));
return _this._cellMetadata = [], _this._lastRenderedCellIndices = [], _this._cellCache = [],
_this._isScrollingChange = _this._isScrollingChange.bind(_this), _this._setCollectionViewRef = _this._setCollectionViewRef.bind(_this),
_this;
}
return (0, _inherits3.default)(Collection, _PureComponent), (0, _createClass3.default)(Collection, [ {
key: "forceUpdate",
value: function() {
void 0 !== this._collectionView && this._collectionView.forceUpdate();
}
}, {
key: "recomputeCellSizesAndPositions",
value: function() {
this._cellCache = [], this._collectionView.recomputeCellSizesAndPositions();
}
}, {
key: "render",
value: function() {
var props = (0, _objectWithoutProperties3.default)(this.props, []);
return _react2.default.createElement(_CollectionView2.default, (0, _extends3.default)({
cellLayoutManager: this,
isScrollingChange: this._isScrollingChange,
ref: this._setCollectionViewRef
}, props));
}
}, {
key: "calculateSizeAndPositionData",
value: function() {
var _props = this.props, cellCount = _props.cellCount, cellSizeAndPositionGetter = _props.cellSizeAndPositionGetter, sectionSize = _props.sectionSize, data = (0,
_calculateSizeAndPositionData3.default)({
cellCount: cellCount,
cellSizeAndPositionGetter: cellSizeAndPositionGetter,
sectionSize: sectionSize
});
this._cellMetadata = data.cellMetadata, this._sectionManager = data.sectionManager,
this._height = data.height, this._width = data.width;
}
}, {
key: "getLastRenderedIndices",
value: function() {
return this._lastRenderedCellIndices;
}
}, {
key: "getScrollPositionForCell",
value: function(_ref) {
var align = _ref.align, cellIndex = _ref.cellIndex, height = _ref.height, scrollLeft = _ref.scrollLeft, scrollTop = _ref.scrollTop, width = _ref.width, cellCount = this.props.cellCount;
if (cellIndex >= 0 && cellIndex < cellCount) {
var cellMetadata = this._cellMetadata[cellIndex];
scrollLeft = (0, _getUpdatedOffsetForIndex2.default)({
align: align,
cellOffset: cellMetadata.x,
cellSize: cellMetadata.width,
containerSize: width,
currentOffset: scrollLeft,
targetIndex: cellIndex
}), scrollTop = (0, _getUpdatedOffsetForIndex2.default)({
align: align,
cellOffset: cellMetadata.y,
cellSize: cellMetadata.height,
containerSize: height,
currentOffset: scrollTop,
targetIndex: cellIndex
});
}
return {
scrollLeft: scrollLeft,
scrollTop: scrollTop
};
}
}, {
key: "getTotalSize",
value: function() {
return {
height: this._height,
width: this._width
};
}
}, {
key: "cellRenderers",
value: function(_ref2) {
var _this2 = this, height = _ref2.height, isScrolling = _ref2.isScrolling, width = _ref2.width, x = _ref2.x, y = _ref2.y, _props2 = this.props, cellGroupRenderer = _props2.cellGroupRenderer, cellRenderer = _props2.cellRenderer;
return this._lastRenderedCellIndices = this._sectionManager.getCellIndices({
height: height,
width: width,
x: x,
y: y
}), cellGroupRenderer({
cellCache: this._cellCache,
cellRenderer: cellRenderer,
cellSizeAndPositionGetter: function(_ref3) {
var index = _ref3.index;
return _this2._sectionManager.getCellMetadata({
index: index
});
},
indices: this._lastRenderedCellIndices,
isScrolling: isScrolling
});
}
}, {
key: "_isScrollingChange",
value: function(isScrolling) {
isScrolling || (this._cellCache = []);
}
}, {
key: "_setCollectionViewRef",
value: function(ref) {
this._collectionView = ref;
}
} ]), Collection;
}(_react.PureComponent);
Collection.propTypes = {
"aria-label": _propTypes2.default.string,
cellCount: _propTypes2.default.number.isRequired,
cellGroupRenderer: _propTypes2.default.func.isRequired,
cellRenderer: _propTypes2.default.func.isRequired,
cellSizeAndPositionGetter: _propTypes2.default.func.isRequired,
sectionSize: _propTypes2.default.number
}, Collection.defaultProps = {
"aria-label": "grid",
cellGroupRenderer: defaultCellGroupRenderer
}, exports.default = Collection;
}, /* 100 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
exports.__esModule = !0;
var _assign = __webpack_require__(101), _assign2 = _interopRequireDefault(_assign);
exports.default = _assign2.default || function(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]);
}
return target;
};
}, /* 101 */
/***/
function(module, exports, __webpack_require__) {
module.exports = {
default: __webpack_require__(102),
__esModule: !0
};
}, /* 102 */
/***/
function(module, exports, __webpack_require__) {
__webpack_require__(103), module.exports = __webpack_require__(16).Object.assign;
}, /* 103 */
/***/
function(module, exports, __webpack_require__) {
// 19.1.3.1 Object.assign(target, source)
var $export = __webpack_require__(15);
$export($export.S + $export.F, "Object", {
assign: __webpack_require__(104)
});
}, /* 104 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
// 19.1.2.1 Object.assign(target, source, ...)
var getKeys = __webpack_require__(48), gOPS = __webpack_require__(72), pIE = __webpack_require__(73), toObject = __webpack_require__(6), IObject = __webpack_require__(51), $assign = Object.assign;
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || __webpack_require__(25)(function() {
var A = {}, B = {}, S = Symbol(), K = "abcdefghijklmnopqrst";
return A[S] = 7, K.split("").forEach(function(k) {
B[k] = k;
}), 7 != $assign({}, A)[S] || Object.keys($assign({}, B)).join("") != K;
}) ? function(target, source) {
for (// eslint-disable-line no-unused-vars
var T = toObject(target), aLen = arguments.length, index = 1, getSymbols = gOPS.f, isEnum = pIE.f; aLen > index; ) for (var key, S = IObject(arguments[index++]), keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S), length = keys.length, j = 0; length > j; ) isEnum.call(S, key = keys[j++]) && (T[key] = S[key]);
return T;
} : $assign;
}, /* 105 */
/***/
function(module, exports) {
"use strict";
exports.__esModule = !0, exports.default = function(obj, keys) {
var target = {};
for (var i in obj) keys.indexOf(i) >= 0 || Object.prototype.hasOwnProperty.call(obj, i) && (target[i] = obj[i]);
return target;
};
}, /* 106 */
/***/
function(module, exports, __webpack_require__) {
function isValidElement(object) {
return "object" == typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE;
}
/**
* 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.
*/
var factory = __webpack_require__(107), REACT_ELEMENT_TYPE = "function" == typeof Symbol && Symbol.for && Symbol.for("react.element") || 60103;
module.exports = factory(isValidElement);
}, /* 107 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* 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.
*/
"use strict";
var emptyFunction = __webpack_require__(108), invariant = __webpack_require__(109), warning = __webpack_require__(110), ReactPropTypesSecret = __webpack_require__(111), checkPropTypes = __webpack_require__(112);
module.exports = function(isValidElement) {
// Before Symbol spec.
/**
* Returns the iterator method function contained on the iterable object.
*
* Be sure to invoke the function with the iterable as context:
*
* var iteratorFn = getIteratorFn(myIterable);
* if (iteratorFn) {
* var iterator = iteratorFn.call(myIterable);
* ...
* }
*
* @param {?object} maybeIterable
* @return {?function}
*/
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if ("function" == typeof iteratorFn) return iteratorFn;
}
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
/*eslint-disable no-self-compare*/
function is(x, y) {
// SameValue algorithm
// SameValue algorithm
return x === y ? 0 !== x || 1 / x === 1 / y : x !== x && y !== y;
}
/*eslint-enable no-self-compare*/
/**
* We use an Error-like object for backward compatibility as people may call
* PropTypes directly and inspect their output. However, we don't use real
* Errors anymore. We don't inspect their stack anyway, and creating them
* is prohibitively expensive if they are created too often, such as what
* happens in oneOfType() for any type before the one that matched.
*/
function PropTypeError(message) {
this.message = message, this.stack = "";
}
function createChainableTypeChecker(validate) {
function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
if (componentName = componentName || ANONYMOUS, propFullName = propFullName || propName,
"production" !== process.env.NODE_ENV && secret !== ReactPropTypesSecret && "undefined" != typeof console) {
var cacheKey = componentName + ":" + propName;
manualPropTypeCallCache[cacheKey] || ("production" !== process.env.NODE_ENV ? warning(!1, "You are manually calling a React.PropTypes validation function for the `%s` prop on `%s`. This is deprecated and will not work in production with the next major version. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details.", propFullName, componentName) : void 0,
manualPropTypeCallCache[cacheKey] = !0);
}
return null == props[propName] ? isRequired ? new PropTypeError(null === props[propName] ? "The " + location + " `" + propFullName + "` is marked as required " + ("in `" + componentName + "`, but its value is `null`.") : "The " + location + " `" + propFullName + "` is marked as required in " + ("`" + componentName + "`, but its value is `undefined`.")) : null : validate(props, propName, componentName, location, propFullName);
}
if ("production" !== process.env.NODE_ENV) var manualPropTypeCallCache = {};
var chainedCheckType = checkType.bind(null, !1);
return chainedCheckType.isRequired = checkType.bind(null, !0), chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location, propFullName, secret) {
var propValue = props[propName], propType = getPropType(propValue);
if (propType !== expectedType) {
// `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 PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + preciseType + "` supplied to `" + componentName + "`, expected ") + ("`" + expectedType + "`."));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunction.thatReturnsNull);
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if ("function" != typeof typeChecker) return new PropTypeError("Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside arrayOf.");
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected an array."));
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location, propFullName + "[" + i + "]", ReactPropTypesSecret);
if (error instanceof Error) return error;
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!isValidElement(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected a single ReactElement."));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location, propFullName) {
if (!(props[propName] instanceof expectedClass)) {
var expectedClassName = expectedClass.name || ANONYMOUS, actualClassName = getClassName(props[propName]);
return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + actualClassName + "` supplied to `" + componentName + "`, expected ") + ("instance of `" + expectedClassName + "`."));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
function validate(props, propName, componentName, location, propFullName) {
for (var propValue = props[propName], i = 0; i < expectedValues.length; i++) if (is(propValue, expectedValues[i])) return null;
var valuesString = JSON.stringify(expectedValues);
return new PropTypeError("Invalid " + location + " `" + propFullName + "` of value `" + propValue + "` " + ("supplied to `" + componentName + "`, expected one of " + valuesString + "."));
}
return Array.isArray(expectedValues) ? createChainableTypeChecker(validate) : ("production" !== process.env.NODE_ENV ? warning(!1, "Invalid argument supplied to oneOf, expected an instance of array.") : void 0,
emptyFunction.thatReturnsNull);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if ("function" != typeof typeChecker) return new PropTypeError("Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside objectOf.");
var propValue = props[propName], propType = getPropType(propValue);
if ("object" !== propType) return new PropTypeError("Invalid " + location + " `" + propFullName + "` 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, propFullName + "." + key, ReactPropTypesSecret);
if (error instanceof Error) return error;
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
function validate(props, propName, componentName, location, propFullName) {
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (null == checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret)) return null;
}
return new PropTypeError("Invalid " + location + " `" + propFullName + "` supplied to " + ("`" + componentName + "`."));
}
return Array.isArray(arrayOfTypeCheckers) ? createChainableTypeChecker(validate) : ("production" !== process.env.NODE_ENV ? warning(!1, "Invalid argument supplied to oneOfType, expected an instance of array.") : void 0,
emptyFunction.thatReturnsNull);
}
function createNodeChecker() {
function validate(props, propName, componentName, location, propFullName) {
return isNode(props[propName]) ? null : new PropTypeError("Invalid " + location + " `" + propFullName + "` supplied to " + ("`" + componentName + "`, expected a ReactNode."));
}
return createChainableTypeChecker(validate);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName], propType = getPropType(propValue);
if ("object" !== propType) return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type `" + propType + "` " + ("supplied to `" + componentName + "`, expected `object`."));
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (checker) {
var error = checker(propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret);
if (error) return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case "number":
case "string":
case "undefined":
return !0;
case "boolean":
return !propValue;
case "object":
if (Array.isArray(propValue)) return propValue.every(isNode);
if (null === propValue || isValidElement(propValue)) return !0;
var iteratorFn = getIteratorFn(propValue);
if (!iteratorFn) return !1;
var step, iterator = iteratorFn.call(propValue);
if (iteratorFn !== propValue.entries) {
for (;!(step = iterator.next()).done; ) if (!isNode(step.value)) return !1;
} else // Iterator will provide entry [k,v] tuples rather than values.
for (;!(step = iterator.next()).done; ) {
var entry = step.value;
if (entry && !isNode(entry[1])) return !1;
}
return !0;
default:
return !1;
}
}
function isSymbol(propType, propValue) {
// Native Symbol.
// Native Symbol.
// 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
return "symbol" === propType || ("Symbol" === propValue["@@toStringTag"] || "function" == typeof Symbol && propValue instanceof Symbol);
}
// Equivalent of `typeof` but with special handling for array and regexp.
function getPropType(propValue) {
var propType = typeof propValue;
return Array.isArray(propValue) ? "array" : propValue instanceof RegExp ? "object" : isSymbol(propType, propValue) ? "symbol" : propType;
}
// This handles more types than `getPropType`. Only used for error messages.
// See `createPrimitiveTypeChecker`.
function getPreciseType(propValue) {
var propType = getPropType(propValue);
if ("object" === propType) {
if (propValue instanceof Date) return "date";
if (propValue instanceof RegExp) return "regexp";
}
return propType;
}
// Returns class name of the object, if any.
function getClassName(propValue) {
return propValue.constructor && propValue.constructor.name ? propValue.constructor.name : ANONYMOUS;
}
/* global Symbol */
var ReactPropTypes, ITERATOR_SYMBOL = "function" == typeof Symbol && Symbol.iterator, FAUX_ITERATOR_SYMBOL = "@@iterator", ANONYMOUS = "<<anonymous>>";
if ("production" !== process.env.NODE_ENV) // Keep in sync with production version below
ReactPropTypes = {
array: createPrimitiveTypeChecker("array"),
bool: createPrimitiveTypeChecker("boolean"),
func: createPrimitiveTypeChecker("function"),
number: createPrimitiveTypeChecker("number"),
object: createPrimitiveTypeChecker("object"),
string: createPrimitiveTypeChecker("string"),
symbol: createPrimitiveTypeChecker("symbol"),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker
}; else {
var productionTypeChecker = function() {
invariant(!1, "React.PropTypes type checking code is stripped in production.");
};
productionTypeChecker.isRequired = productionTypeChecker;
var getProductionTypeChecker = function() {
return productionTypeChecker;
};
// Keep in sync with development version above
ReactPropTypes = {
array: productionTypeChecker,
bool: productionTypeChecker,
func: productionTypeChecker,
number: productionTypeChecker,
object: productionTypeChecker,
string: productionTypeChecker,
symbol: productionTypeChecker,
any: productionTypeChecker,
arrayOf: getProductionTypeChecker,
element: productionTypeChecker,
instanceOf: getProductionTypeChecker,
node: productionTypeChecker,
objectOf: getProductionTypeChecker,
oneOf: getProductionTypeChecker,
oneOfType: getProductionTypeChecker,
shape: getProductionTypeChecker
};
}
// Make `instanceof Error` still work for returned errors.
return PropTypeError.prototype = Error.prototype, ReactPropTypes.checkPropTypes = checkPropTypes,
ReactPropTypes.PropTypes = ReactPropTypes, ReactPropTypes;
};
}).call(exports, __webpack_require__(95));
}, /* 108 */
/***/
function(module, exports) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
function makeEmptyFunction(arg) {
return function() {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
var emptyFunction = function() {};
emptyFunction.thatReturns = makeEmptyFunction, emptyFunction.thatReturnsFalse = makeEmptyFunction(!1),
emptyFunction.thatReturnsTrue = makeEmptyFunction(!0), emptyFunction.thatReturnsNull = makeEmptyFunction(null),
emptyFunction.thatReturnsThis = function() {
return this;
}, emptyFunction.thatReturnsArgument = function(arg) {
return arg;
}, module.exports = emptyFunction;
}, /* 109 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
"use strict";
function invariant(condition, format, a, b, c, d, e, f) {
if (validateFormat(format), !condition) {
var error;
if (void 0 === format) error = new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings."); else {
var args = [ a, b, c, d, e, f ], argIndex = 0;
error = new Error(format.replace(/%s/g, function() {
return args[argIndex++];
})), error.name = "Invariant Violation";
}
// we don't care about invariant's own frame
throw error.framesToPop = 1, error;
}
}
/**
* 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 validateFormat = function(format) {};
"production" !== process.env.NODE_ENV && (validateFormat = function(format) {
if (void 0 === format) throw new Error("invariant requires an error message argument");
}), module.exports = invariant;
}).call(exports, __webpack_require__(95));
}, /* 110 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* 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";
var emptyFunction = __webpack_require__(108), warning = emptyFunction;
"production" !== process.env.NODE_ENV && !function() {
var printWarning = function(format) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) args[_key - 1] = arguments[_key];
var argIndex = 0, message = "Warning: " + format.replace(/%s/g, function() {
return args[argIndex++];
});
"undefined" != typeof console && console.error(message);
try {
// --- Welcome to debugging React ---
// 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) {}
};
warning = function(condition, format) {
if (void 0 === format) throw new Error("`warning(condition, format, ...args)` requires a warning message argument");
if (0 !== format.indexOf("Failed Composite propType: ") && !condition) {
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) args[_key2 - 2] = arguments[_key2];
printWarning.apply(void 0, [ format ].concat(args));
}
};
}(), module.exports = warning;
}).call(exports, __webpack_require__(95));
}, /* 111 */
/***/
function(module, exports) {
/**
* 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.
*/
"use strict";
var ReactPropTypesSecret = "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";
module.exports = ReactPropTypesSecret;
}, /* 112 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
/**
* 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.
*/
"use strict";
/**
* Assert that the values match with the type specs.
* Error messages are memorized and will only be shown once.
*
* @param {object} typeSpecs Map of name to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @param {string} componentName Name of the component for error messages.
* @param {?Function} getStack Returns the component stack.
* @private
*/
function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
if ("production" !== process.env.NODE_ENV) for (var typeSpecName in typeSpecs) if (typeSpecs.hasOwnProperty(typeSpecName)) {
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 {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
invariant("function" == typeof typeSpecs[typeSpecName], "%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.", componentName || "React class", location, typeSpecName),
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
} catch (ex) {
error = ex;
}
if ("production" !== process.env.NODE_ENV ? warning(!error || error instanceof Error, "%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error) : void 0,
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] = !0;
var stack = getStack ? getStack() : "";
"production" !== process.env.NODE_ENV ? warning(!1, "Failed %s type: %s%s", location, error.message, null != stack ? stack : "") : void 0;
}
}
}
var invariant = __webpack_require__(109), warning = __webpack_require__(110), ReactPropTypesSecret = __webpack_require__(111), loggedTypeFailures = {};
module.exports = checkPropTypes;
}).call(exports, __webpack_require__(95));
}, /* 113 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _extends2 = __webpack_require__(100), _extends3 = _interopRequireDefault(_extends2), _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _propTypes = __webpack_require__(106), _propTypes2 = _interopRequireDefault(_propTypes), _react = __webpack_require__(89), _react2 = _interopRequireDefault(_react), _classnames = __webpack_require__(114), _classnames2 = _interopRequireDefault(_classnames), _createCallbackMemoizer = __webpack_require__(115), _createCallbackMemoizer2 = _interopRequireDefault(_createCallbackMemoizer), _scrollbarSize = __webpack_require__(119), _scrollbarSize2 = _interopRequireDefault(_scrollbarSize), IS_SCROLLING_TIMEOUT = 150, SCROLL_POSITION_CHANGE_REASONS = {
OBSERVED: "observed",
REQUESTED: "requested"
}, CollectionView = function(_PureComponent) {
function CollectionView(props, context) {
(0, _classCallCheck3.default)(this, CollectionView);
var _this = (0, _possibleConstructorReturn3.default)(this, (CollectionView.__proto__ || (0,
_getPrototypeOf2.default)(CollectionView)).call(this, props, context));
return _this.state = {
isScrolling: !1,
scrollLeft: 0,
scrollTop: 0
}, _this._calculateSizeAndPositionDataOnNextUpdate = !1, _this._onSectionRenderedMemoizer = (0,
_createCallbackMemoizer2.default)(), _this._onScrollMemoizer = (0, _createCallbackMemoizer2.default)(!1),
_this._invokeOnSectionRenderedHelper = _this._invokeOnSectionRenderedHelper.bind(_this),
_this._onScroll = _this._onScroll.bind(_this), _this._setScrollingContainerRef = _this._setScrollingContainerRef.bind(_this),
_this._updateScrollPositionForScrollToCell = _this._updateScrollPositionForScrollToCell.bind(_this),
_this;
}
return (0, _inherits3.default)(CollectionView, _PureComponent), (0, _createClass3.default)(CollectionView, [ {
key: "recomputeCellSizesAndPositions",
value: function() {
this._calculateSizeAndPositionDataOnNextUpdate = !0, this.forceUpdate();
}
}, {
key: "componentDidMount",
value: function() {
var _props = this.props, cellLayoutManager = _props.cellLayoutManager, scrollLeft = _props.scrollLeft, scrollToCell = _props.scrollToCell, scrollTop = _props.scrollTop;
this._scrollbarSizeMeasured || (this._scrollbarSize = (0, _scrollbarSize2.default)(),
this._scrollbarSizeMeasured = !0, this.setState({})), scrollToCell >= 0 ? this._updateScrollPositionForScrollToCell() : (scrollLeft >= 0 || scrollTop >= 0) && this._setScrollPosition({
scrollLeft: scrollLeft,
scrollTop: scrollTop
}), this._invokeOnSectionRenderedHelper();
var _cellLayoutManager$ge = cellLayoutManager.getTotalSize(), totalHeight = _cellLayoutManager$ge.height, totalWidth = _cellLayoutManager$ge.width;
this._invokeOnScrollMemoizer({
scrollLeft: scrollLeft || 0,
scrollTop: scrollTop || 0,
totalHeight: totalHeight,
totalWidth: totalWidth
});
}
}, {
key: "componentDidUpdate",
value: function(prevProps, prevState) {
var _props2 = this.props, height = _props2.height, scrollToAlignment = _props2.scrollToAlignment, scrollToCell = _props2.scrollToCell, width = _props2.width, _state = this.state, scrollLeft = _state.scrollLeft, scrollPositionChangeReason = _state.scrollPositionChangeReason, scrollTop = _state.scrollTop;
scrollPositionChangeReason === SCROLL_POSITION_CHANGE_REASONS.REQUESTED && (scrollLeft >= 0 && scrollLeft !== prevState.scrollLeft && scrollLeft !== this._scrollingContainer.scrollLeft && (this._scrollingContainer.scrollLeft = scrollLeft),
scrollTop >= 0 && scrollTop !== prevState.scrollTop && scrollTop !== this._scrollingContainer.scrollTop && (this._scrollingContainer.scrollTop = scrollTop)),
height === prevProps.height && scrollToAlignment === prevProps.scrollToAlignment && scrollToCell === prevProps.scrollToCell && width === prevProps.width || this._updateScrollPositionForScrollToCell(),
this._invokeOnSectionRenderedHelper();
}
}, {
key: "componentWillMount",
value: function() {
var cellLayoutManager = this.props.cellLayoutManager;
cellLayoutManager.calculateSizeAndPositionData(), this._scrollbarSize = (0, _scrollbarSize2.default)(),
void 0 === this._scrollbarSize ? (this._scrollbarSizeMeasured = !1, this._scrollbarSize = 0) : this._scrollbarSizeMeasured = !0;
}
}, {
key: "componentWillUnmount",
value: function() {
this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId);
}
}, {
key: "componentWillReceiveProps",
value: function(nextProps) {
var _state2 = this.state, scrollLeft = _state2.scrollLeft, scrollTop = _state2.scrollTop;
0 !== nextProps.cellCount || 0 === scrollLeft && 0 === scrollTop ? nextProps.scrollLeft === this.props.scrollLeft && nextProps.scrollTop === this.props.scrollTop || this._setScrollPosition({
scrollLeft: nextProps.scrollLeft,
scrollTop: nextProps.scrollTop
}) : this._setScrollPosition({
scrollLeft: 0,
scrollTop: 0
}), (nextProps.cellCount !== this.props.cellCount || nextProps.cellLayoutManager !== this.props.cellLayoutManager || this._calculateSizeAndPositionDataOnNextUpdate) && nextProps.cellLayoutManager.calculateSizeAndPositionData(),
this._calculateSizeAndPositionDataOnNextUpdate && (this._calculateSizeAndPositionDataOnNextUpdate = !1);
}
}, {
key: "render",
value: function() {
var _props3 = this.props, autoHeight = _props3.autoHeight, cellCount = _props3.cellCount, cellLayoutManager = _props3.cellLayoutManager, className = _props3.className, height = _props3.height, horizontalOverscanSize = _props3.horizontalOverscanSize, id = _props3.id, noContentRenderer = _props3.noContentRenderer, style = _props3.style, verticalOverscanSize = _props3.verticalOverscanSize, width = _props3.width, _state3 = this.state, isScrolling = _state3.isScrolling, scrollLeft = _state3.scrollLeft, scrollTop = _state3.scrollTop, _cellLayoutManager$ge2 = cellLayoutManager.getTotalSize(), totalHeight = _cellLayoutManager$ge2.height, totalWidth = _cellLayoutManager$ge2.width, left = Math.max(0, scrollLeft - horizontalOverscanSize), top = Math.max(0, scrollTop - verticalOverscanSize), right = Math.min(totalWidth, scrollLeft + width + horizontalOverscanSize), bottom = Math.min(totalHeight, scrollTop + height + verticalOverscanSize), childrenToDisplay = height > 0 && width > 0 ? cellLayoutManager.cellRenderers({
height: bottom - top,
isScrolling: isScrolling,
width: right - left,
x: left,
y: top
}) : [], collectionStyle = {
boxSizing: "border-box",
direction: "ltr",
height: autoHeight ? "auto" : height,
position: "relative",
WebkitOverflowScrolling: "touch",
width: width,
willChange: "transform"
}, verticalScrollBarSize = totalHeight > height ? this._scrollbarSize : 0, horizontalScrollBarSize = totalWidth > width ? this._scrollbarSize : 0;
return collectionStyle.overflowX = totalWidth + verticalScrollBarSize <= width ? "hidden" : "auto",
collectionStyle.overflowY = totalHeight + horizontalScrollBarSize <= height ? "hidden" : "auto",
_react2.default.createElement("div", {
ref: this._setScrollingContainerRef,
"aria-label": this.props["aria-label"],
className: (0, _classnames2.default)("ReactVirtualized__Collection", className),
id: id,
onScroll: this._onScroll,
role: "grid",
style: (0, _extends3.default)({}, collectionStyle, style),
tabIndex: 0
}, cellCount > 0 && _react2.default.createElement("div", {
className: "ReactVirtualized__Collection__innerScrollContainer",
style: {
height: totalHeight,
maxHeight: totalHeight,
maxWidth: totalWidth,
overflow: "hidden",
pointerEvents: isScrolling ? "none" : "",
width: totalWidth
}
}, childrenToDisplay), 0 === cellCount && noContentRenderer());
}
}, {
key: "_enablePointerEventsAfterDelay",
value: function() {
var _this2 = this;
this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId),
this._disablePointerEventsTimeoutId = setTimeout(function() {
var isScrollingChange = _this2.props.isScrollingChange;
isScrollingChange(!1), _this2._disablePointerEventsTimeoutId = null, _this2.setState({
isScrolling: !1
});
}, IS_SCROLLING_TIMEOUT);
}
}, {
key: "_invokeOnSectionRenderedHelper",
value: function() {
var _props4 = this.props, cellLayoutManager = _props4.cellLayoutManager, onSectionRendered = _props4.onSectionRendered;
this._onSectionRenderedMemoizer({
callback: onSectionRendered,
indices: {
indices: cellLayoutManager.getLastRenderedIndices()
}
});
}
}, {
key: "_invokeOnScrollMemoizer",
value: function(_ref) {
var _this3 = this, scrollLeft = _ref.scrollLeft, scrollTop = _ref.scrollTop, totalHeight = _ref.totalHeight, totalWidth = _ref.totalWidth;
this._onScrollMemoizer({
callback: function(_ref2) {
var scrollLeft = _ref2.scrollLeft, scrollTop = _ref2.scrollTop, _props5 = _this3.props, height = _props5.height, onScroll = _props5.onScroll, width = _props5.width;
onScroll({
clientHeight: height,
clientWidth: width,
scrollHeight: totalHeight,
scrollLeft: scrollLeft,
scrollTop: scrollTop,
scrollWidth: totalWidth
});
},
indices: {
scrollLeft: scrollLeft,
scrollTop: scrollTop
}
});
}
}, {
key: "_setScrollingContainerRef",
value: function(ref) {
this._scrollingContainer = ref;
}
}, {
key: "_setScrollPosition",
value: function(_ref3) {
var scrollLeft = _ref3.scrollLeft, scrollTop = _ref3.scrollTop, newState = {
scrollPositionChangeReason: SCROLL_POSITION_CHANGE_REASONS.REQUESTED
};
scrollLeft >= 0 && (newState.scrollLeft = scrollLeft), scrollTop >= 0 && (newState.scrollTop = scrollTop),
(scrollLeft >= 0 && scrollLeft !== this.state.scrollLeft || scrollTop >= 0 && scrollTop !== this.state.scrollTop) && this.setState(newState);
}
}, {
key: "_updateScrollPositionForScrollToCell",
value: function() {
var _props6 = this.props, cellLayoutManager = _props6.cellLayoutManager, height = _props6.height, scrollToAlignment = _props6.scrollToAlignment, scrollToCell = _props6.scrollToCell, width = _props6.width, _state4 = this.state, scrollLeft = _state4.scrollLeft, scrollTop = _state4.scrollTop;
if (scrollToCell >= 0) {
var scrollPosition = cellLayoutManager.getScrollPositionForCell({
align: scrollToAlignment,
cellIndex: scrollToCell,
height: height,
scrollLeft: scrollLeft,
scrollTop: scrollTop,
width: width
});
scrollPosition.scrollLeft === scrollLeft && scrollPosition.scrollTop === scrollTop || this._setScrollPosition(scrollPosition);
}
}
}, {
key: "_onScroll",
value: function(event) {
if (event.target === this._scrollingContainer) {
this._enablePointerEventsAfterDelay();
var _props7 = this.props, cellLayoutManager = _props7.cellLayoutManager, height = _props7.height, isScrollingChange = _props7.isScrollingChange, width = _props7.width, scrollbarSize = this._scrollbarSize, _cellLayoutManager$ge3 = cellLayoutManager.getTotalSize(), totalHeight = _cellLayoutManager$ge3.height, totalWidth = _cellLayoutManager$ge3.width, scrollLeft = Math.max(0, Math.min(totalWidth - width + scrollbarSize, event.target.scrollLeft)), scrollTop = Math.max(0, Math.min(totalHeight - height + scrollbarSize, event.target.scrollTop));
if (this.state.scrollLeft !== scrollLeft || this.state.scrollTop !== scrollTop) {
var scrollPositionChangeReason = event.cancelable ? SCROLL_POSITION_CHANGE_REASONS.OBSERVED : SCROLL_POSITION_CHANGE_REASONS.REQUESTED;
this.state.isScrolling || isScrollingChange(!0), this.setState({
isScrolling: !0,
scrollLeft: scrollLeft,
scrollPositionChangeReason: scrollPositionChangeReason,
scrollTop: scrollTop
});
}
this._invokeOnScrollMemoizer({
scrollLeft: scrollLeft,
scrollTop: scrollTop,
totalWidth: totalWidth,
totalHeight: totalHeight
});
}
}
} ]), CollectionView;
}(_react.PureComponent);
CollectionView.propTypes = {
"aria-label": _propTypes2.default.string,
autoHeight: _propTypes2.default.bool,
cellCount: _propTypes2.default.number.isRequired,
cellLayoutManager: _propTypes2.default.object.isRequired,
className: _propTypes2.default.string,
height: _propTypes2.default.number.isRequired,
id: _propTypes2.default.string,
horizontalOverscanSize: _propTypes2.default.number.isRequired,
isScrollingChange: _propTypes2.default.func,
noContentRenderer: _propTypes2.default.func.isRequired,
onScroll: _propTypes2.default.func.isRequired,
onSectionRendered: _propTypes2.default.func.isRequired,
scrollLeft: _propTypes2.default.number,
scrollToAlignment: _propTypes2.default.oneOf([ "auto", "end", "start", "center" ]).isRequired,
scrollToCell: _propTypes2.default.number.isRequired,
scrollTop: _propTypes2.default.number,
style: _propTypes2.default.object,
verticalOverscanSize: _propTypes2.default.number.isRequired,
width: _propTypes2.default.number.isRequired
}, CollectionView.defaultProps = {
"aria-label": "grid",
horizontalOverscanSize: 0,
noContentRenderer: function() {
return null;
},
onScroll: function() {
return null;
},
onSectionRendered: function() {
return null;
},
scrollToAlignment: "auto",
scrollToCell: -1,
style: {},
verticalOverscanSize: 0
}, exports.default = CollectionView;
}, /* 114 */
/***/
function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;
/*!
Copyright (c) 2016 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
!function() {
"use strict";
function classNames() {
for (var classes = [], i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
var argType = typeof arg;
if ("string" === argType || "number" === argType) classes.push(arg); else if (Array.isArray(arg)) classes.push(classNames.apply(null, arg)); else if ("object" === argType) for (var key in arg) hasOwn.call(arg, key) && arg[key] && classes.push(key);
}
}
return classes.join(" ");
}
var hasOwn = {}.hasOwnProperty;
"undefined" != typeof module && module.exports ? module.exports = classNames : (__WEBPACK_AMD_DEFINE_ARRAY__ = [],
__WEBPACK_AMD_DEFINE_RESULT__ = function() {
return classNames;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), // register as 'classnames', consistent with npm package name
!(void 0 !== __WEBPACK_AMD_DEFINE_RESULT__ && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)));
}();
}, /* 115 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function createCallbackMemoizer() {
var requireAllKeys = !(arguments.length > 0 && void 0 !== arguments[0]) || arguments[0], cachedIndices = {};
return function(_ref) {
var callback = _ref.callback, indices = _ref.indices, keys = (0, _keys2.default)(indices), allInitialized = !requireAllKeys || keys.every(function(key) {
var value = indices[key];
return Array.isArray(value) ? value.length > 0 : value >= 0;
}), indexChanged = keys.length !== (0, _keys2.default)(cachedIndices).length || keys.some(function(key) {
var cachedValue = cachedIndices[key], value = indices[key];
return Array.isArray(value) ? cachedValue.join(",") !== value.join(",") : cachedValue !== value;
});
cachedIndices = indices, allInitialized && indexChanged && callback(indices);
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _keys = __webpack_require__(116), _keys2 = _interopRequireDefault(_keys);
exports.default = createCallbackMemoizer;
}, /* 116 */
/***/
function(module, exports, __webpack_require__) {
module.exports = {
default: __webpack_require__(117),
__esModule: !0
};
}, /* 117 */
/***/
function(module, exports, __webpack_require__) {
__webpack_require__(118), module.exports = __webpack_require__(16).Object.keys;
}, /* 118 */
/***/
function(module, exports, __webpack_require__) {
// 19.1.2.14 Object.keys(O)
var toObject = __webpack_require__(6), $keys = __webpack_require__(48);
__webpack_require__(14)("keys", function() {
return function(it) {
return $keys(toObject(it));
};
});
}, /* 119 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.default = function(recalc) {
if ((!size || recalc) && _inDOM2.default) {
var scrollDiv = document.createElement("div");
scrollDiv.style.position = "absolute", scrollDiv.style.top = "-9999px", scrollDiv.style.width = "50px",
scrollDiv.style.height = "50px", scrollDiv.style.overflow = "scroll", document.body.appendChild(scrollDiv),
size = scrollDiv.offsetWidth - scrollDiv.clientWidth, document.body.removeChild(scrollDiv);
}
return size;
};
var _inDOM = __webpack_require__(120), _inDOM2 = _interopRequireDefault(_inDOM), size = void 0;
module.exports = exports.default;
}, /* 120 */
/***/
function(module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.default = !("undefined" == typeof window || !window.document || !window.document.createElement),
module.exports = exports.default;
}, /* 121 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function calculateSizeAndPositionData(_ref) {
for (var cellCount = _ref.cellCount, cellSizeAndPositionGetter = _ref.cellSizeAndPositionGetter, sectionSize = _ref.sectionSize, cellMetadata = [], sectionManager = new _SectionManager2.default(sectionSize), height = 0, width = 0, index = 0; index < cellCount; index++) {
var cellMetadatum = cellSizeAndPositionGetter({
index: index
});
if (null == cellMetadatum.height || isNaN(cellMetadatum.height) || null == cellMetadatum.width || isNaN(cellMetadatum.width) || null == cellMetadatum.x || isNaN(cellMetadatum.x) || null == cellMetadatum.y || isNaN(cellMetadatum.y)) throw Error("Invalid metadata returned for cell " + index + ":\n x:" + cellMetadatum.x + ", y:" + cellMetadatum.y + ", width:" + cellMetadatum.width + ", height:" + cellMetadatum.height);
height = Math.max(height, cellMetadatum.y + cellMetadatum.height), width = Math.max(width, cellMetadatum.x + cellMetadatum.width),
cellMetadata[index] = cellMetadatum, sectionManager.registerCell({
cellMetadatum: cellMetadatum,
index: index
});
}
return {
cellMetadata: cellMetadata,
height: height,
sectionManager: sectionManager,
width: width
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.default = calculateSizeAndPositionData;
var _SectionManager = __webpack_require__(122), _SectionManager2 = _interopRequireDefault(_SectionManager);
}, /* 122 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _keys = __webpack_require__(116), _keys2 = _interopRequireDefault(_keys), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _Section = __webpack_require__(123), _Section2 = _interopRequireDefault(_Section), SECTION_SIZE = 100, SectionManager = function() {
function SectionManager() {
var sectionSize = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : SECTION_SIZE;
(0, _classCallCheck3.default)(this, SectionManager), this._sectionSize = sectionSize,
this._cellMetadata = [], this._sections = {};
}
return (0, _createClass3.default)(SectionManager, [ {
key: "getCellIndices",
value: function(_ref) {
var height = _ref.height, width = _ref.width, x = _ref.x, y = _ref.y, indices = {};
return this.getSections({
height: height,
width: width,
x: x,
y: y
}).forEach(function(section) {
return section.getCellIndices().forEach(function(index) {
indices[index] = index;
});
}), (0, _keys2.default)(indices).map(function(index) {
return indices[index];
});
}
}, {
key: "getCellMetadata",
value: function(_ref2) {
var index = _ref2.index;
return this._cellMetadata[index];
}
}, {
key: "getSections",
value: function(_ref3) {
for (var height = _ref3.height, width = _ref3.width, x = _ref3.x, y = _ref3.y, sectionXStart = Math.floor(x / this._sectionSize), sectionXStop = Math.floor((x + width - 1) / this._sectionSize), sectionYStart = Math.floor(y / this._sectionSize), sectionYStop = Math.floor((y + height - 1) / this._sectionSize), sections = [], sectionX = sectionXStart; sectionX <= sectionXStop; sectionX++) for (var sectionY = sectionYStart; sectionY <= sectionYStop; sectionY++) {
var key = sectionX + "." + sectionY;
this._sections[key] || (this._sections[key] = new _Section2.default({
height: this._sectionSize,
width: this._sectionSize,
x: sectionX * this._sectionSize,
y: sectionY * this._sectionSize
})), sections.push(this._sections[key]);
}
return sections;
}
}, {
key: "getTotalSectionCount",
value: function() {
return (0, _keys2.default)(this._sections).length;
}
}, {
key: "toString",
value: function() {
var _this = this;
return (0, _keys2.default)(this._sections).map(function(index) {
return _this._sections[index].toString();
});
}
}, {
key: "registerCell",
value: function(_ref4) {
var cellMetadatum = _ref4.cellMetadatum, index = _ref4.index;
this._cellMetadata[index] = cellMetadatum, this.getSections(cellMetadatum).forEach(function(section) {
return section.addCellIndex({
index: index
});
});
}
} ]), SectionManager;
}();
exports.default = SectionManager;
}, /* 123 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), Section = function() {
function Section(_ref) {
var height = _ref.height, width = _ref.width, x = _ref.x, y = _ref.y;
(0, _classCallCheck3.default)(this, Section), this.height = height, this.width = width,
this.x = x, this.y = y, this._indexMap = {}, this._indices = [];
}
return (0, _createClass3.default)(Section, [ {
key: "addCellIndex",
value: function(_ref2) {
var index = _ref2.index;
this._indexMap[index] || (this._indexMap[index] = !0, this._indices.push(index));
}
}, {
key: "getCellIndices",
value: function() {
return this._indices;
}
}, {
key: "toString",
value: function() {
return this.x + "," + this.y + " " + this.width + "x" + this.height;
}
} ]), Section;
}();
exports.default = Section;
}, /* 124 */
/***/
function(module, exports) {
"use strict";
function getUpdatedOffsetForIndex(_ref) {
var _ref$align = _ref.align, align = void 0 === _ref$align ? "auto" : _ref$align, cellOffset = _ref.cellOffset, cellSize = _ref.cellSize, containerSize = _ref.containerSize, currentOffset = _ref.currentOffset, maxOffset = cellOffset, minOffset = maxOffset - containerSize + cellSize;
switch (align) {
case "start":
return maxOffset;
case "end":
return minOffset;
case "center":
return maxOffset - (containerSize - cellSize) / 2;
default:
return Math.max(minOffset, Math.min(maxOffset, currentOffset));
}
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.default = getUpdatedOffsetForIndex;
}, /* 125 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.ColumnSizer = void 0;
var _ColumnSizer = __webpack_require__(126), _ColumnSizer2 = _interopRequireDefault(_ColumnSizer);
exports.default = _ColumnSizer2.default, exports.ColumnSizer = _ColumnSizer2.default;
}, /* 126 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _propTypes = __webpack_require__(106), _propTypes2 = _interopRequireDefault(_propTypes), _react = __webpack_require__(89), ColumnSizer = function(_PureComponent) {
function ColumnSizer(props, context) {
(0, _classCallCheck3.default)(this, ColumnSizer);
var _this = (0, _possibleConstructorReturn3.default)(this, (ColumnSizer.__proto__ || (0,
_getPrototypeOf2.default)(ColumnSizer)).call(this, props, context));
return _this._registerChild = _this._registerChild.bind(_this), _this;
}
return (0, _inherits3.default)(ColumnSizer, _PureComponent), (0, _createClass3.default)(ColumnSizer, [ {
key: "componentDidUpdate",
value: function(prevProps) {
var _props = this.props, columnMaxWidth = _props.columnMaxWidth, columnMinWidth = _props.columnMinWidth, columnCount = _props.columnCount, width = _props.width;
columnMaxWidth === prevProps.columnMaxWidth && columnMinWidth === prevProps.columnMinWidth && columnCount === prevProps.columnCount && width === prevProps.width || this._registeredChild && this._registeredChild.recomputeGridSize();
}
}, {
key: "render",
value: function() {
var _props2 = this.props, children = _props2.children, columnMaxWidth = _props2.columnMaxWidth, columnMinWidth = _props2.columnMinWidth, columnCount = _props2.columnCount, width = _props2.width, safeColumnMinWidth = columnMinWidth || 1, safeColumnMaxWidth = columnMaxWidth ? Math.min(columnMaxWidth, width) : width, columnWidth = width / columnCount;
columnWidth = Math.max(safeColumnMinWidth, columnWidth), columnWidth = Math.min(safeColumnMaxWidth, columnWidth),
columnWidth = Math.floor(columnWidth);
var adjustedWidth = Math.min(width, columnWidth * columnCount);
return children({
adjustedWidth: adjustedWidth,
columnWidth: columnWidth,
getColumnWidth: function() {
return columnWidth;
},
registerChild: this._registerChild
});
}
}, {
key: "_registerChild",
value: function(child) {
if (child && "function" != typeof child.recomputeGridSize) throw Error("Unexpected child type registered; only Grid/MultiGrid children are supported.");
this._registeredChild = child, this._registeredChild && this._registeredChild.recomputeGridSize();
}
} ]), ColumnSizer;
}(_react.PureComponent);
ColumnSizer.propTypes = {
children: _propTypes2.default.func.isRequired,
columnMaxWidth: _propTypes2.default.number,
columnMinWidth: _propTypes2.default.number,
columnCount: _propTypes2.default.number.isRequired,
width: _propTypes2.default.number.isRequired
}, exports.default = ColumnSizer;
}, /* 127 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _Grid = __webpack_require__(128);
Object.defineProperty(exports, "default", {
enumerable: !0,
get: function() {
return _interopRequireDefault(_Grid).default;
}
}), Object.defineProperty(exports, "Grid", {
enumerable: !0,
get: function() {
return _interopRequireDefault(_Grid).default;
}
});
var _accessibilityOverscanIndicesGetter = __webpack_require__(138);
Object.defineProperty(exports, "accessibilityOverscanIndicesGetter", {
enumerable: !0,
get: function() {
return _interopRequireDefault(_accessibilityOverscanIndicesGetter).default;
}
});
var _defaultCellRangeRenderer = __webpack_require__(135);
Object.defineProperty(exports, "defaultCellRangeRenderer", {
enumerable: !0,
get: function() {
return _interopRequireDefault(_defaultCellRangeRenderer).default;
}
});
var _defaultOverscanIndicesGetter = __webpack_require__(133);
Object.defineProperty(exports, "defaultOverscanIndicesGetter", {
enumerable: !0,
get: function() {
return _interopRequireDefault(_defaultOverscanIndicesGetter).default;
}
});
}, /* 128 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.DEFAULT_SCROLLING_RESET_TIME_INTERVAL = void 0;
var _objectDestructuringEmpty2 = __webpack_require__(129), _objectDestructuringEmpty3 = _interopRequireDefault(_objectDestructuringEmpty2), _extends2 = __webpack_require__(100), _extends3 = _interopRequireDefault(_extends2), _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _react = __webpack_require__(89), _react2 = _interopRequireDefault(_react), _classnames = __webpack_require__(114), _classnames2 = _interopRequireDefault(_classnames), _calculateSizeAndPositionDataAndUpdateScrollOffset = __webpack_require__(130), _calculateSizeAndPositionDataAndUpdateScrollOffset2 = _interopRequireDefault(_calculateSizeAndPositionDataAndUpdateScrollOffset), _ScalingCellSizeAndPositionManager = __webpack_require__(131), _ScalingCellSizeAndPositionManager2 = _interopRequireDefault(_ScalingCellSizeAndPositionManager), _createCallbackMemoizer = __webpack_require__(115), _createCallbackMemoizer2 = _interopRequireDefault(_createCallbackMemoizer), _defaultOverscanIndicesGetter = __webpack_require__(133), _defaultOverscanIndicesGetter2 = _interopRequireDefault(_defaultOverscanIndicesGetter), _updateScrollIndexHelper = __webpack_require__(134), _updateScrollIndexHelper2 = _interopRequireDefault(_updateScrollIndexHelper), _defaultCellRangeRenderer = __webpack_require__(135), _defaultCellRangeRenderer2 = _interopRequireDefault(_defaultCellRangeRenderer), _scrollbarSize = __webpack_require__(119), _scrollbarSize2 = _interopRequireDefault(_scrollbarSize), _requestAnimationTimeout = __webpack_require__(136), DEFAULT_SCROLLING_RESET_TIME_INTERVAL = exports.DEFAULT_SCROLLING_RESET_TIME_INTERVAL = 150, SCROLL_POSITION_CHANGE_REASONS = {
OBSERVED: "observed",
REQUESTED: "requested"
}, renderNull = function() {
return null;
}, Grid = function(_React$PureComponent) {
function Grid(props) {
(0, _classCallCheck3.default)(this, Grid);
var _this = (0, _possibleConstructorReturn3.default)(this, (Grid.__proto__ || (0,
_getPrototypeOf2.default)(Grid)).call(this, props));
_this.state = {
isScrolling: !1,
scrollDirectionHorizontal: _defaultOverscanIndicesGetter.SCROLL_DIRECTION_FORWARD,
scrollDirectionVertical: _defaultOverscanIndicesGetter.SCROLL_DIRECTION_FORWARD,
scrollLeft: 0,
scrollTop: 0
}, _this._onGridRenderedMemoizer = (0, _createCallbackMemoizer2.default)(), _this._onScrollMemoizer = (0,
_createCallbackMemoizer2.default)(!1), _this._deferredInvalidateColumnIndex = null,
_this._deferredInvalidateRowIndex = null, _this._recomputeScrollLeftFlag = !1, _this._recomputeScrollTopFlag = !1,
_this._horizontalScrollBarSize = 0, _this._verticalScrollBarSize = 0, _this._scrollbarPresenceChanged = !1,
_this._cellCache = {}, _this._styleCache = {}, _this._scrollbarSizeMeasured = !1,
_this._renderedColumnStartIndex = 0, _this._renderedColumnStopIndex = 0, _this._renderedRowStartIndex = 0,
_this._renderedRowStopIndex = 0, _this._debounceScrollEndedCallback = function() {
_this._disablePointerEventsTimeoutId = null, _this._resetStyleCache();
}, _this._invokeOnGridRenderedHelper = function() {
var onSectionRendered = _this.props.onSectionRendered;
_this._onGridRenderedMemoizer({
callback: onSectionRendered,
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
}
});
}, _this._setScrollingContainerRef = function(ref) {
_this._scrollingContainer = ref;
}, _this._onScroll = function(event) {
event.target === _this._scrollingContainer && _this.handleScrollEvent(event.target);
}, _this._columnWidthGetter = _this._wrapSizeGetter(props.columnWidth), _this._rowHeightGetter = _this._wrapSizeGetter(props.rowHeight);
var deferredMeasurementCache = props.deferredMeasurementCache;
return _this._columnSizeAndPositionManager = new _ScalingCellSizeAndPositionManager2.default({
batchAllCells: void 0 !== deferredMeasurementCache && !deferredMeasurementCache.hasFixedHeight(),
cellCount: props.columnCount,
cellSizeGetter: function(params) {
return _this._columnWidthGetter(params);
},
estimatedCellSize: _this._getEstimatedColumnSize(props)
}), _this._rowSizeAndPositionManager = new _ScalingCellSizeAndPositionManager2.default({
batchAllCells: void 0 !== deferredMeasurementCache && !deferredMeasurementCache.hasFixedWidth(),
cellCount: props.rowCount,
cellSizeGetter: function(params) {
return _this._rowHeightGetter(params);
},
estimatedCellSize: _this._getEstimatedRowSize(props)
}), _this;
}
return (0, _inherits3.default)(Grid, _React$PureComponent), (0, _createClass3.default)(Grid, [ {
key: "getOffsetForCell",
value: function() {
var _ref = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}, _ref$alignment = _ref.alignment, alignment = void 0 === _ref$alignment ? this.props.scrollToAlignment : _ref$alignment, _ref$columnIndex = _ref.columnIndex, columnIndex = void 0 === _ref$columnIndex ? this.props.scrollToColumn : _ref$columnIndex, _ref$rowIndex = _ref.rowIndex, rowIndex = void 0 === _ref$rowIndex ? this.props.scrollToRow : _ref$rowIndex, offsetProps = (0,
_extends3.default)({}, this.props, {
scrollToAlignment: alignment,
scrollToColumn: columnIndex,
scrollToRow: rowIndex
});
return {
scrollLeft: this._getCalculatedScrollLeft(offsetProps),
scrollTop: this._getCalculatedScrollTop(offsetProps)
};
}
}, {
key: "handleScrollEvent",
value: function(_ref2) {
var _ref2$scrollLeft = _ref2.scrollLeft, scrollLeftParam = void 0 === _ref2$scrollLeft ? 0 : _ref2$scrollLeft, _ref2$scrollTop = _ref2.scrollTop, scrollTopParam = void 0 === _ref2$scrollTop ? 0 : _ref2$scrollTop;
if (!(scrollTopParam < 0)) {
this._debounceScrollEnded();
var _props = this.props, autoHeight = _props.autoHeight, autoWidth = _props.autoWidth, height = _props.height, width = _props.width, scrollbarSize = this._scrollbarSize, totalRowsHeight = this._rowSizeAndPositionManager.getTotalSize(), totalColumnsWidth = this._columnSizeAndPositionManager.getTotalSize(), scrollLeft = Math.min(Math.max(0, totalColumnsWidth - width + scrollbarSize), scrollLeftParam), scrollTop = Math.min(Math.max(0, totalRowsHeight - height + scrollbarSize), scrollTopParam);
if (this.state.scrollLeft !== scrollLeft || this.state.scrollTop !== scrollTop) {
var _scrollDirectionHorizontal = scrollLeft !== this.state.scrollLeft ? scrollLeft > this.state.scrollLeft ? _defaultOverscanIndicesGetter.SCROLL_DIRECTION_FORWARD : _defaultOverscanIndicesGetter.SCROLL_DIRECTION_BACKWARD : this.state.scrollDirectionHorizontal, _scrollDirectionVertical = scrollTop !== this.state.scrollTop ? scrollTop > this.state.scrollTop ? _defaultOverscanIndicesGetter.SCROLL_DIRECTION_FORWARD : _defaultOverscanIndicesGetter.SCROLL_DIRECTION_BACKWARD : this.state.scrollDirectionVertical, newState = {
isScrolling: !0,
scrollDirectionHorizontal: _scrollDirectionHorizontal,
scrollDirectionVertical: _scrollDirectionVertical,
scrollPositionChangeReason: SCROLL_POSITION_CHANGE_REASONS.OBSERVED
};
autoHeight || (newState.scrollTop = scrollTop), autoWidth || (newState.scrollLeft = scrollLeft),
this.setState(newState);
}
this._invokeOnScrollMemoizer({
scrollLeft: scrollLeft,
scrollTop: scrollTop,
totalColumnsWidth: totalColumnsWidth,
totalRowsHeight: totalRowsHeight
});
}
}
}, {
key: "invalidateCellSizeAfterRender",
value: function(_ref3) {
var columnIndex = _ref3.columnIndex, rowIndex = _ref3.rowIndex;
this._deferredInvalidateColumnIndex = "number" == typeof this._deferredInvalidateColumnIndex ? Math.min(this._deferredInvalidateColumnIndex, columnIndex) : columnIndex,
this._deferredInvalidateRowIndex = "number" == typeof this._deferredInvalidateRowIndex ? Math.min(this._deferredInvalidateRowIndex, rowIndex) : rowIndex;
}
}, {
key: "measureAllCells",
value: function() {
var _props2 = this.props, columnCount = _props2.columnCount, rowCount = _props2.rowCount;
this._columnSizeAndPositionManager.getSizeAndPositionOfCell(columnCount - 1), this._rowSizeAndPositionManager.getSizeAndPositionOfCell(rowCount - 1);
}
}, {
key: "recomputeGridSize",
value: function() {
var _ref4 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}, _ref4$columnIndex = _ref4.columnIndex, columnIndex = void 0 === _ref4$columnIndex ? 0 : _ref4$columnIndex, _ref4$rowIndex = _ref4.rowIndex, rowIndex = void 0 === _ref4$rowIndex ? 0 : _ref4$rowIndex, _props3 = this.props, scrollToColumn = _props3.scrollToColumn, scrollToRow = _props3.scrollToRow;
this._columnSizeAndPositionManager.resetCell(columnIndex), this._rowSizeAndPositionManager.resetCell(rowIndex),
this._recomputeScrollLeftFlag = scrollToColumn >= 0 && columnIndex <= scrollToColumn,
this._recomputeScrollTopFlag = scrollToRow >= 0 && rowIndex <= scrollToRow, this._cellCache = {},
this._styleCache = {}, this.forceUpdate();
}
}, {
key: "scrollToCell",
value: function(_ref5) {
var columnIndex = _ref5.columnIndex, rowIndex = _ref5.rowIndex, columnCount = this.props.columnCount, props = this.props;
columnCount > 1 && void 0 !== columnIndex && this._updateScrollLeftForScrollToColumn((0,
_extends3.default)({}, props, {
scrollToColumn: columnIndex
})), void 0 !== rowIndex && this._updateScrollTopForScrollToRow((0, _extends3.default)({}, props, {
scrollToRow: rowIndex
}));
}
}, {
key: "componentDidMount",
value: function() {
var _props4 = this.props, getScrollbarSize = _props4.getScrollbarSize, height = _props4.height, scrollLeft = _props4.scrollLeft, scrollToColumn = _props4.scrollToColumn, scrollTop = _props4.scrollTop, scrollToRow = _props4.scrollToRow, width = _props4.width;
this._handleInvalidatedGridSize(), this._scrollbarSizeMeasured || (this._scrollbarSize = getScrollbarSize(),
this._scrollbarSizeMeasured = !0, this.setState({})), ("number" == typeof scrollLeft && scrollLeft >= 0 || "number" == typeof scrollTop && scrollTop >= 0) && this.scrollToPosition({
scrollLeft: scrollLeft,
scrollTop: scrollTop
});
var sizeIsBiggerThanZero = height > 0 && width > 0;
scrollToColumn >= 0 && sizeIsBiggerThanZero && this._updateScrollLeftForScrollToColumn(),
scrollToRow >= 0 && sizeIsBiggerThanZero && this._updateScrollTopForScrollToRow(),
this._invokeOnGridRenderedHelper(), this._invokeOnScrollMemoizer({
scrollLeft: scrollLeft || 0,
scrollTop: scrollTop || 0,
totalColumnsWidth: this._columnSizeAndPositionManager.getTotalSize(),
totalRowsHeight: this._rowSizeAndPositionManager.getTotalSize()
}), this._maybeCallOnScrollbarPresenceChange();
}
}, {
key: "componentDidUpdate",
value: function(prevProps, prevState) {
var _this2 = this, _props5 = this.props, autoHeight = _props5.autoHeight, autoWidth = _props5.autoWidth, columnCount = _props5.columnCount, height = _props5.height, rowCount = _props5.rowCount, scrollToAlignment = _props5.scrollToAlignment, scrollToColumn = _props5.scrollToColumn, scrollToRow = _props5.scrollToRow, width = _props5.width, _state = this.state, scrollLeft = _state.scrollLeft, scrollPositionChangeReason = _state.scrollPositionChangeReason, scrollTop = _state.scrollTop;
this._handleInvalidatedGridSize();
var columnOrRowCountJustIncreasedFromZero = columnCount > 0 && 0 === prevProps.columnCount || rowCount > 0 && 0 === prevProps.rowCount;
scrollPositionChangeReason === SCROLL_POSITION_CHANGE_REASONS.REQUESTED && (!autoWidth && scrollLeft >= 0 && (scrollLeft !== prevState.scrollLeft && scrollLeft !== this._scrollingContainer.scrollLeft || columnOrRowCountJustIncreasedFromZero) && (this._scrollingContainer.scrollLeft = scrollLeft),
!autoHeight && scrollTop >= 0 && (scrollTop !== prevState.scrollTop && scrollTop !== this._scrollingContainer.scrollTop || columnOrRowCountJustIncreasedFromZero) && (this._scrollingContainer.scrollTop = scrollTop));
var sizeJustIncreasedFromZero = (0 === prevProps.width || 0 === prevProps.height) && height > 0 && width > 0;
if (this._recomputeScrollLeftFlag ? (this._recomputeScrollLeftFlag = !1, this._updateScrollLeftForScrollToColumn(this.props)) : (0,
_updateScrollIndexHelper2.default)({
cellSizeAndPositionManager: this._columnSizeAndPositionManager,
previousCellsCount: prevProps.columnCount,
previousCellSize: prevProps.columnWidth,
previousScrollToAlignment: prevProps.scrollToAlignment,
previousScrollToIndex: prevProps.scrollToColumn,
previousSize: prevProps.width,
scrollOffset: scrollLeft,
scrollToAlignment: scrollToAlignment,
scrollToIndex: scrollToColumn,
size: width,
sizeJustIncreasedFromZero: sizeJustIncreasedFromZero,
updateScrollIndexCallback: function() {
return _this2._updateScrollLeftForScrollToColumn(_this2.props);
}
}), this._recomputeScrollTopFlag ? (this._recomputeScrollTopFlag = !1, this._updateScrollTopForScrollToRow(this.props)) : (0,
_updateScrollIndexHelper2.default)({
cellSizeAndPositionManager: this._rowSizeAndPositionManager,
previousCellsCount: prevProps.rowCount,
previousCellSize: prevProps.rowHeight,
previousScrollToAlignment: prevProps.scrollToAlignment,
previousScrollToIndex: prevProps.scrollToRow,
previousSize: prevProps.height,
scrollOffset: scrollTop,
scrollToAlignment: scrollToAlignment,
scrollToIndex: scrollToRow,
size: height,
sizeJustIncreasedFromZero: sizeJustIncreasedFromZero,
updateScrollIndexCallback: function() {
return _this2._updateScrollTopForScrollToRow(_this2.props);
}
}), this._invokeOnGridRenderedHelper(), scrollLeft !== prevState.scrollLeft || scrollTop !== prevState.scrollTop) {
var totalRowsHeight = this._rowSizeAndPositionManager.getTotalSize(), totalColumnsWidth = this._columnSizeAndPositionManager.getTotalSize();
this._invokeOnScrollMemoizer({
scrollLeft: scrollLeft,
scrollTop: scrollTop,
totalColumnsWidth: totalColumnsWidth,
totalRowsHeight: totalRowsHeight
});
}
this._maybeCallOnScrollbarPresenceChange();
}
}, {
key: "componentWillMount",
value: function() {
var getScrollbarSize = this.props.getScrollbarSize;
this._scrollbarSize = getScrollbarSize(), void 0 === this._scrollbarSize ? (this._scrollbarSizeMeasured = !1,
this._scrollbarSize = 0) : this._scrollbarSizeMeasured = !0, this._calculateChildrenToRender();
}
}, {
key: "componentWillUnmount",
value: function() {
this._disablePointerEventsTimeoutId && (0, _requestAnimationTimeout.cancelAnimationTimeout)(this._disablePointerEventsTimeoutId);
}
}, {
key: "componentWillReceiveProps",
value: function(nextProps) {
var _this3 = this, _state2 = this.state, scrollLeft = _state2.scrollLeft, scrollTop = _state2.scrollTop;
if (0 === nextProps.columnCount && 0 !== scrollLeft || 0 === nextProps.rowCount && 0 !== scrollTop) this.scrollToPosition({
scrollLeft: 0,
scrollTop: 0
}); else if (nextProps.scrollLeft !== this.props.scrollLeft || nextProps.scrollTop !== this.props.scrollTop) {
var newState = {};
null != nextProps.scrollLeft && (newState.scrollLeft = nextProps.scrollLeft), null != nextProps.scrollTop && (newState.scrollTop = nextProps.scrollTop),
this.scrollToPosition(newState);
}
nextProps.columnWidth === this.props.columnWidth && nextProps.rowHeight === this.props.rowHeight || (this._styleCache = {}),
this._columnWidthGetter = this._wrapSizeGetter(nextProps.columnWidth), this._rowHeightGetter = this._wrapSizeGetter(nextProps.rowHeight),
this._columnSizeAndPositionManager.configure({
cellCount: nextProps.columnCount,
estimatedCellSize: this._getEstimatedColumnSize(nextProps)
}), this._rowSizeAndPositionManager.configure({
cellCount: nextProps.rowCount,
estimatedCellSize: this._getEstimatedRowSize(nextProps)
});
var _props6 = this.props, columnCount = _props6.columnCount, rowCount = _props6.rowCount;
0 !== columnCount && 0 !== rowCount || (columnCount = 0, rowCount = 0), nextProps.autoHeight && nextProps.isScrolling === !1 && this.props.isScrolling === !0 && this._resetStyleCache(),
(0, _calculateSizeAndPositionDataAndUpdateScrollOffset2.default)({
cellCount: columnCount,
cellSize: "number" == typeof this.props.columnWidth ? this.props.columnWidth : null,
computeMetadataCallback: function() {
return _this3._columnSizeAndPositionManager.resetCell(0);
},
computeMetadataCallbackProps: nextProps,
nextCellsCount: nextProps.columnCount,
nextCellSize: "number" == typeof nextProps.columnWidth ? nextProps.columnWidth : null,
nextScrollToIndex: nextProps.scrollToColumn,
scrollToIndex: this.props.scrollToColumn,
updateScrollOffsetForScrollToIndex: function() {
return _this3._updateScrollLeftForScrollToColumn(nextProps, _this3.state);
}
}), (0, _calculateSizeAndPositionDataAndUpdateScrollOffset2.default)({
cellCount: rowCount,
cellSize: "number" == typeof this.props.rowHeight ? this.props.rowHeight : null,
computeMetadataCallback: function() {
return _this3._rowSizeAndPositionManager.resetCell(0);
},
computeMetadataCallbackProps: nextProps,
nextCellsCount: nextProps.rowCount,
nextCellSize: "number" == typeof nextProps.rowHeight ? nextProps.rowHeight : null,
nextScrollToIndex: nextProps.scrollToRow,
scrollToIndex: this.props.scrollToRow,
updateScrollOffsetForScrollToIndex: function() {
return _this3._updateScrollTopForScrollToRow(nextProps, _this3.state);
}
});
}
}, {
key: "componentWillUpdate",
value: function(nextProps, nextState) {
this._calculateChildrenToRender(nextProps, nextState);
}
}, {
key: "render",
value: function() {
var _props7 = this.props, autoContainerWidth = _props7.autoContainerWidth, autoHeight = _props7.autoHeight, autoWidth = _props7.autoWidth, className = _props7.className, containerProps = _props7.containerProps, containerRole = _props7.containerRole, containerStyle = _props7.containerStyle, height = _props7.height, id = _props7.id, noContentRenderer = _props7.noContentRenderer, role = _props7.role, style = _props7.style, tabIndex = _props7.tabIndex, width = _props7.width, isScrolling = this._isScrolling(), gridStyle = {
boxSizing: "border-box",
direction: "ltr",
height: autoHeight ? "auto" : height,
position: "relative",
width: autoWidth ? "auto" : width,
WebkitOverflowScrolling: "touch",
willChange: "transform"
}, totalColumnsWidth = this._columnSizeAndPositionManager.getTotalSize(), totalRowsHeight = this._rowSizeAndPositionManager.getTotalSize(), verticalScrollBarSize = totalRowsHeight > height ? this._scrollbarSize : 0, horizontalScrollBarSize = totalColumnsWidth > width ? this._scrollbarSize : 0;
horizontalScrollBarSize === this._horizontalScrollBarSize && verticalScrollBarSize === this._verticalScrollBarSize || (this._horizontalScrollBarSize = horizontalScrollBarSize,
this._verticalScrollBarSize = verticalScrollBarSize, this._scrollbarPresenceChanged = !0),
gridStyle.overflowX = totalColumnsWidth + verticalScrollBarSize <= width ? "hidden" : "auto",
gridStyle.overflowY = totalRowsHeight + horizontalScrollBarSize <= height ? "hidden" : "auto";
var childrenToDisplay = this._childrenToDisplay, showNoContentRenderer = 0 === childrenToDisplay.length && height > 0 && width > 0;
return _react2.default.createElement("div", (0, _extends3.default)({
ref: this._setScrollingContainerRef
}, containerProps, {
"aria-label": this.props["aria-label"],
"aria-readonly": this.props["aria-readonly"],
className: (0, _classnames2.default)("ReactVirtualized__Grid", className),
id: id,
onScroll: this._onScroll,
role: role,
style: (0, _extends3.default)({}, gridStyle, style),
tabIndex: tabIndex
}), childrenToDisplay.length > 0 && _react2.default.createElement("div", {
className: "ReactVirtualized__Grid__innerScrollContainer",
role: containerRole,
style: (0, _extends3.default)({
width: autoContainerWidth ? "auto" : totalColumnsWidth,
height: totalRowsHeight,
maxWidth: totalColumnsWidth,
maxHeight: totalRowsHeight,
overflow: "hidden",
pointerEvents: isScrolling ? "none" : "",
position: "relative"
}, containerStyle)
}, childrenToDisplay), showNoContentRenderer && noContentRenderer());
}
}, {
key: "_calculateChildrenToRender",
value: function() {
var props = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : this.props, state = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : this.state, cellRenderer = props.cellRenderer, cellRangeRenderer = props.cellRangeRenderer, columnCount = props.columnCount, deferredMeasurementCache = props.deferredMeasurementCache, height = props.height, overscanColumnCount = props.overscanColumnCount, overscanIndicesGetter = props.overscanIndicesGetter, overscanRowCount = props.overscanRowCount, rowCount = props.rowCount, width = props.width, scrollDirectionHorizontal = state.scrollDirectionHorizontal, scrollDirectionVertical = state.scrollDirectionVertical, scrollLeft = state.scrollLeft, scrollTop = state.scrollTop, isScrolling = this._isScrolling(props, state);
if (this._childrenToDisplay = [], height > 0 && width > 0) {
var visibleColumnIndices = this._columnSizeAndPositionManager.getVisibleCellRange({
containerSize: width,
offset: scrollLeft
}), visibleRowIndices = this._rowSizeAndPositionManager.getVisibleCellRange({
containerSize: height,
offset: scrollTop
}), horizontalOffsetAdjustment = this._columnSizeAndPositionManager.getOffsetAdjustment({
containerSize: width,
offset: scrollLeft
}), verticalOffsetAdjustment = this._rowSizeAndPositionManager.getOffsetAdjustment({
containerSize: height,
offset: scrollTop
});
this._renderedColumnStartIndex = visibleColumnIndices.start, this._renderedColumnStopIndex = visibleColumnIndices.stop,
this._renderedRowStartIndex = visibleRowIndices.start, this._renderedRowStopIndex = visibleRowIndices.stop;
var overscanColumnIndices = overscanIndicesGetter({
direction: "horizontal",
cellCount: columnCount,
overscanCellsCount: overscanColumnCount,
scrollDirection: scrollDirectionHorizontal,
startIndex: "number" == typeof this._renderedColumnStartIndex ? this._renderedColumnStartIndex : 0,
stopIndex: "number" == typeof this._renderedColumnStopIndex ? this._renderedColumnStopIndex : -1
}), overscanRowIndices = overscanIndicesGetter({
direction: "vertical",
cellCount: rowCount,
overscanCellsCount: overscanRowCount,
scrollDirection: scrollDirectionVertical,
startIndex: "number" == typeof this._renderedRowStartIndex ? this._renderedRowStartIndex : 0,
stopIndex: "number" == typeof this._renderedRowStopIndex ? this._renderedRowStopIndex : -1
});
this._columnStartIndex = overscanColumnIndices.overscanStartIndex, this._columnStopIndex = overscanColumnIndices.overscanStopIndex,
this._rowStartIndex = overscanRowIndices.overscanStartIndex, this._rowStopIndex = overscanRowIndices.overscanStopIndex,
this._childrenToDisplay = cellRangeRenderer({
cellCache: this._cellCache,
cellRenderer: cellRenderer,
columnSizeAndPositionManager: this._columnSizeAndPositionManager,
columnStartIndex: this._columnStartIndex,
columnStopIndex: this._columnStopIndex,
deferredMeasurementCache: deferredMeasurementCache,
horizontalOffsetAdjustment: horizontalOffsetAdjustment,
isScrolling: isScrolling,
parent: this,
rowSizeAndPositionManager: this._rowSizeAndPositionManager,
rowStartIndex: this._rowStartIndex,
rowStopIndex: this._rowStopIndex,
scrollLeft: scrollLeft,
scrollTop: scrollTop,
styleCache: this._styleCache,
verticalOffsetAdjustment: verticalOffsetAdjustment,
visibleColumnIndices: visibleColumnIndices,
visibleRowIndices: visibleRowIndices
});
}
}
}, {
key: "_debounceScrollEnded",
value: function() {
var scrollingResetTimeInterval = this.props.scrollingResetTimeInterval;
this._disablePointerEventsTimeoutId && (0, _requestAnimationTimeout.cancelAnimationTimeout)(this._disablePointerEventsTimeoutId),
this._disablePointerEventsTimeoutId = (0, _requestAnimationTimeout.requestAnimationTimeout)(this._debounceScrollEndedCallback, scrollingResetTimeInterval);
}
}, {
key: "_getEstimatedColumnSize",
value: function(props) {
return "number" == typeof props.columnWidth ? props.columnWidth : props.estimatedColumnSize;
}
}, {
key: "_getEstimatedRowSize",
value: function(props) {
return "number" == typeof props.rowHeight ? props.rowHeight : props.estimatedRowSize;
}
}, {
key: "_handleInvalidatedGridSize",
value: function() {
if ("number" == typeof this._deferredInvalidateColumnIndex && "number" == typeof this._deferredInvalidateRowIndex) {
var columnIndex = this._deferredInvalidateColumnIndex, rowIndex = this._deferredInvalidateRowIndex;
this._deferredInvalidateColumnIndex = null, this._deferredInvalidateRowIndex = null,
this.recomputeGridSize({
columnIndex: columnIndex,
rowIndex: rowIndex
});
}
}
}, {
key: "_invokeOnScrollMemoizer",
value: function(_ref6) {
var _this4 = this, scrollLeft = _ref6.scrollLeft, scrollTop = _ref6.scrollTop, totalColumnsWidth = _ref6.totalColumnsWidth, totalRowsHeight = _ref6.totalRowsHeight;
this._onScrollMemoizer({
callback: function(_ref7) {
var scrollLeft = _ref7.scrollLeft, scrollTop = _ref7.scrollTop, _props8 = _this4.props, height = _props8.height, onScroll = _props8.onScroll, width = _props8.width;
onScroll({
clientHeight: height,
clientWidth: width,
scrollHeight: totalRowsHeight,
scrollLeft: scrollLeft,
scrollTop: scrollTop,
scrollWidth: totalColumnsWidth
});
},
indices: {
scrollLeft: scrollLeft,
scrollTop: scrollTop
}
});
}
}, {
key: "_isScrolling",
value: function() {
var props = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : this.props, state = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : this.state;
return Object.hasOwnProperty.call(props, "isScrolling") ? Boolean(props.isScrolling) : Boolean(state.isScrolling);
}
}, {
key: "_maybeCallOnScrollbarPresenceChange",
value: function() {
if (this._scrollbarPresenceChanged) {
var _onScrollbarPresenceChange = this.props.onScrollbarPresenceChange;
this._scrollbarPresenceChanged = !1, _onScrollbarPresenceChange({
horizontal: this._horizontalScrollBarSize > 0,
size: this._scrollbarSize,
vertical: this._verticalScrollBarSize > 0
});
}
}
}, {
key: "scrollToPosition",
value: function(_ref8) {
var scrollLeft = _ref8.scrollLeft, scrollTop = _ref8.scrollTop, newState = {
scrollPositionChangeReason: SCROLL_POSITION_CHANGE_REASONS.REQUESTED
};
"number" == typeof scrollLeft && scrollLeft >= 0 && (newState.scrollDirectionHorizontal = scrollLeft > this.state.scrollLeft ? _defaultOverscanIndicesGetter.SCROLL_DIRECTION_FORWARD : _defaultOverscanIndicesGetter.SCROLL_DIRECTION_BACKWARD,
newState.scrollLeft = scrollLeft), "number" == typeof scrollTop && scrollTop >= 0 && (newState.scrollDirectionVertical = scrollTop > this.state.scrollTop ? _defaultOverscanIndicesGetter.SCROLL_DIRECTION_FORWARD : _defaultOverscanIndicesGetter.SCROLL_DIRECTION_BACKWARD,
newState.scrollTop = scrollTop), ("number" == typeof scrollLeft && scrollLeft >= 0 && scrollLeft !== this.state.scrollLeft || "number" == typeof scrollTop && scrollTop >= 0 && scrollTop !== this.state.scrollTop) && this.setState(newState);
}
}, {
key: "_wrapSizeGetter",
value: function(value) {
return "function" == typeof value ? value : function() {
return value;
};
}
}, {
key: "_getCalculatedScrollLeft",
value: function() {
var props = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : this.props, state = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : this.state, columnCount = props.columnCount, height = props.height, scrollToAlignment = props.scrollToAlignment, scrollToColumn = props.scrollToColumn, width = props.width, scrollLeft = state.scrollLeft;
if (columnCount > 0) {
var finalColumn = columnCount - 1, targetIndex = scrollToColumn < 0 ? finalColumn : Math.min(finalColumn, scrollToColumn), totalRowsHeight = this._rowSizeAndPositionManager.getTotalSize(), scrollBarSize = totalRowsHeight > height ? this._scrollbarSize : 0;
return this._columnSizeAndPositionManager.getUpdatedOffsetForIndex({
align: scrollToAlignment,
containerSize: width - scrollBarSize,
currentOffset: scrollLeft,
targetIndex: targetIndex
});
}
}
}, {
key: "_updateScrollLeftForScrollToColumn",
value: function() {
var props = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : this.props, state = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : this.state, scrollLeft = state.scrollLeft, calculatedScrollLeft = this._getCalculatedScrollLeft(props, state);
"number" == typeof calculatedScrollLeft && calculatedScrollLeft >= 0 && scrollLeft !== calculatedScrollLeft && this.scrollToPosition({
scrollLeft: calculatedScrollLeft,
scrollTop: -1
});
}
}, {
key: "_getCalculatedScrollTop",
value: function() {
var props = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : this.props, state = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : this.state, height = props.height, rowCount = props.rowCount, scrollToAlignment = props.scrollToAlignment, scrollToRow = props.scrollToRow, width = props.width, scrollTop = state.scrollTop;
if (rowCount > 0) {
var finalRow = rowCount - 1, targetIndex = scrollToRow < 0 ? finalRow : Math.min(finalRow, scrollToRow), totalColumnsWidth = this._columnSizeAndPositionManager.getTotalSize(), scrollBarSize = totalColumnsWidth > width ? this._scrollbarSize : 0;
return this._rowSizeAndPositionManager.getUpdatedOffsetForIndex({
align: scrollToAlignment,
containerSize: height - scrollBarSize,
currentOffset: scrollTop,
targetIndex: targetIndex
});
}
}
}, {
key: "_resetStyleCache",
value: function() {
var styleCache = this._styleCache;
this._cellCache = {}, this._styleCache = {};
for (var rowIndex = this._rowStartIndex; rowIndex <= this._rowStopIndex; rowIndex++) for (var columnIndex = this._columnStartIndex; columnIndex <= this._columnStopIndex; columnIndex++) {
var key = rowIndex + "-" + columnIndex;
this._styleCache[key] = styleCache[key];
}
this.setState({
isScrolling: !1
});
}
}, {
key: "_updateScrollTopForScrollToRow",
value: function() {
var props = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : this.props, state = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : this.state, scrollTop = state.scrollTop, calculatedScrollTop = this._getCalculatedScrollTop(props, state);
"number" == typeof calculatedScrollTop && calculatedScrollTop >= 0 && scrollTop !== calculatedScrollTop && this.scrollToPosition({
scrollLeft: -1,
scrollTop: calculatedScrollTop
});
}
} ]), Grid;
}(_react2.default.PureComponent);
Grid.defaultProps = {
"aria-label": "grid",
"aria-readonly": !0,
autoContainerWidth: !1,
autoHeight: !1,
autoWidth: !1,
cellRangeRenderer: _defaultCellRangeRenderer2.default,
containerRole: "rowgroup",
containerStyle: {},
estimatedColumnSize: 100,
estimatedRowSize: 30,
getScrollbarSize: _scrollbarSize2.default,
noContentRenderer: renderNull,
onScroll: function(_ref9) {
(0, _objectDestructuringEmpty3.default)(_ref9);
},
onScrollbarPresenceChange: function() {},
onSectionRendered: function(_ref10) {
(0, _objectDestructuringEmpty3.default)(_ref10);
},
overscanColumnCount: 0,
overscanIndicesGetter: _defaultOverscanIndicesGetter2.default,
overscanRowCount: 10,
role: "grid",
scrollingResetTimeInterval: DEFAULT_SCROLLING_RESET_TIME_INTERVAL,
scrollToAlignment: "auto",
scrollToColumn: -1,
scrollToRow: -1,
style: {},
tabIndex: 0
}, exports.default = Grid;
}, /* 129 */
/***/
function(module, exports) {
"use strict";
exports.__esModule = !0, exports.default = function(obj) {
if (null == obj) throw new TypeError("Cannot destructure undefined");
};
}, /* 130 */
/***/
function(module, exports) {
"use strict";
function calculateSizeAndPositionDataAndUpdateScrollOffset(_ref) {
var cellCount = _ref.cellCount, cellSize = _ref.cellSize, computeMetadataCallback = _ref.computeMetadataCallback, computeMetadataCallbackProps = _ref.computeMetadataCallbackProps, nextCellsCount = _ref.nextCellsCount, nextCellSize = _ref.nextCellSize, nextScrollToIndex = _ref.nextScrollToIndex, scrollToIndex = _ref.scrollToIndex, updateScrollOffsetForScrollToIndex = _ref.updateScrollOffsetForScrollToIndex;
cellCount === nextCellsCount && ("number" != typeof cellSize && "number" != typeof nextCellSize || cellSize === nextCellSize) || (computeMetadataCallback(computeMetadataCallbackProps),
scrollToIndex >= 0 && scrollToIndex === nextScrollToIndex && updateScrollOffsetForScrollToIndex());
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.default = calculateSizeAndPositionDataAndUpdateScrollOffset;
}, /* 131 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.DEFAULT_MAX_SCROLL_SIZE = void 0;
var _objectWithoutProperties2 = __webpack_require__(105), _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _CellSizeAndPositionManager = __webpack_require__(132), _CellSizeAndPositionManager2 = _interopRequireDefault(_CellSizeAndPositionManager), DEFAULT_MAX_SCROLL_SIZE = exports.DEFAULT_MAX_SCROLL_SIZE = 15e5, ScalingCellSizeAndPositionManager = function() {
function ScalingCellSizeAndPositionManager(_ref) {
var _ref$maxScrollSize = _ref.maxScrollSize, maxScrollSize = void 0 === _ref$maxScrollSize ? DEFAULT_MAX_SCROLL_SIZE : _ref$maxScrollSize, params = (0,
_objectWithoutProperties3.default)(_ref, [ "maxScrollSize" ]);
(0, _classCallCheck3.default)(this, ScalingCellSizeAndPositionManager), this._cellSizeAndPositionManager = new _CellSizeAndPositionManager2.default(params),
this._maxScrollSize = maxScrollSize;
}
return (0, _createClass3.default)(ScalingCellSizeAndPositionManager, [ {
key: "areOffsetsAdjusted",
value: function() {
return this._cellSizeAndPositionManager.getTotalSize() > this._maxScrollSize;
}
}, {
key: "configure",
value: function(params) {
this._cellSizeAndPositionManager.configure(params);
}
}, {
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(_ref2) {
var containerSize = _ref2.containerSize, offset = _ref2.offset, totalSize = this._cellSizeAndPositionManager.getTotalSize(), safeTotalSize = this.getTotalSize(), offsetPercentage = this._getOffsetPercentage({
containerSize: containerSize,
offset: offset,
totalSize: safeTotalSize
});
return Math.round(offsetPercentage * (safeTotalSize - totalSize));
}
}, {
key: "getSizeAndPositionOfCell",
value: function(index) {
return this._cellSizeAndPositionManager.getSizeAndPositionOfCell(index);
}
}, {
key: "getSizeAndPositionOfLastMeasuredCell",
value: function() {
return this._cellSizeAndPositionManager.getSizeAndPositionOfLastMeasuredCell();
}
}, {
key: "getTotalSize",
value: function() {
return Math.min(this._maxScrollSize, this._cellSizeAndPositionManager.getTotalSize());
}
}, {
key: "getUpdatedOffsetForIndex",
value: function(_ref3) {
var _ref3$align = _ref3.align, align = void 0 === _ref3$align ? "auto" : _ref3$align, containerSize = _ref3.containerSize, currentOffset = _ref3.currentOffset, targetIndex = _ref3.targetIndex;
currentOffset = this._safeOffsetToOffset({
containerSize: containerSize,
offset: currentOffset
});
var offset = this._cellSizeAndPositionManager.getUpdatedOffsetForIndex({
align: align,
containerSize: containerSize,
currentOffset: currentOffset,
targetIndex: targetIndex
});
return this._offsetToSafeOffset({
containerSize: containerSize,
offset: offset
});
}
}, {
key: "getVisibleCellRange",
value: function(_ref4) {
var containerSize = _ref4.containerSize, offset = _ref4.offset;
return offset = this._safeOffsetToOffset({
containerSize: containerSize,
offset: offset
}), this._cellSizeAndPositionManager.getVisibleCellRange({
containerSize: containerSize,
offset: offset
});
}
}, {
key: "resetCell",
value: function(index) {
this._cellSizeAndPositionManager.resetCell(index);
}
}, {
key: "_getOffsetPercentage",
value: function(_ref5) {
var containerSize = _ref5.containerSize, offset = _ref5.offset, totalSize = _ref5.totalSize;
return totalSize <= containerSize ? 0 : offset / (totalSize - containerSize);
}
}, {
key: "_offsetToSafeOffset",
value: function(_ref6) {
var containerSize = _ref6.containerSize, offset = _ref6.offset, totalSize = this._cellSizeAndPositionManager.getTotalSize(), safeTotalSize = this.getTotalSize();
if (totalSize === safeTotalSize) return offset;
var offsetPercentage = this._getOffsetPercentage({
containerSize: containerSize,
offset: offset,
totalSize: totalSize
});
return Math.round(offsetPercentage * (safeTotalSize - containerSize));
}
}, {
key: "_safeOffsetToOffset",
value: function(_ref7) {
var containerSize = _ref7.containerSize, offset = _ref7.offset, totalSize = this._cellSizeAndPositionManager.getTotalSize(), safeTotalSize = this.getTotalSize();
if (totalSize === safeTotalSize) return offset;
var offsetPercentage = this._getOffsetPercentage({
containerSize: containerSize,
offset: offset,
totalSize: safeTotalSize
});
return Math.round(offsetPercentage * (totalSize - containerSize));
}
} ]), ScalingCellSizeAndPositionManager;
}();
exports.default = ScalingCellSizeAndPositionManager;
}, /* 132 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), CellSizeAndPositionManager = function() {
function CellSizeAndPositionManager(_ref) {
var _ref$batchAllCells = _ref.batchAllCells, batchAllCells = void 0 !== _ref$batchAllCells && _ref$batchAllCells, cellCount = _ref.cellCount, cellSizeGetter = _ref.cellSizeGetter, estimatedCellSize = _ref.estimatedCellSize;
(0, _classCallCheck3.default)(this, CellSizeAndPositionManager), this._cellSizeAndPositionData = {},
this._lastMeasuredIndex = -1, this._lastBatchedIndex = -1, this._batchAllCells = batchAllCells,
this._cellSizeGetter = cellSizeGetter, this._cellCount = cellCount, this._estimatedCellSize = estimatedCellSize;
}
return (0, _createClass3.default)(CellSizeAndPositionManager, [ {
key: "areOffsetsAdjusted",
value: function() {
return !1;
}
}, {
key: "configure",
value: function(_ref2) {
var cellCount = _ref2.cellCount, estimatedCellSize = _ref2.estimatedCellSize;
this._cellCount = cellCount, this._estimatedCellSize = estimatedCellSize;
}
}, {
key: "getCellCount",
value: function() {
return this._cellCount;
}
}, {
key: "getEstimatedCellSize",
value: function() {
return this._estimatedCellSize;
}
}, {
key: "getLastMeasuredIndex",
value: function() {
return this._lastMeasuredIndex;
}
}, {
key: "getOffsetAdjustment",
value: function() {
return 0;
}
}, {
key: "getSizeAndPositionOfCell",
value: function(index) {
if (index < 0 || index >= this._cellCount) throw Error("Requested index " + index + " is outside of range 0.." + this._cellCount);
if (index > this._lastMeasuredIndex) for (var lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(), _offset = lastMeasuredCellSizeAndPosition.offset + lastMeasuredCellSizeAndPosition.size, i = this._lastMeasuredIndex + 1; i <= index; i++) {
var _size = this._cellSizeGetter({
index: i
});
if (void 0 === _size || isNaN(_size)) throw Error("Invalid size returned for cell " + i + " of value " + _size);
null === _size ? (this._cellSizeAndPositionData[i] = {
offset: _offset,
size: 0
}, this._lastBatchedIndex = index) : (this._cellSizeAndPositionData[i] = {
offset: _offset,
size: _size
}, _offset += _size, this._lastMeasuredIndex = index);
}
return this._cellSizeAndPositionData[index];
}
}, {
key: "getSizeAndPositionOfLastMeasuredCell",
value: function() {
return this._lastMeasuredIndex >= 0 ? this._cellSizeAndPositionData[this._lastMeasuredIndex] : {
offset: 0,
size: 0
};
}
}, {
key: "getTotalSize",
value: function() {
var lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(), totalSizeOfMeasuredCells = lastMeasuredCellSizeAndPosition.offset + lastMeasuredCellSizeAndPosition.size, numUnmeasuredCells = this._cellCount - this._lastMeasuredIndex - 1, totalSizeOfUnmeasuredCells = numUnmeasuredCells * this._estimatedCellSize;
return totalSizeOfMeasuredCells + totalSizeOfUnmeasuredCells;
}
}, {
key: "getUpdatedOffsetForIndex",
value: function(_ref3) {
var _ref3$align = _ref3.align, align = void 0 === _ref3$align ? "auto" : _ref3$align, containerSize = _ref3.containerSize, currentOffset = _ref3.currentOffset, targetIndex = _ref3.targetIndex;
if (containerSize <= 0) return 0;
var datum = this.getSizeAndPositionOfCell(targetIndex), maxOffset = datum.offset, minOffset = maxOffset - containerSize + datum.size, idealOffset = void 0;
switch (align) {
case "start":
idealOffset = maxOffset;
break;
case "end":
idealOffset = minOffset;
break;
case "center":
idealOffset = maxOffset - (containerSize - datum.size) / 2;
break;
default:
idealOffset = Math.max(minOffset, Math.min(maxOffset, currentOffset));
}
var totalSize = this.getTotalSize();
return Math.max(0, Math.min(totalSize - containerSize, idealOffset));
}
}, {
key: "getVisibleCellRange",
value: function(params) {
if (this._batchAllCells) return {
start: 0,
stop: this._cellCount - 1
};
var containerSize = params.containerSize, offset = params.offset, totalSize = this.getTotalSize();
if (0 === totalSize) return {};
var maxOffset = offset + containerSize, start = this._findNearestCell(offset), datum = this.getSizeAndPositionOfCell(start);
offset = datum.offset + datum.size;
for (var stop = start; offset < maxOffset && stop < this._cellCount - 1; ) stop++,
offset += this.getSizeAndPositionOfCell(stop).size;
return {
start: start,
stop: stop
};
}
}, {
key: "resetCell",
value: function(index) {
this._lastMeasuredIndex = Math.min(this._lastMeasuredIndex, index - 1);
}
}, {
key: "_binarySearch",
value: function(high, low, offset) {
for (;low <= high; ) {
var middle = low + Math.floor((high - low) / 2), _currentOffset = this.getSizeAndPositionOfCell(middle).offset;
if (_currentOffset === offset) return middle;
_currentOffset < offset ? low = middle + 1 : _currentOffset > offset && (high = middle - 1);
}
return low > 0 ? low - 1 : 0;
}
}, {
key: "_exponentialSearch",
value: function(index, offset) {
for (var interval = 1; index < this._cellCount && this.getSizeAndPositionOfCell(index).offset < offset; ) index += interval,
interval *= 2;
return this._binarySearch(Math.min(index, this._cellCount - 1), Math.floor(index / 2), offset);
}
}, {
key: "_findNearestCell",
value: function(offset) {
if (isNaN(offset)) throw Error("Invalid offset " + offset + " specified");
offset = Math.max(0, offset);
var lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(), lastMeasuredIndex = Math.max(0, this._lastMeasuredIndex);
return lastMeasuredCellSizeAndPosition.offset >= offset ? this._binarySearch(lastMeasuredIndex, 0, offset) : this._exponentialSearch(lastMeasuredIndex, offset);
}
} ]), CellSizeAndPositionManager;
}();
exports.default = CellSizeAndPositionManager;
}, /* 133 */
/***/
function(module, exports) {
"use strict";
function defaultOverscanIndicesGetter(_ref) {
var cellCount = _ref.cellCount, overscanCellsCount = _ref.overscanCellsCount, scrollDirection = _ref.scrollDirection, startIndex = _ref.startIndex, stopIndex = _ref.stopIndex;
return scrollDirection === SCROLL_DIRECTION_FORWARD ? {
overscanStartIndex: Math.max(0, startIndex),
overscanStopIndex: Math.min(cellCount - 1, stopIndex + overscanCellsCount)
} : {
overscanStartIndex: Math.max(0, startIndex - overscanCellsCount),
overscanStopIndex: Math.min(cellCount - 1, stopIndex)
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.default = defaultOverscanIndicesGetter;
var SCROLL_DIRECTION_FORWARD = (exports.SCROLL_DIRECTION_BACKWARD = -1, exports.SCROLL_DIRECTION_FORWARD = 1);
exports.SCROLL_DIRECTION_HORIZONTAL = "horizontal", exports.SCROLL_DIRECTION_VERTICAL = "vertical";
}, /* 134 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function updateScrollIndexHelper(_ref) {
var cellSize = _ref.cellSize, cellSizeAndPositionManager = _ref.cellSizeAndPositionManager, previousCellsCount = _ref.previousCellsCount, previousCellSize = _ref.previousCellSize, previousScrollToAlignment = _ref.previousScrollToAlignment, previousScrollToIndex = _ref.previousScrollToIndex, previousSize = _ref.previousSize, scrollOffset = _ref.scrollOffset, scrollToAlignment = _ref.scrollToAlignment, scrollToIndex = _ref.scrollToIndex, size = _ref.size, sizeJustIncreasedFromZero = _ref.sizeJustIncreasedFromZero, updateScrollIndexCallback = _ref.updateScrollIndexCallback, cellCount = cellSizeAndPositionManager.getCellCount(), hasScrollToIndex = scrollToIndex >= 0 && scrollToIndex < cellCount, sizeHasChanged = size !== previousSize || sizeJustIncreasedFromZero || !previousCellSize || "number" == typeof cellSize && cellSize !== previousCellSize;
hasScrollToIndex && (sizeHasChanged || scrollToAlignment !== previousScrollToAlignment || scrollToIndex !== previousScrollToIndex) ? updateScrollIndexCallback(scrollToIndex) : !hasScrollToIndex && cellCount > 0 && (size < previousSize || cellCount < previousCellsCount) && scrollOffset > cellSizeAndPositionManager.getTotalSize() - size && updateScrollIndexCallback(cellCount - 1);
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.default = updateScrollIndexHelper;
var _ScalingCellSizeAndPositionManager = __webpack_require__(131);
_interopRequireDefault(_ScalingCellSizeAndPositionManager);
}, /* 135 */
/***/
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */
(function(process) {
"use strict";
function defaultCellRangeRenderer(_ref) {
for (var cellCache = _ref.cellCache, cellRenderer = _ref.cellRenderer, columnSizeAndPositionManager = _ref.columnSizeAndPositionManager, columnStartIndex = _ref.columnStartIndex, columnStopIndex = _ref.columnStopIndex, deferredMeasurementCache = _ref.deferredMeasurementCache, horizontalOffsetAdjustment = _ref.horizontalOffsetAdjustment, isScrolling = _ref.isScrolling, parent = _ref.parent, rowSizeAndPositionManager = _ref.rowSizeAndPositionManager, rowStartIndex = _ref.rowStartIndex, rowStopIndex = _ref.rowStopIndex, styleCache = _ref.styleCache, verticalOffsetAdjustment = _ref.verticalOffsetAdjustment, visibleColumnIndices = _ref.visibleColumnIndices, visibleRowIndices = _ref.visibleRowIndices, renderedCells = [], areOffsetsAdjusted = columnSizeAndPositionManager.areOffsetsAdjusted() || rowSizeAndPositionManager.areOffsetsAdjusted(), canCacheStyle = !isScrolling && !areOffsetsAdjusted, rowIndex = rowStartIndex; rowIndex <= rowStopIndex; rowIndex++) for (var rowDatum = rowSizeAndPositionManager.getSizeAndPositionOfCell(rowIndex), columnIndex = columnStartIndex; columnIndex <= columnStopIndex; columnIndex++) {
var columnDatum = columnSizeAndPositionManager.getSizeAndPositionOfCell(columnIndex), isVisible = columnIndex >= visibleColumnIndices.start && columnIndex <= visibleColumnIndices.stop && rowIndex >= visibleRowIndices.start && rowIndex <= visibleRowIndices.stop, key = rowIndex + "-" + columnIndex, style = void 0;
canCacheStyle && styleCache[key] ? style = styleCache[key] : deferredMeasurementCache && !deferredMeasurementCache.has(rowIndex, columnIndex) ? style = {
height: "auto",
left: 0,
position: "absolute",
top: 0,
width: "auto"
} : (style = {
height: rowDatum.size,
left: columnDatum.offset + horizontalOffsetAdjustment,
position: "absolute",
top: rowDatum.offset + verticalOffsetAdjustment,
width: columnDatum.size
}, styleCache[key] = style);
var cellRendererParams = {
columnIndex: columnIndex,
isScrolling: isScrolling,
isVisible: isVisible,
key: key,
parent: parent,
rowIndex: rowIndex,
style: style
}, renderedCell = void 0;
!isScrolling || horizontalOffsetAdjustment || verticalOffsetAdjustment ? renderedCell = cellRenderer(cellRendererParams) : (cellCache[key] || (cellCache[key] = cellRenderer(cellRendererParams)),
renderedCell = cellCache[key]), null != renderedCell && renderedCell !== !1 && ("production" !== process.env.NODE_ENV && warnAboutMissingStyle(parent, renderedCell),
renderedCells.push(renderedCell));
}
return renderedCells;
}
function warnAboutMissingStyle(parent, renderedCell) {
"production" !== process.env.NODE_ENV && renderedCell && (renderedCell.type && renderedCell.type.__internalCellMeasurerFlag && (renderedCell = renderedCell.props.children),
renderedCell && renderedCell.props && void 0 === renderedCell.props.style && parent.__warnedAboutMissingStyle !== !0 && (parent.__warnedAboutMissingStyle = !0,
console.warn("Rendered cell should include style property for positioning.")));
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.default = defaultCellRangeRenderer;
}).call(exports, __webpack_require__(95));
}, /* 136 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.requestAnimationTimeout = exports.cancelAnimationTimeout = void 0;
var _animationFrame = __webpack_require__(137);
exports.cancelAnimationTimeout = function(frame) {
return (0, _animationFrame.caf)(frame.id);
}, exports.requestAnimationTimeout = function(callback, delay) {
var start = Date.now(), timeout = function timeout() {
Date.now() - start >= delay ? callback.call() : frame.id = (0, _animationFrame.raf)(timeout);
}, frame = {
id: (0, _animationFrame.raf)(timeout)
};
return frame;
};
}, /* 137 */
/***/
function(module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: !0
});
var win = void 0;
win = "undefined" != typeof window ? window : "undefined" != typeof self ? self : {};
var request = win.requestAnimationFrame || win.webkitRequestAnimationFrame || win.mozRequestAnimationFrame || win.oRequestAnimationFrame || win.msRequestAnimationFrame || function(callback) {
return win.setTimeout(callback, 1e3 / 60);
}, cancel = win.cancelAnimationFrame || win.webkitCancelAnimationFrame || win.mozCancelAnimationFrame || win.oCancelAnimationFrame || win.msCancelAnimationFrame || function(id) {
win.clearTimeout(id);
};
exports.raf = request, exports.caf = cancel;
}, /* 138 */
/***/
function(module, exports) {
"use strict";
function defaultOverscanIndicesGetter(_ref) {
var cellCount = _ref.cellCount, overscanCellsCount = _ref.overscanCellsCount, scrollDirection = _ref.scrollDirection, startIndex = _ref.startIndex, stopIndex = _ref.stopIndex;
return overscanCellsCount = Math.max(1, overscanCellsCount), scrollDirection === SCROLL_DIRECTION_FORWARD ? {
overscanStartIndex: Math.max(0, startIndex - 1),
overscanStopIndex: Math.min(cellCount - 1, stopIndex + overscanCellsCount)
} : {
overscanStartIndex: Math.max(0, startIndex - overscanCellsCount),
overscanStopIndex: Math.min(cellCount - 1, stopIndex + 1)
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.default = defaultOverscanIndicesGetter;
var SCROLL_DIRECTION_FORWARD = (exports.SCROLL_DIRECTION_BACKWARD = -1, exports.SCROLL_DIRECTION_FORWARD = 1);
exports.SCROLL_DIRECTION_HORIZONTAL = "horizontal", exports.SCROLL_DIRECTION_VERTICAL = "vertical";
}, /* 139 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.InfiniteLoader = void 0;
var _InfiniteLoader = __webpack_require__(140), _InfiniteLoader2 = _interopRequireDefault(_InfiniteLoader);
exports.default = _InfiniteLoader2.default, exports.InfiniteLoader = _InfiniteLoader2.default;
}, /* 140 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function isRangeVisible(_ref2) {
var lastRenderedStartIndex = _ref2.lastRenderedStartIndex, lastRenderedStopIndex = _ref2.lastRenderedStopIndex, startIndex = _ref2.startIndex, stopIndex = _ref2.stopIndex;
return !(startIndex > lastRenderedStopIndex || stopIndex < lastRenderedStartIndex);
}
function scanForUnloadedRanges(_ref3) {
for (var isRowLoaded = _ref3.isRowLoaded, minimumBatchSize = _ref3.minimumBatchSize, rowCount = _ref3.rowCount, startIndex = _ref3.startIndex, stopIndex = _ref3.stopIndex, unloadedRanges = [], rangeStartIndex = null, rangeStopIndex = null, index = startIndex; index <= stopIndex; index++) {
var loaded = isRowLoaded({
index: index
});
loaded ? null !== rangeStopIndex && (unloadedRanges.push({
startIndex: rangeStartIndex,
stopIndex: rangeStopIndex
}), rangeStartIndex = rangeStopIndex = null) : (rangeStopIndex = index, null === rangeStartIndex && (rangeStartIndex = index));
}
if (null !== rangeStopIndex) {
for (var potentialStopIndex = Math.min(Math.max(rangeStopIndex, rangeStartIndex + minimumBatchSize - 1), rowCount - 1), _index = rangeStopIndex + 1; _index <= potentialStopIndex && !isRowLoaded({
index: _index
}); _index++) rangeStopIndex = _index;
unloadedRanges.push({
startIndex: rangeStartIndex,
stopIndex: rangeStopIndex
});
}
if (unloadedRanges.length) for (var firstUnloadedRange = unloadedRanges[0]; firstUnloadedRange.stopIndex - firstUnloadedRange.startIndex + 1 < minimumBatchSize && firstUnloadedRange.startIndex > 0; ) {
var _index2 = firstUnloadedRange.startIndex - 1;
if (isRowLoaded({
index: _index2
})) break;
firstUnloadedRange.startIndex = _index2;
}
return unloadedRanges;
}
function forceUpdateReactVirtualizedComponent(component) {
var currentIndex = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0, recomputeSize = "function" == typeof component.recomputeGridSize ? component.recomputeGridSize : component.recomputeRowHeights;
recomputeSize ? recomputeSize.call(component, currentIndex) : component.forceUpdate();
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2);
exports.isRangeVisible = isRangeVisible, exports.scanForUnloadedRanges = scanForUnloadedRanges,
exports.forceUpdateReactVirtualizedComponent = forceUpdateReactVirtualizedComponent;
var _react = __webpack_require__(89), _propTypes = __webpack_require__(106), _propTypes2 = _interopRequireDefault(_propTypes), _createCallbackMemoizer = __webpack_require__(115), _createCallbackMemoizer2 = _interopRequireDefault(_createCallbackMemoizer), InfiniteLoader = function(_PureComponent) {
function InfiniteLoader(props, context) {
(0, _classCallCheck3.default)(this, InfiniteLoader);
var _this = (0, _possibleConstructorReturn3.default)(this, (InfiniteLoader.__proto__ || (0,
_getPrototypeOf2.default)(InfiniteLoader)).call(this, props, context));
return _this._loadMoreRowsMemoizer = (0, _createCallbackMemoizer2.default)(), _this._onRowsRendered = _this._onRowsRendered.bind(_this),
_this._registerChild = _this._registerChild.bind(_this), _this;
}
return (0, _inherits3.default)(InfiniteLoader, _PureComponent), (0, _createClass3.default)(InfiniteLoader, [ {
key: "resetLoadMoreRowsCache",
value: function(autoReload) {
this._loadMoreRowsMemoizer = (0, _createCallbackMemoizer2.default)(), autoReload && this._doStuff(this._lastRenderedStartIndex, this._lastRenderedStopIndex);
}
}, {
key: "render",
value: function() {
var children = this.props.children;
return children({
onRowsRendered: this._onRowsRendered,
registerChild: this._registerChild
});
}
}, {
key: "_loadUnloadedRanges",
value: function(unloadedRanges) {
var _this2 = this, loadMoreRows = this.props.loadMoreRows;
unloadedRanges.forEach(function(unloadedRange) {
var promise = loadMoreRows(unloadedRange);
promise && promise.then(function() {
isRangeVisible({
lastRenderedStartIndex: _this2._lastRenderedStartIndex,
lastRenderedStopIndex: _this2._lastRenderedStopIndex,
startIndex: unloadedRange.startIndex,
stopIndex: unloadedRange.stopIndex
}) && _this2._registeredChild && forceUpdateReactVirtualizedComponent(_this2._registeredChild, _this2._lastRenderedStartIndex);
});
});
}
}, {
key: "_onRowsRendered",
value: function(_ref) {
var startIndex = _ref.startIndex, stopIndex = _ref.stopIndex;
this._lastRenderedStartIndex = startIndex, this._lastRenderedStopIndex = stopIndex,
this._doStuff(startIndex, stopIndex);
}
}, {
key: "_doStuff",
value: function(startIndex, stopIndex) {
var _this3 = this, _props = this.props, isRowLoaded = _props.isRowLoaded, minimumBatchSize = _props.minimumBatchSize, rowCount = _props.rowCount, threshold = _props.threshold, unloadedRanges = scanForUnloadedRanges({
isRowLoaded: isRowLoaded,
minimumBatchSize: minimumBatchSize,
rowCount: rowCount,
startIndex: Math.max(0, startIndex - threshold),
stopIndex: Math.min(rowCount - 1, stopIndex + threshold)
}), squashedUnloadedRanges = unloadedRanges.reduce(function(reduced, unloadedRange) {
return reduced.concat([ unloadedRange.startIndex, unloadedRange.stopIndex ]);
}, []);
this._loadMoreRowsMemoizer({
callback: function() {
_this3._loadUnloadedRanges(unloadedRanges);
},
indices: {
squashedUnloadedRanges: squashedUnloadedRanges
}
});
}
}, {
key: "_registerChild",
value: function(registeredChild) {
this._registeredChild = registeredChild;
}
} ]), InfiniteLoader;
}(_react.PureComponent);
InfiniteLoader.propTypes = {
children: _propTypes2.default.func.isRequired,
isRowLoaded: _propTypes2.default.func.isRequired,
loadMoreRows: _propTypes2.default.func.isRequired,
minimumBatchSize: _propTypes2.default.number.isRequired,
rowCount: _propTypes2.default.number.isRequired,
threshold: _propTypes2.default.number.isRequired
}, InfiniteLoader.defaultProps = {
minimumBatchSize: 10,
rowCount: 0,
threshold: 15
}, exports.default = InfiniteLoader;
}, /* 141 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _List = __webpack_require__(142);
Object.defineProperty(exports, "default", {
enumerable: !0,
get: function() {
return _interopRequireDefault(_List).default;
}
}), Object.defineProperty(exports, "List", {
enumerable: !0,
get: function() {
return _interopRequireDefault(_List).default;
}
});
}, /* 142 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _extends2 = __webpack_require__(100), _extends3 = _interopRequireDefault(_extends2), _getOwnPropertyDescriptor = __webpack_require__(143), _getOwnPropertyDescriptor2 = _interopRequireDefault(_getOwnPropertyDescriptor), _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _Grid = __webpack_require__(127), _Grid2 = _interopRequireDefault(_Grid), _react = __webpack_require__(89), _react2 = _interopRequireDefault(_react), _classnames = __webpack_require__(114), _classnames2 = _interopRequireDefault(_classnames), List = function(_React$PureComponent) {
function List() {
var _ref, _temp, _this, _ret;
(0, _classCallCheck3.default)(this, List);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
return _temp = _this = (0, _possibleConstructorReturn3.default)(this, (_ref = List.__proto__ || (0,
_getPrototypeOf2.default)(List)).call.apply(_ref, [ this ].concat(args))), _this._cellRenderer = function(_ref2) {
var rowIndex = _ref2.rowIndex, style = _ref2.style, isScrolling = _ref2.isScrolling, isVisible = _ref2.isVisible, key = _ref2.key, rowRenderer = _this.props.rowRenderer, _Object$getOwnPropert = (0,
_getOwnPropertyDescriptor2.default)(style, "width"), writable = _Object$getOwnPropert.writable;
return writable && (style.width = "100%"), rowRenderer({
index: rowIndex,
style: style,
isScrolling: isScrolling,
isVisible: isVisible,
key: key,
parent: _this
});
}, _this._setRef = function(ref) {
_this.Grid = ref;
}, _this._onScroll = function(_ref3) {
var clientHeight = _ref3.clientHeight, scrollHeight = _ref3.scrollHeight, scrollTop = _ref3.scrollTop, onScroll = _this.props.onScroll;
onScroll({
clientHeight: clientHeight,
scrollHeight: scrollHeight,
scrollTop: scrollTop
});
}, _this._onSectionRendered = function(_ref4) {
var rowOverscanStartIndex = _ref4.rowOverscanStartIndex, rowOverscanStopIndex = _ref4.rowOverscanStopIndex, rowStartIndex = _ref4.rowStartIndex, rowStopIndex = _ref4.rowStopIndex, onRowsRendered = _this.props.onRowsRendered;
onRowsRendered({
overscanStartIndex: rowOverscanStartIndex,
overscanStopIndex: rowOverscanStopIndex,
startIndex: rowStartIndex,
stopIndex: rowStopIndex
});
}, _ret = _temp, (0, _possibleConstructorReturn3.default)(_this, _ret);
}
return (0, _inherits3.default)(List, _React$PureComponent), (0, _createClass3.default)(List, [ {
key: "forceUpdateGrid",
value: function() {
this.Grid && this.Grid.forceUpdate();
}
}, {
key: "getOffsetForRow",
value: function(_ref5) {
var alignment = _ref5.alignment, index = _ref5.index;
if (this.Grid) {
var _Grid$getOffsetForCel = this.Grid.getOffsetForCell({
alignment: alignment,
rowIndex: index,
columnIndex: 0
}), _scrollTop = _Grid$getOffsetForCel.scrollTop;
return _scrollTop;
}
return 0;
}
}, {
key: "invalidateCellSizeAfterRender",
value: function(_ref6) {
var columnIndex = _ref6.columnIndex, rowIndex = _ref6.rowIndex;
this.Grid && this.Grid.invalidateCellSizeAfterRender({
rowIndex: rowIndex,
columnIndex: columnIndex
});
}
}, {
key: "measureAllRows",
value: function() {
this.Grid && this.Grid.measureAllCells();
}
}, {
key: "recomputeGridSize",
value: function() {
var _ref7 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}, _ref7$columnIndex = _ref7.columnIndex, columnIndex = void 0 === _ref7$columnIndex ? 0 : _ref7$columnIndex, _ref7$rowIndex = _ref7.rowIndex, rowIndex = void 0 === _ref7$rowIndex ? 0 : _ref7$rowIndex;
this.Grid && this.Grid.recomputeGridSize({
rowIndex: rowIndex,
columnIndex: columnIndex
});
}
}, {
key: "recomputeRowHeights",
value: function() {
var index = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : 0;
this.Grid && this.Grid.recomputeGridSize({
rowIndex: index,
columnIndex: 0
});
}
}, {
key: "scrollToPosition",
value: function() {
var scrollTop = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : 0;
this.Grid && this.Grid.scrollToPosition({
scrollTop: scrollTop
});
}
}, {
key: "scrollToRow",
value: function() {
var index = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : 0;
this.Grid && this.Grid.scrollToCell({
columnIndex: 0,
rowIndex: index
});
}
}, {
key: "render",
value: function() {
var _props = this.props, className = _props.className, noRowsRenderer = _props.noRowsRenderer, scrollToIndex = _props.scrollToIndex, width = _props.width, classNames = (0,
_classnames2.default)("ReactVirtualized__List", className);
return _react2.default.createElement(_Grid2.default, (0, _extends3.default)({}, this.props, {
autoContainerWidth: !0,
cellRenderer: this._cellRenderer,
className: classNames,
columnWidth: width,
columnCount: 1,
noContentRenderer: noRowsRenderer,
onScroll: this._onScroll,
onSectionRendered: this._onSectionRendered,
ref: this._setRef,
scrollToRow: scrollToIndex
}));
}
} ]), List;
}(_react2.default.PureComponent);
List.defaultProps = {
autoHeight: !1,
estimatedRowSize: 30,
onScroll: function() {},
noRowsRenderer: function() {
return null;
},
onRowsRendered: function() {},
overscanIndicesGetter: _Grid.accessibilityOverscanIndicesGetter,
overscanRowCount: 10,
scrollToAlignment: "auto",
scrollToIndex: -1,
style: {}
}, exports.default = List;
}, /* 143 */
/***/
function(module, exports, __webpack_require__) {
module.exports = {
default: __webpack_require__(144),
__esModule: !0
};
}, /* 144 */
/***/
function(module, exports, __webpack_require__) {
__webpack_require__(145);
var $Object = __webpack_require__(16).Object;
module.exports = function(it, key) {
return $Object.getOwnPropertyDescriptor(it, key);
};
}, /* 145 */
/***/
function(module, exports, __webpack_require__) {
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
var toIObject = __webpack_require__(50), $getOwnPropertyDescriptor = __webpack_require__(77).f;
__webpack_require__(14)("getOwnPropertyDescriptor", function() {
return function(it, key) {
return $getOwnPropertyDescriptor(toIObject(it), key);
};
});
}, /* 146 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.Masonry = exports.createCellPositioner = void 0;
var _createCellPositioner = __webpack_require__(147), _createCellPositioner2 = _interopRequireDefault(_createCellPositioner), _Masonry = __webpack_require__(148), _Masonry2 = _interopRequireDefault(_Masonry);
exports.default = _Masonry2.default, exports.createCellPositioner = _createCellPositioner2.default,
exports.Masonry = _Masonry2.default;
}, /* 147 */
/***/
function(module, exports) {
"use strict";
function createCellPositioner(_ref) {
function cellPositioner(index) {
for (var columnIndex = 0, i = 1; i < columnHeights.length; i++) columnHeights[i] < columnHeights[columnIndex] && (columnIndex = i);
var left = columnIndex * (columnWidth + spacer), top = columnHeights[columnIndex] || 0;
return columnHeights[columnIndex] = top + cellMeasurerCache.getHeight(index) + spacer,
{
left: left,
top: top
};
}
function initOrResetDerivedValues() {
columnHeights = [];
for (var i = 0; i < columnCount; i++) columnHeights[i] = 0;
}
function reset(params) {
columnCount = params.columnCount, columnWidth = params.columnWidth, spacer = params.spacer,
initOrResetDerivedValues();
}
var cellMeasurerCache = _ref.cellMeasurerCache, columnCount = _ref.columnCount, columnWidth = _ref.columnWidth, _ref$spacer = _ref.spacer, spacer = void 0 === _ref$spacer ? 0 : _ref$spacer, columnHeights = void 0;
return initOrResetDerivedValues(), cellPositioner.reset = reset, cellPositioner;
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.default = createCellPositioner;
}, /* 148 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function identity(value) {
return value;
}
function noop() {}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.DEFAULT_SCROLLING_RESET_TIME_INTERVAL = void 0;
var _extends2 = __webpack_require__(100), _extends3 = _interopRequireDefault(_extends2), _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _react = __webpack_require__(89), _react2 = _interopRequireDefault(_react), _classnames = __webpack_require__(114), _classnames2 = _interopRequireDefault(_classnames), _PositionCache = __webpack_require__(149), _PositionCache2 = _interopRequireDefault(_PositionCache), _requestAnimationTimeout = __webpack_require__(136), emptyObject = {}, DEFAULT_SCROLLING_RESET_TIME_INTERVAL = exports.DEFAULT_SCROLLING_RESET_TIME_INTERVAL = 150, Masonry = function(_PureComponent) {
function Masonry(props, context) {
(0, _classCallCheck3.default)(this, Masonry);
var _this = (0, _possibleConstructorReturn3.default)(this, (Masonry.__proto__ || (0,
_getPrototypeOf2.default)(Masonry)).call(this, props, context));
return _this._invalidateOnUpdateStartIndex = null, _this._invalidateOnUpdateStopIndex = null,
_this._positionCache = new _PositionCache2.default(), _this._startIndex = null,
_this._startIndexMemoized = null, _this._stopIndex = null, _this._stopIndexMemoized = null,
_this.state = {
isScrolling: !1,
scrollTop: 0
}, _this._debounceResetIsScrollingCallback = _this._debounceResetIsScrollingCallback.bind(_this),
_this._setScrollingContainerRef = _this._setScrollingContainerRef.bind(_this), _this._onScroll = _this._onScroll.bind(_this),
_this;
}
return (0, _inherits3.default)(Masonry, _PureComponent), (0, _createClass3.default)(Masonry, [ {
key: "clearCellPositions",
value: function() {
this._positionCache = new _PositionCache2.default(), this.forceUpdate();
}
}, {
key: "invalidateCellSizeAfterRender",
value: function(_ref) {
var index = _ref.rowIndex;
null === this._invalidateOnUpdateStartIndex ? (this._invalidateOnUpdateStartIndex = index,
this._invalidateOnUpdateStopIndex = index) : (this._invalidateOnUpdateStartIndex = Math.min(this._invalidateOnUpdateStartIndex, index),
this._invalidateOnUpdateStopIndex = Math.max(this._invalidateOnUpdateStopIndex, index));
}
}, {
key: "recomputeCellPositions",
value: function() {
var stopIndex = this._positionCache.count - 1;
this._positionCache = new _PositionCache2.default(), this._populatePositionCache(0, stopIndex),
this.forceUpdate();
}
}, {
key: "componentDidMount",
value: function() {
this._checkInvalidateOnUpdate(), this._invokeOnScrollCallback(), this._invokeOnCellsRenderedCallback();
}
}, {
key: "componentDidUpdate",
value: function() {
this._checkInvalidateOnUpdate(), this._invokeOnScrollCallback(), this._invokeOnCellsRenderedCallback();
}
}, {
key: "componentWillUnmount",
value: function() {
this._debounceResetIsScrollingId && (0, _requestAnimationTimeout.cancelAnimationTimeout)(this._debounceResetIsScrollingId);
}
}, {
key: "componentWillReceiveProps",
value: function(nextProps) {
var scrollTop = this.props.scrollTop;
scrollTop !== nextProps.scrollTop && (this._debounceResetIsScrolling(), this.setState({
isScrolling: !0,
scrollTop: nextProps.scrollTop
}));
}
}, {
key: "render",
value: function() {
var _this2 = this, _props = this.props, autoHeight = _props.autoHeight, cellCount = _props.cellCount, cellMeasurerCache = _props.cellMeasurerCache, cellRenderer = _props.cellRenderer, className = _props.className, height = _props.height, id = _props.id, keyMapper = _props.keyMapper, overscanByPixels = _props.overscanByPixels, role = _props.role, style = _props.style, tabIndex = _props.tabIndex, width = _props.width, _state = this.state, isScrolling = _state.isScrolling, scrollTop = _state.scrollTop, children = [], estimateTotalHeight = this._getEstimatedTotalHeight(), shortestColumnSize = this._positionCache.shortestColumnSize, measuredCellCount = this._positionCache.count, startIndex = 0, stopIndex = void 0;
if (this._positionCache.range(Math.max(0, scrollTop - overscanByPixels), height + 2 * overscanByPixels, function(index, left, top) {
"undefined" == typeof stopIndex ? (startIndex = index, stopIndex = index) : (startIndex = Math.min(startIndex, index),
stopIndex = Math.max(stopIndex, index)), children.push(cellRenderer({
index: index,
isScrolling: isScrolling,
key: keyMapper(index),
parent: _this2,
style: {
height: cellMeasurerCache.getHeight(index),
left: left,
position: "absolute",
top: top,
width: cellMeasurerCache.getWidth(index)
}
}));
}), shortestColumnSize < scrollTop + height + overscanByPixels && measuredCellCount < cellCount) for (var batchSize = Math.min(cellCount - measuredCellCount, Math.ceil((scrollTop + height + overscanByPixels - shortestColumnSize) / cellMeasurerCache.defaultHeight * width / cellMeasurerCache.defaultWidth)), _index = measuredCellCount; _index < measuredCellCount + batchSize; _index++) stopIndex = _index,
children.push(cellRenderer({
index: _index,
isScrolling: isScrolling,
key: keyMapper(_index),
parent: this,
style: {
width: cellMeasurerCache.getWidth(_index)
}
}));
return this._startIndex = startIndex, this._stopIndex = stopIndex, _react2.default.createElement("div", {
ref: this._setScrollingContainerRef,
"aria-label": this.props["aria-label"],
className: (0, _classnames2.default)("ReactVirtualized__Masonry", className),
id: id,
onScroll: this._onScroll,
role: role,
style: (0, _extends3.default)({
boxSizing: "border-box",
direction: "ltr",
height: autoHeight ? "auto" : height,
overflowX: "hidden",
overflowY: estimateTotalHeight < height ? "hidden" : "auto",
position: "relative",
width: width,
WebkitOverflowScrolling: "touch",
willChange: "transform"
}, style),
tabIndex: tabIndex
}, _react2.default.createElement("div", {
className: "ReactVirtualized__Masonry__innerScrollContainer",
style: {
width: "100%",
height: estimateTotalHeight,
maxWidth: "100%",
maxHeight: estimateTotalHeight,
overflow: "hidden",
pointerEvents: isScrolling ? "none" : "",
position: "relative"
}
}, children));
}
}, {
key: "_checkInvalidateOnUpdate",
value: function() {
if ("number" == typeof this._invalidateOnUpdateStartIndex) {
var _startIndex = this._invalidateOnUpdateStartIndex, _stopIndex = this._invalidateOnUpdateStopIndex;
this._invalidateOnUpdateStartIndex = null, this._invalidateOnUpdateStopIndex = null,
this._populatePositionCache(_startIndex, _stopIndex), this.forceUpdate();
}
}
}, {
key: "_debounceResetIsScrolling",
value: function() {
var scrollingResetTimeInterval = this.props.scrollingResetTimeInterval;
this._debounceResetIsScrollingId && (0, _requestAnimationTimeout.cancelAnimationTimeout)(this._debounceResetIsScrollingId),
this._debounceResetIsScrollingId = (0, _requestAnimationTimeout.requestAnimationTimeout)(this._debounceResetIsScrollingCallback, scrollingResetTimeInterval);
}
}, {
key: "_debounceResetIsScrollingCallback",
value: function() {
this.setState({
isScrolling: !1
});
}
}, {
key: "_getEstimatedTotalHeight",
value: function() {
var _props2 = this.props, cellCount = _props2.cellCount, cellMeasurerCache = _props2.cellMeasurerCache, width = _props2.width, estimatedColumnCount = Math.floor(width / cellMeasurerCache.defaultWidth);
return this._positionCache.estimateTotalHeight(cellCount, estimatedColumnCount, cellMeasurerCache.defaultHeight);
}
}, {
key: "_invokeOnScrollCallback",
value: function() {
var _props3 = this.props, height = _props3.height, onScroll = _props3.onScroll, scrollTop = this.state.scrollTop;
this._onScrollMemoized !== scrollTop && (onScroll({
clientHeight: height,
scrollHeight: this._getEstimatedTotalHeight(),
scrollTop: scrollTop
}), this._onScrollMemoized = scrollTop);
}
}, {
key: "_invokeOnCellsRenderedCallback",
value: function() {
if (this._startIndexMemoized !== this._startIndex || this._stopIndexMemoized !== this._stopIndex) {
var _onCellsRendered = this.props.onCellsRendered;
_onCellsRendered({
startIndex: this._startIndex,
stopIndex: this._stopIndex
}), this._startIndexMemoized = this._startIndex, this._stopIndexMemoized = this._stopIndex;
}
}
}, {
key: "_populatePositionCache",
value: function(startIndex, stopIndex) {
for (var _props4 = this.props, cellMeasurerCache = _props4.cellMeasurerCache, cellPositioner = _props4.cellPositioner, _index2 = startIndex; _index2 <= stopIndex; _index2++) {
var _cellPositioner = cellPositioner(_index2), _left = _cellPositioner.left, _top = _cellPositioner.top;
this._positionCache.setPosition(_index2, _left, _top, cellMeasurerCache.getHeight(_index2));
}
}
}, {
key: "_setScrollingContainerRef",
value: function(ref) {
this._scrollingContainer = ref;
}
}, {
key: "_onScroll",
value: function(event) {
var height = this.props.height, eventScrollTop = event.target.scrollTop, scrollTop = Math.min(Math.max(0, this._getEstimatedTotalHeight() - height), eventScrollTop);
eventScrollTop === scrollTop && (this._debounceResetIsScrolling(), this.state.scrollTop !== scrollTop && this.setState({
isScrolling: !0,
scrollTop: scrollTop
}));
}
} ]), Masonry;
}(_react.PureComponent);
Masonry.defaultProps = {
autoHeight: !1,
keyMapper: identity,
onCellsRendered: noop,
onScroll: noop,
overscanByPixels: 20,
role: "grid",
scrollingResetTimeInterval: DEFAULT_SCROLLING_RESET_TIME_INTERVAL,
style: emptyObject,
tabIndex: 0
}, exports.default = Masonry;
}, /* 149 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _slicedToArray2 = __webpack_require__(150), _slicedToArray3 = _interopRequireDefault(_slicedToArray2), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _intervalTree = __webpack_require__(159), _intervalTree2 = _interopRequireDefault(_intervalTree), PositionCache = function() {
function PositionCache() {
(0, _classCallCheck3.default)(this, PositionCache), this._columnSizeMap = {}, this._intervalTree = (0,
_intervalTree2.default)(), this._leftMap = {};
}
return (0, _createClass3.default)(PositionCache, [ {
key: "estimateTotalHeight",
value: function(cellCount, columnCount, defaultCellHeight) {
var unmeasuredCellCount = cellCount - this.count;
return this.tallestColumnSize + Math.ceil(unmeasuredCellCount / columnCount) * defaultCellHeight;
}
}, {
key: "range",
value: function(scrollTop, clientHeight, renderCallback) {
var _this = this;
this._intervalTree.queryInterval(scrollTop, scrollTop + clientHeight, function(_ref) {
var _ref2 = (0, _slicedToArray3.default)(_ref, 3), top = _ref2[0], index = (_ref2[1],
_ref2[2]);
return renderCallback(index, _this._leftMap[index], top);
});
}
}, {
key: "setPosition",
value: function(index, left, top, height) {
this._intervalTree.insert([ top, top + height, index ]), this._leftMap[index] = left;
var columnSizeMap = this._columnSizeMap, columnHeight = columnSizeMap[left];
void 0 === columnHeight ? columnSizeMap[left] = top + height : columnSizeMap[left] = Math.max(columnHeight, top + height);
}
}, {
key: "count",
get: function() {
return this._intervalTree.count;
}
}, {
key: "shortestColumnSize",
get: function() {
var columnSizeMap = this._columnSizeMap, size = 0;
for (var i in columnSizeMap) {
var height = columnSizeMap[i];
size = 0 === size ? height : Math.min(size, height);
}
return size;
}
}, {
key: "tallestColumnSize",
get: function() {
var columnSizeMap = this._columnSizeMap, size = 0;
for (var i in columnSizeMap) {
var height = columnSizeMap[i];
size = Math.max(size, height);
}
return size;
}
} ]), PositionCache;
}();
exports.default = PositionCache;
}, /* 150 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
exports.__esModule = !0;
var _isIterable2 = __webpack_require__(151), _isIterable3 = _interopRequireDefault(_isIterable2), _getIterator2 = __webpack_require__(155), _getIterator3 = _interopRequireDefault(_getIterator2);
exports.default = function() {
function sliceIterator(arr, i) {
var _arr = [], _n = !0, _d = !1, _e = void 0;
try {
for (var _s, _i = (0, _getIterator3.default)(arr); !(_n = (_s = _i.next()).done) && (_arr.push(_s.value),
!i || _arr.length !== i); _n = !0) ;
} catch (err) {
_d = !0, _e = err;
} finally {
try {
!_n && _i.return && _i.return();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
return function(arr, i) {
if (Array.isArray(arr)) return arr;
if ((0, _isIterable3.default)(Object(arr))) return sliceIterator(arr, i);
throw new TypeError("Invalid attempt to destructure non-iterable instance");
};
}();
}, /* 151 */
/***/
function(module, exports, __webpack_require__) {
module.exports = {
default: __webpack_require__(152),
__esModule: !0
};
}, /* 152 */
/***/
function(module, exports, __webpack_require__) {
__webpack_require__(60), __webpack_require__(38), module.exports = __webpack_require__(153);
}, /* 153 */
/***/
function(module, exports, __webpack_require__) {
var classof = __webpack_require__(154), ITERATOR = __webpack_require__(59)("iterator"), Iterators = __webpack_require__(44);
module.exports = __webpack_require__(16).isIterable = function(it) {
var O = Object(it);
return void 0 !== O[ITERATOR] || "@@iterator" in O || Iterators.hasOwnProperty(classof(O));
};
}, /* 154 */
/***/
function(module, exports, __webpack_require__) {
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = __webpack_require__(52), TAG = __webpack_require__(59)("toStringTag"), ARG = "Arguments" == cof(function() {
return arguments;
}()), tryGet = function(it, key) {
try {
return it[key];
} catch (e) {}
};
module.exports = function(it) {
var O, T, B;
return void 0 === it ? "Undefined" : null === it ? "Null" : "string" == typeof (T = tryGet(O = Object(it), TAG)) ? T : ARG ? cof(O) : "Object" == (B = cof(O)) && "function" == typeof O.callee ? "Arguments" : B;
};
}, /* 155 */
/***/
function(module, exports, __webpack_require__) {
module.exports = {
default: __webpack_require__(156),
__esModule: !0
};
}, /* 156 */
/***/
function(module, exports, __webpack_require__) {
__webpack_require__(60), __webpack_require__(38), module.exports = __webpack_require__(157);
}, /* 157 */
/***/
function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(21), get = __webpack_require__(158);
module.exports = __webpack_require__(16).getIterator = function(it) {
var iterFn = get(it);
if ("function" != typeof iterFn) throw TypeError(it + " is not iterable!");
return anObject(iterFn.call(it));
};
}, /* 158 */
/***/
function(module, exports, __webpack_require__) {
var classof = __webpack_require__(154), ITERATOR = __webpack_require__(59)("iterator"), Iterators = __webpack_require__(44);
module.exports = __webpack_require__(16).getIteratorMethod = function(it) {
if (void 0 != it) return it[ITERATOR] || it["@@iterator"] || Iterators[classof(it)];
};
}, /* 159 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function IntervalTreeNode(mid, left, right, leftPoints, rightPoints) {
this.mid = mid, this.left = left, this.right = right, this.leftPoints = leftPoints,
this.rightPoints = rightPoints, this.count = (left ? left.count : 0) + (right ? right.count : 0) + leftPoints.length;
}
function copy(a, b) {
a.mid = b.mid, a.left = b.left, a.right = b.right, a.leftPoints = b.leftPoints,
a.rightPoints = b.rightPoints, a.count = b.count;
}
function rebuild(node, intervals) {
var ntree = createIntervalTree(intervals);
node.mid = ntree.mid, node.left = ntree.left, node.right = ntree.right, node.leftPoints = ntree.leftPoints,
node.rightPoints = ntree.rightPoints, node.count = ntree.count;
}
function rebuildWithInterval(node, interval) {
var intervals = node.intervals([]);
intervals.push(interval), rebuild(node, intervals);
}
function rebuildWithoutInterval(node, interval) {
var intervals = node.intervals([]), idx = intervals.indexOf(interval);
return idx < 0 ? NOT_FOUND : (intervals.splice(idx, 1), rebuild(node, intervals),
SUCCESS);
}
function reportLeftRange(arr, hi, cb) {
for (var i = 0; i < arr.length && arr[i][0] <= hi; ++i) {
var r = cb(arr[i]);
if (r) return r;
}
}
function reportRightRange(arr, lo, cb) {
for (var i = arr.length - 1; i >= 0 && arr[i][1] >= lo; --i) {
var r = cb(arr[i]);
if (r) return r;
}
}
function reportRange(arr, cb) {
for (var i = 0; i < arr.length; ++i) {
var r = cb(arr[i]);
if (r) return r;
}
}
function compareNumbers(a, b) {
return a - b;
}
function compareBegin(a, b) {
var d = a[0] - b[0];
return d ? d : a[1] - b[1];
}
function compareEnd(a, b) {
var d = a[1] - b[1];
return d ? d : a[0] - b[0];
}
function createIntervalTree(intervals) {
if (0 === intervals.length) return null;
for (var pts = [], i = 0; i < intervals.length; ++i) pts.push(intervals[i][0], intervals[i][1]);
pts.sort(compareNumbers);
for (var mid = pts[pts.length >> 1], leftIntervals = [], rightIntervals = [], centerIntervals = [], i = 0; i < intervals.length; ++i) {
var s = intervals[i];
s[1] < mid ? leftIntervals.push(s) : mid < s[0] ? rightIntervals.push(s) : centerIntervals.push(s);
}
var leftPoints = centerIntervals, rightPoints = centerIntervals.slice();
return leftPoints.sort(compareBegin), rightPoints.sort(compareEnd), new IntervalTreeNode(mid, createIntervalTree(leftIntervals), createIntervalTree(rightIntervals), leftPoints, rightPoints);
}
function IntervalTree(root) {
this.root = root;
}
function createWrapper(intervals) {
return new IntervalTree(intervals && 0 !== intervals.length ? createIntervalTree(intervals) : null);
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.default = createWrapper;
var _binarySearchBounds = __webpack_require__(160), _binarySearchBounds2 = _interopRequireDefault(_binarySearchBounds), NOT_FOUND = 0, SUCCESS = 1, EMPTY = 2, proto = IntervalTreeNode.prototype;
proto.intervals = function(result) {
return result.push.apply(result, this.leftPoints), this.left && this.left.intervals(result),
this.right && this.right.intervals(result), result;
}, proto.insert = function(interval) {
var weight = this.count - this.leftPoints.length;
if (this.count += 1, interval[1] < this.mid) this.left ? 4 * (this.left.count + 1) > 3 * (weight + 1) ? rebuildWithInterval(this, interval) : this.left.insert(interval) : this.left = createIntervalTree([ interval ]); else if (interval[0] > this.mid) this.right ? 4 * (this.right.count + 1) > 3 * (weight + 1) ? rebuildWithInterval(this, interval) : this.right.insert(interval) : this.right = createIntervalTree([ interval ]); else {
var l = _binarySearchBounds2.default.ge(this.leftPoints, interval, compareBegin), r = _binarySearchBounds2.default.ge(this.rightPoints, interval, compareEnd);
this.leftPoints.splice(l, 0, interval), this.rightPoints.splice(r, 0, interval);
}
}, proto.remove = function(interval) {
var weight = this.count - this.leftPoints;
if (interval[1] < this.mid) {
if (!this.left) return NOT_FOUND;
var rw = this.right ? this.right.count : 0;
if (4 * rw > 3 * (weight - 1)) return rebuildWithoutInterval(this, interval);
var r = this.left.remove(interval);
return r === EMPTY ? (this.left = null, this.count -= 1, SUCCESS) : (r === SUCCESS && (this.count -= 1),
r);
}
if (interval[0] > this.mid) {
if (!this.right) return NOT_FOUND;
var lw = this.left ? this.left.count : 0;
if (4 * lw > 3 * (weight - 1)) return rebuildWithoutInterval(this, interval);
var r = this.right.remove(interval);
return r === EMPTY ? (this.right = null, this.count -= 1, SUCCESS) : (r === SUCCESS && (this.count -= 1),
r);
}
if (1 === this.count) return this.leftPoints[0] === interval ? EMPTY : NOT_FOUND;
if (1 === this.leftPoints.length && this.leftPoints[0] === interval) {
if (this.left && this.right) {
for (var p = this, n = this.left; n.right; ) p = n, n = n.right;
if (p === this) n.right = this.right; else {
var l = this.left, r = this.right;
p.count -= n.count, p.right = n.left, n.left = l, n.right = r;
}
copy(this, n), this.count = (this.left ? this.left.count : 0) + (this.right ? this.right.count : 0) + this.leftPoints.length;
} else this.left ? copy(this, this.left) : copy(this, this.right);
return SUCCESS;
}
for (var l = _binarySearchBounds2.default.ge(this.leftPoints, interval, compareBegin); l < this.leftPoints.length && this.leftPoints[l][0] === interval[0]; ++l) if (this.leftPoints[l] === interval) {
this.count -= 1, this.leftPoints.splice(l, 1);
for (var r = _binarySearchBounds2.default.ge(this.rightPoints, interval, compareEnd); r < this.rightPoints.length && this.rightPoints[r][1] === interval[1]; ++r) if (this.rightPoints[r] === interval) return this.rightPoints.splice(r, 1),
SUCCESS;
}
return NOT_FOUND;
}, proto.queryPoint = function(x, cb) {
if (x < this.mid) {
if (this.left) {
var r = this.left.queryPoint(x, cb);
if (r) return r;
}
return reportLeftRange(this.leftPoints, x, cb);
}
if (x > this.mid) {
if (this.right) {
var r = this.right.queryPoint(x, cb);
if (r) return r;
}
return reportRightRange(this.rightPoints, x, cb);
}
return reportRange(this.leftPoints, cb);
}, proto.queryInterval = function(lo, hi, cb) {
if (lo < this.mid && this.left) {
var r = this.left.queryInterval(lo, hi, cb);
if (r) return r;
}
if (hi > this.mid && this.right) {
var r = this.right.queryInterval(lo, hi, cb);
if (r) return r;
}
return hi < this.mid ? reportLeftRange(this.leftPoints, hi, cb) : lo > this.mid ? reportRightRange(this.rightPoints, lo, cb) : reportRange(this.leftPoints, cb);
};
var tproto = IntervalTree.prototype;
tproto.insert = function(interval) {
this.root ? this.root.insert(interval) : this.root = new IntervalTreeNode(interval[0], null, null, [ interval ], [ interval ]);
}, tproto.remove = function(interval) {
if (this.root) {
var r = this.root.remove(interval);
return r === EMPTY && (this.root = null), r !== NOT_FOUND;
}
return !1;
}, tproto.queryPoint = function(p, cb) {
if (this.root) return this.root.queryPoint(p, cb);
}, tproto.queryInterval = function(lo, hi, cb) {
if (lo <= hi && this.root) return this.root.queryInterval(lo, hi, cb);
}, Object.defineProperty(tproto, "count", {
get: function() {
return this.root ? this.root.count : 0;
}
}), Object.defineProperty(tproto, "intervals", {
get: function() {
return this.root ? this.root.intervals([]) : [];
}
});
}, /* 160 */
/***/
function(module, exports) {
"use strict";
function _GEA(a, l, h, y) {
for (var i = h + 1; l <= h; ) {
var m = l + h >>> 1, x = a[m];
x >= y ? (i = m, h = m - 1) : l = m + 1;
}
return i;
}
function _GEP(a, l, h, y, c) {
for (var i = h + 1; l <= h; ) {
var m = l + h >>> 1, x = a[m];
c(x, y) >= 0 ? (i = m, h = m - 1) : l = m + 1;
}
return i;
}
function dispatchBsearchGE(a, y, c, l, h) {
return "function" == typeof c ? _GEP(a, void 0 === l ? 0 : 0 | l, void 0 === h ? a.length - 1 : 0 | h, y, c) : _GEA(a, void 0 === c ? 0 : 0 | c, void 0 === l ? a.length - 1 : 0 | l, y);
}
function _GTA(a, l, h, y) {
for (var i = h + 1; l <= h; ) {
var m = l + h >>> 1, x = a[m];
x > y ? (i = m, h = m - 1) : l = m + 1;
}
return i;
}
function _GTP(a, l, h, y, c) {
for (var i = h + 1; l <= h; ) {
var m = l + h >>> 1, x = a[m];
c(x, y) > 0 ? (i = m, h = m - 1) : l = m + 1;
}
return i;
}
function dispatchBsearchGT(a, y, c, l, h) {
return "function" == typeof c ? _GTP(a, void 0 === l ? 0 : 0 | l, void 0 === h ? a.length - 1 : 0 | h, y, c) : _GTA(a, void 0 === c ? 0 : 0 | c, void 0 === l ? a.length - 1 : 0 | l, y);
}
function _LTA(a, l, h, y) {
for (var i = l - 1; l <= h; ) {
var m = l + h >>> 1, x = a[m];
x < y ? (i = m, l = m + 1) : h = m - 1;
}
return i;
}
function _LTP(a, l, h, y, c) {
for (var i = l - 1; l <= h; ) {
var m = l + h >>> 1, x = a[m];
c(x, y) < 0 ? (i = m, l = m + 1) : h = m - 1;
}
return i;
}
function dispatchBsearchLT(a, y, c, l, h) {
return "function" == typeof c ? _LTP(a, void 0 === l ? 0 : 0 | l, void 0 === h ? a.length - 1 : 0 | h, y, c) : _LTA(a, void 0 === c ? 0 : 0 | c, void 0 === l ? a.length - 1 : 0 | l, y);
}
function _LEA(a, l, h, y) {
for (var i = l - 1; l <= h; ) {
var m = l + h >>> 1, x = a[m];
x <= y ? (i = m, l = m + 1) : h = m - 1;
}
return i;
}
function _LEP(a, l, h, y, c) {
for (var i = l - 1; l <= h; ) {
var m = l + h >>> 1, x = a[m];
c(x, y) <= 0 ? (i = m, l = m + 1) : h = m - 1;
}
return i;
}
function dispatchBsearchLE(a, y, c, l, h) {
return "function" == typeof c ? _LEP(a, void 0 === l ? 0 : 0 | l, void 0 === h ? a.length - 1 : 0 | h, y, c) : _LEA(a, void 0 === c ? 0 : 0 | c, void 0 === l ? a.length - 1 : 0 | l, y);
}
function _EQA(a, l, h, y) {
for (;l <= h; ) {
var m = l + h >>> 1, x = a[m];
if (x === y) return m;
x <= y ? l = m + 1 : h = m - 1;
}
return -1;
}
function _EQP(a, l, h, y, c) {
for (;l <= h; ) {
var m = l + h >>> 1, x = a[m], p = c(x, y);
if (0 === p) return m;
p <= 0 ? l = m + 1 : h = m - 1;
}
return -1;
}
function dispatchBsearchEQ(a, y, c, l, h) {
return "function" == typeof c ? _EQP(a, void 0 === l ? 0 : 0 | l, void 0 === h ? a.length - 1 : 0 | h, y, c) : _EQA(a, void 0 === c ? 0 : 0 | c, void 0 === l ? a.length - 1 : 0 | l, y);
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.default = {
ge: dispatchBsearchGE,
gt: dispatchBsearchGT,
lt: dispatchBsearchLT,
le: dispatchBsearchLE,
eq: dispatchBsearchEQ
};
}, /* 161 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.MultiGrid = void 0;
var _MultiGrid = __webpack_require__(162), _MultiGrid2 = _interopRequireDefault(_MultiGrid);
exports.default = _MultiGrid2.default, exports.MultiGrid = _MultiGrid2.default;
}, /* 162 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _extends2 = __webpack_require__(100), _extends3 = _interopRequireDefault(_extends2), _objectWithoutProperties2 = __webpack_require__(105), _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2), _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _propTypes = __webpack_require__(106), _propTypes2 = _interopRequireDefault(_propTypes), _react = __webpack_require__(89), _react2 = _interopRequireDefault(_react), _CellMeasurerCacheDecorator = __webpack_require__(163), _CellMeasurerCacheDecorator2 = _interopRequireDefault(_CellMeasurerCacheDecorator), _Grid = __webpack_require__(127), _Grid2 = _interopRequireDefault(_Grid), SCROLLBAR_SIZE_BUFFER = 20, MultiGrid = function(_PureComponent) {
function MultiGrid(props, context) {
(0, _classCallCheck3.default)(this, MultiGrid);
var _this = (0, _possibleConstructorReturn3.default)(this, (MultiGrid.__proto__ || (0,
_getPrototypeOf2.default)(MultiGrid)).call(this, props, context));
return _this.state = {
scrollLeft: 0,
scrollTop: 0,
scrollbarSize: 0,
showHorizontalScrollbar: !1,
showVerticalScrollbar: !1
}, _this._deferredInvalidateColumnIndex = null, _this._deferredInvalidateRowIndex = null,
_this._bottomLeftGridRef = _this._bottomLeftGridRef.bind(_this), _this._bottomRightGridRef = _this._bottomRightGridRef.bind(_this),
_this._cellRendererBottomLeftGrid = _this._cellRendererBottomLeftGrid.bind(_this),
_this._cellRendererBottomRightGrid = _this._cellRendererBottomRightGrid.bind(_this),
_this._cellRendererTopRightGrid = _this._cellRendererTopRightGrid.bind(_this), _this._columnWidthRightGrid = _this._columnWidthRightGrid.bind(_this),
_this._onScroll = _this._onScroll.bind(_this), _this._onScrollbarPresenceChange = _this._onScrollbarPresenceChange.bind(_this),
_this._onScrollLeft = _this._onScrollLeft.bind(_this), _this._onScrollTop = _this._onScrollTop.bind(_this),
_this._rowHeightBottomGrid = _this._rowHeightBottomGrid.bind(_this), _this._topLeftGridRef = _this._topLeftGridRef.bind(_this),
_this._topRightGridRef = _this._topRightGridRef.bind(_this), _this;
}
return (0, _inherits3.default)(MultiGrid, _PureComponent), (0, _createClass3.default)(MultiGrid, [ {
key: "forceUpdateGrids",
value: function() {
this._bottomLeftGrid && this._bottomLeftGrid.forceUpdate(), this._bottomRightGrid && this._bottomRightGrid.forceUpdate(),
this._topLeftGrid && this._topLeftGrid.forceUpdate(), this._topRightGrid && this._topRightGrid.forceUpdate();
}
}, {
key: "invalidateCellSizeAfterRender",
value: function() {
var _ref = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}, _ref$columnIndex = _ref.columnIndex, columnIndex = void 0 === _ref$columnIndex ? 0 : _ref$columnIndex, _ref$rowIndex = _ref.rowIndex, rowIndex = void 0 === _ref$rowIndex ? 0 : _ref$rowIndex;
this._deferredInvalidateColumnIndex = "number" == typeof this._deferredInvalidateColumnIndex ? Math.min(this._deferredInvalidateColumnIndex, columnIndex) : columnIndex,
this._deferredInvalidateRowIndex = "number" == typeof this._deferredInvalidateRowIndex ? Math.min(this._deferredInvalidateRowIndex, rowIndex) : rowIndex;
}
}, {
key: "measureAllCells",
value: function() {
this._bottomLeftGrid && this._bottomLeftGrid.measureAllCells(), this._bottomRightGrid && this._bottomRightGrid.measureAllCells(),
this._topLeftGrid && this._topLeftGrid.measureAllCells(), this._topRightGrid && this._topRightGrid.measureAllCells();
}
}, {
key: "recomputeGridSize",
value: function() {
var _ref2 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}, _ref2$columnIndex = _ref2.columnIndex, columnIndex = void 0 === _ref2$columnIndex ? 0 : _ref2$columnIndex, _ref2$rowIndex = _ref2.rowIndex, rowIndex = void 0 === _ref2$rowIndex ? 0 : _ref2$rowIndex, _props = this.props, fixedColumnCount = _props.fixedColumnCount, fixedRowCount = _props.fixedRowCount, adjustedColumnIndex = Math.max(0, columnIndex - fixedColumnCount), adjustedRowIndex = Math.max(0, rowIndex - fixedRowCount);
this._bottomLeftGrid && this._bottomLeftGrid.recomputeGridSize({
columnIndex: columnIndex,
rowIndex: adjustedRowIndex
}), this._bottomRightGrid && this._bottomRightGrid.recomputeGridSize({
columnIndex: adjustedColumnIndex,
rowIndex: adjustedRowIndex
}), this._topLeftGrid && this._topLeftGrid.recomputeGridSize({
columnIndex: columnIndex,
rowIndex: rowIndex
}), this._topRightGrid && this._topRightGrid.recomputeGridSize({
columnIndex: adjustedColumnIndex,
rowIndex: rowIndex
}), this._leftGridWidth = null, this._topGridHeight = null, this._maybeCalculateCachedStyles(null, this.props, null, this.state);
}
}, {
key: "componentDidMount",
value: function() {
var _props2 = this.props, scrollLeft = _props2.scrollLeft, scrollTop = _props2.scrollTop;
if (scrollLeft > 0 || scrollTop > 0) {
var newState = {};
scrollLeft > 0 && (newState.scrollLeft = scrollLeft), scrollTop > 0 && (newState.scrollTop = scrollTop),
this.setState(newState);
}
this._handleInvalidatedGridSize();
}
}, {
key: "componentDidUpdate",
value: function() {
this._handleInvalidatedGridSize();
}
}, {
key: "componentWillMount",
value: function() {
var _props3 = this.props, deferredMeasurementCache = _props3.deferredMeasurementCache, fixedColumnCount = _props3.fixedColumnCount, fixedRowCount = _props3.fixedRowCount;
this._maybeCalculateCachedStyles(null, this.props, null, this.state), deferredMeasurementCache && (this._deferredMeasurementCacheBottomLeftGrid = fixedRowCount > 0 ? new _CellMeasurerCacheDecorator2.default({
cellMeasurerCache: deferredMeasurementCache,
columnIndexOffset: 0,
rowIndexOffset: fixedRowCount
}) : deferredMeasurementCache, this._deferredMeasurementCacheBottomRightGrid = fixedColumnCount > 0 || fixedRowCount > 0 ? new _CellMeasurerCacheDecorator2.default({
cellMeasurerCache: deferredMeasurementCache,
columnIndexOffset: fixedColumnCount,
rowIndexOffset: fixedRowCount
}) : deferredMeasurementCache, this._deferredMeasurementCacheTopRightGrid = fixedColumnCount > 0 ? new _CellMeasurerCacheDecorator2.default({
cellMeasurerCache: deferredMeasurementCache,
columnIndexOffset: fixedColumnCount,
rowIndexOffset: 0
}) : deferredMeasurementCache);
}
}, {
key: "componentWillReceiveProps",
value: function(nextProps, nextState) {
var _props4 = this.props, columnWidth = _props4.columnWidth, fixedColumnCount = _props4.fixedColumnCount, fixedRowCount = _props4.fixedRowCount, rowHeight = _props4.rowHeight;
if (columnWidth === nextProps.columnWidth && fixedColumnCount === nextProps.fixedColumnCount || (this._leftGridWidth = null),
fixedRowCount === nextProps.fixedRowCount && rowHeight === nextProps.rowHeight || (this._topGridHeight = null),
nextProps.scrollLeft !== this.props.scrollLeft || nextProps.scrollTop !== this.props.scrollTop) {
var newState = {};
null != nextProps.scrollLeft && nextProps.scrollLeft >= 0 && (newState.scrollLeft = nextProps.scrollLeft),
null != nextProps.scrollTop && nextProps.scrollTop >= 0 && (newState.scrollTop = nextProps.scrollTop),
this.setState(newState);
}
this._maybeCalculateCachedStyles(this.props, nextProps, this.state, nextState);
}
}, {
key: "render",
value: function() {
var _props5 = this.props, onScroll = _props5.onScroll, onSectionRendered = _props5.onSectionRendered, scrollToColumn = (_props5.scrollLeft,
_props5.scrollToColumn), scrollToRow = (_props5.scrollTop, _props5.scrollToRow), rest = (0,
_objectWithoutProperties3.default)(_props5, [ "onScroll", "onSectionRendered", "scrollLeft", "scrollToColumn", "scrollTop", "scrollToRow" ]);
if (0 === this.props.width || 0 === this.props.height) return null;
var _state = this.state, scrollLeft = _state.scrollLeft, scrollTop = _state.scrollTop;
return _react2.default.createElement("div", {
style: this._containerOuterStyle
}, _react2.default.createElement("div", {
style: this._containerTopStyle
}, this._renderTopLeftGrid(rest), this._renderTopRightGrid((0, _extends3.default)({}, rest, {
onScroll: onScroll,
scrollLeft: scrollLeft
}))), _react2.default.createElement("div", {
style: this._containerBottomStyle
}, this._renderBottomLeftGrid((0, _extends3.default)({}, rest, {
onScroll: onScroll,
scrollTop: scrollTop
})), this._renderBottomRightGrid((0, _extends3.default)({}, rest, {
onScroll: onScroll,
onSectionRendered: onSectionRendered,
scrollLeft: scrollLeft,
scrollToColumn: scrollToColumn,
scrollToRow: scrollToRow,
scrollTop: scrollTop
}))));
}
}, {
key: "_bottomLeftGridRef",
value: function(ref) {
this._bottomLeftGrid = ref;
}
}, {
key: "_bottomRightGridRef",
value: function(ref) {
this._bottomRightGrid = ref;
}
}, {
key: "_cellRendererBottomLeftGrid",
value: function(_ref3) {
var rowIndex = _ref3.rowIndex, rest = (0, _objectWithoutProperties3.default)(_ref3, [ "rowIndex" ]), _props6 = this.props, cellRenderer = _props6.cellRenderer, fixedRowCount = _props6.fixedRowCount, rowCount = _props6.rowCount;
return rowIndex === rowCount - fixedRowCount ? _react2.default.createElement("div", {
key: rest.key,
style: (0, _extends3.default)({}, rest.style, {
height: SCROLLBAR_SIZE_BUFFER
})
}) : cellRenderer((0, _extends3.default)({}, rest, {
parent: this,
rowIndex: rowIndex + fixedRowCount
}));
}
}, {
key: "_cellRendererBottomRightGrid",
value: function(_ref4) {
var columnIndex = _ref4.columnIndex, rowIndex = _ref4.rowIndex, rest = (0, _objectWithoutProperties3.default)(_ref4, [ "columnIndex", "rowIndex" ]), _props7 = this.props, cellRenderer = _props7.cellRenderer, fixedColumnCount = _props7.fixedColumnCount, fixedRowCount = _props7.fixedRowCount;
return cellRenderer((0, _extends3.default)({}, rest, {
columnIndex: columnIndex + fixedColumnCount,
parent: this,
rowIndex: rowIndex + fixedRowCount
}));
}
}, {
key: "_cellRendererTopRightGrid",
value: function(_ref5) {
var columnIndex = _ref5.columnIndex, rest = (0, _objectWithoutProperties3.default)(_ref5, [ "columnIndex" ]), _props8 = this.props, cellRenderer = _props8.cellRenderer, columnCount = _props8.columnCount, fixedColumnCount = _props8.fixedColumnCount;
return columnIndex === columnCount - fixedColumnCount ? _react2.default.createElement("div", {
key: rest.key,
style: (0, _extends3.default)({}, rest.style, {
width: SCROLLBAR_SIZE_BUFFER
})
}) : cellRenderer((0, _extends3.default)({}, rest, {
columnIndex: columnIndex + fixedColumnCount,
parent: this
}));
}
}, {
key: "_columnWidthRightGrid",
value: function(_ref6) {
var index = _ref6.index, _props9 = this.props, columnCount = _props9.columnCount, fixedColumnCount = _props9.fixedColumnCount, columnWidth = _props9.columnWidth, _state2 = this.state, scrollbarSize = _state2.scrollbarSize, showHorizontalScrollbar = _state2.showHorizontalScrollbar;
return showHorizontalScrollbar && index === columnCount - fixedColumnCount ? scrollbarSize : "function" == typeof columnWidth ? columnWidth({
index: index + fixedColumnCount
}) : columnWidth;
}
}, {
key: "_getBottomGridHeight",
value: function(props) {
var height = props.height, topGridHeight = this._getTopGridHeight(props);
return height - topGridHeight;
}
}, {
key: "_getLeftGridWidth",
value: function(props) {
var fixedColumnCount = props.fixedColumnCount, columnWidth = props.columnWidth;
if (null == this._leftGridWidth) if ("function" == typeof columnWidth) {
for (var leftGridWidth = 0, index = 0; index < fixedColumnCount; index++) leftGridWidth += columnWidth({
index: index
});
this._leftGridWidth = leftGridWidth;
} else this._leftGridWidth = columnWidth * fixedColumnCount;
return this._leftGridWidth;
}
}, {
key: "_getRightGridWidth",
value: function(props) {
var width = props.width, leftGridWidth = this._getLeftGridWidth(props);
return width - leftGridWidth;
}
}, {
key: "_getTopGridHeight",
value: function(props) {
var fixedRowCount = props.fixedRowCount, rowHeight = props.rowHeight;
if (null == this._topGridHeight) if ("function" == typeof rowHeight) {
for (var topGridHeight = 0, index = 0; index < fixedRowCount; index++) topGridHeight += rowHeight({
index: index
});
this._topGridHeight = topGridHeight;
} else this._topGridHeight = rowHeight * fixedRowCount;
return this._topGridHeight;
}
}, {
key: "_handleInvalidatedGridSize",
value: function() {
if ("number" == typeof this._deferredInvalidateColumnIndex) {
var columnIndex = this._deferredInvalidateColumnIndex, rowIndex = this._deferredInvalidateRowIndex;
this._deferredInvalidateColumnIndex = null, this._deferredInvalidateRowIndex = null,
this.recomputeGridSize({
columnIndex: columnIndex,
rowIndex: rowIndex
}), this.forceUpdate();
}
}
}, {
key: "_maybeCalculateCachedStyles",
value: function(prevProps, props) {
var columnWidth = props.columnWidth, enableFixedColumnScroll = props.enableFixedColumnScroll, enableFixedRowScroll = props.enableFixedRowScroll, height = props.height, fixedColumnCount = props.fixedColumnCount, fixedRowCount = props.fixedRowCount, rowHeight = props.rowHeight, style = props.style, styleBottomLeftGrid = props.styleBottomLeftGrid, styleBottomRightGrid = props.styleBottomRightGrid, styleTopLeftGrid = props.styleTopLeftGrid, styleTopRightGrid = props.styleTopRightGrid, width = props.width, firstRender = !prevProps, sizeChange = firstRender || height !== prevProps.height || width !== prevProps.width, leftSizeChange = firstRender || columnWidth !== prevProps.columnWidth || fixedColumnCount !== prevProps.fixedColumnCount, topSizeChange = firstRender || fixedRowCount !== prevProps.fixedRowCount || rowHeight !== prevProps.rowHeight;
(firstRender || sizeChange || style !== prevProps.style) && (this._containerOuterStyle = (0,
_extends3.default)({
height: height,
overflow: "visible",
width: width
}, style)), (firstRender || sizeChange || topSizeChange) && (this._containerTopStyle = {
height: this._getTopGridHeight(props),
position: "relative",
width: width
}, this._containerBottomStyle = {
height: height - this._getTopGridHeight(props),
overflow: "visible",
position: "relative",
width: width
}), (firstRender || styleBottomLeftGrid !== prevProps.styleBottomLeftGrid) && (this._bottomLeftGridStyle = (0,
_extends3.default)({
left: 0,
overflowX: "hidden",
overflowY: enableFixedColumnScroll ? "auto" : "hidden",
position: "absolute"
}, styleBottomLeftGrid)), (firstRender || leftSizeChange || styleBottomRightGrid !== prevProps.styleBottomRightGrid) && (this._bottomRightGridStyle = (0,
_extends3.default)({
left: this._getLeftGridWidth(props),
position: "absolute"
}, styleBottomRightGrid)), (firstRender || styleTopLeftGrid !== prevProps.styleTopLeftGrid) && (this._topLeftGridStyle = (0,
_extends3.default)({
left: 0,
overflowX: "hidden",
overflowY: "hidden",
position: "absolute",
top: 0
}, styleTopLeftGrid)), (firstRender || leftSizeChange || styleTopRightGrid !== prevProps.styleTopRightGrid) && (this._topRightGridStyle = (0,
_extends3.default)({
left: this._getLeftGridWidth(props),
overflowX: enableFixedRowScroll ? "auto" : "hidden",
overflowY: "hidden",
position: "absolute",
top: 0
}, styleTopRightGrid));
}
}, {
key: "_onScroll",
value: function(scrollInfo) {
var scrollLeft = scrollInfo.scrollLeft, scrollTop = scrollInfo.scrollTop;
this.setState({
scrollLeft: scrollLeft,
scrollTop: scrollTop
});
var onScroll = this.props.onScroll;
onScroll && onScroll(scrollInfo);
}
}, {
key: "_onScrollbarPresenceChange",
value: function(_ref7) {
var horizontal = _ref7.horizontal, size = _ref7.size, vertical = _ref7.vertical, _state3 = this.state, showHorizontalScrollbar = _state3.showHorizontalScrollbar, showVerticalScrollbar = _state3.showVerticalScrollbar;
horizontal === showHorizontalScrollbar && vertical === showVerticalScrollbar || this.setState({
scrollbarSize: size,
showHorizontalScrollbar: horizontal,
showVerticalScrollbar: vertical
});
}
}, {
key: "_onScrollLeft",
value: function(scrollInfo) {
var scrollLeft = scrollInfo.scrollLeft;
this._onScroll({
scrollLeft: scrollLeft,
scrollTop: this.state.scrollTop
});
}
}, {
key: "_onScrollTop",
value: function(scrollInfo) {
var scrollTop = scrollInfo.scrollTop;
this._onScroll({
scrollTop: scrollTop,
scrollLeft: this.state.scrollLeft
});
}
}, {
key: "_renderBottomLeftGrid",
value: function(props) {
var enableFixedColumnScroll = props.enableFixedColumnScroll, fixedColumnCount = props.fixedColumnCount, fixedRowCount = props.fixedRowCount, rowCount = props.rowCount, scrollTop = props.scrollTop, showVerticalScrollbar = this.state.showVerticalScrollbar;
if (!fixedColumnCount) return null;
var additionalRowCount = showVerticalScrollbar ? 1 : 0;
return _react2.default.createElement(_Grid2.default, (0, _extends3.default)({}, props, {
cellRenderer: this._cellRendererBottomLeftGrid,
className: this.props.classNameBottomLeftGrid,
columnCount: fixedColumnCount,
deferredMeasurementCache: this._deferredMeasurementCacheBottomLeftGrid,
height: this._getBottomGridHeight(props),
onScroll: enableFixedColumnScroll ? this._onScrollTop : void 0,
ref: this._bottomLeftGridRef,
rowCount: Math.max(0, rowCount - fixedRowCount) + additionalRowCount,
rowHeight: this._rowHeightBottomGrid,
scrollTop: scrollTop,
style: this._bottomLeftGridStyle,
tabIndex: null,
width: this._getLeftGridWidth(props)
}));
}
}, {
key: "_renderBottomRightGrid",
value: function(props) {
var columnCount = props.columnCount, fixedColumnCount = props.fixedColumnCount, fixedRowCount = props.fixedRowCount, rowCount = props.rowCount, scrollToColumn = props.scrollToColumn, scrollToRow = props.scrollToRow;
return _react2.default.createElement(_Grid2.default, (0, _extends3.default)({}, props, {
cellRenderer: this._cellRendererBottomRightGrid,
className: this.props.classNameBottomRightGrid,
columnCount: Math.max(0, columnCount - fixedColumnCount),
columnWidth: this._columnWidthRightGrid,
deferredMeasurementCache: this._deferredMeasurementCacheBottomRightGrid,
height: this._getBottomGridHeight(props),
onScroll: this._onScroll,
onScrollbarPresenceChange: this._onScrollbarPresenceChange,
ref: this._bottomRightGridRef,
rowCount: Math.max(0, rowCount - fixedRowCount),
rowHeight: this._rowHeightBottomGrid,
scrollToColumn: scrollToColumn - fixedColumnCount,
scrollToRow: scrollToRow - fixedRowCount,
style: this._bottomRightGridStyle,
width: this._getRightGridWidth(props)
}));
}
}, {
key: "_renderTopLeftGrid",
value: function(props) {
var fixedColumnCount = props.fixedColumnCount, fixedRowCount = props.fixedRowCount;
return fixedColumnCount && fixedRowCount ? _react2.default.createElement(_Grid2.default, (0,
_extends3.default)({}, props, {
className: this.props.classNameTopLeftGrid,
columnCount: fixedColumnCount,
height: this._getTopGridHeight(props),
ref: this._topLeftGridRef,
rowCount: fixedRowCount,
style: this._topLeftGridStyle,
tabIndex: null,
width: this._getLeftGridWidth(props)
})) : null;
}
}, {
key: "_renderTopRightGrid",
value: function(props) {
var columnCount = props.columnCount, enableFixedRowScroll = props.enableFixedRowScroll, fixedColumnCount = props.fixedColumnCount, fixedRowCount = props.fixedRowCount, scrollLeft = props.scrollLeft, showHorizontalScrollbar = this.state.showHorizontalScrollbar;
if (!fixedRowCount) return null;
var additionalColumnCount = showHorizontalScrollbar ? 1 : 0;
return _react2.default.createElement(_Grid2.default, (0, _extends3.default)({}, props, {
cellRenderer: this._cellRendererTopRightGrid,
className: this.props.classNameTopRightGrid,
columnCount: Math.max(0, columnCount - fixedColumnCount) + additionalColumnCount,
columnWidth: this._columnWidthRightGrid,
deferredMeasurementCache: this._deferredMeasurementCacheTopRightGrid,
height: this._getTopGridHeight(props),
onScroll: enableFixedRowScroll ? this._onScrollLeft : void 0,
ref: this._topRightGridRef,
rowCount: fixedRowCount,
scrollLeft: scrollLeft,
style: this._topRightGridStyle,
tabIndex: null,
width: this._getRightGridWidth(props)
}));
}
}, {
key: "_rowHeightBottomGrid",
value: function(_ref8) {
var index = _ref8.index, _props10 = this.props, fixedRowCount = _props10.fixedRowCount, rowCount = _props10.rowCount, rowHeight = _props10.rowHeight, _state4 = this.state, scrollbarSize = _state4.scrollbarSize, showVerticalScrollbar = _state4.showVerticalScrollbar;
return showVerticalScrollbar && index === rowCount - fixedRowCount ? scrollbarSize : "function" == typeof rowHeight ? rowHeight({
index: index + fixedRowCount
}) : rowHeight;
}
}, {
key: "_topLeftGridRef",
value: function(ref) {
this._topLeftGrid = ref;
}
}, {
key: "_topRightGridRef",
value: function(ref) {
this._topRightGrid = ref;
}
} ]), MultiGrid;
}(_react.PureComponent);
MultiGrid.propTypes = {
classNameBottomLeftGrid: _propTypes2.default.string.isRequired,
classNameBottomRightGrid: _propTypes2.default.string.isRequired,
classNameTopLeftGrid: _propTypes2.default.string.isRequired,
classNameTopRightGrid: _propTypes2.default.string.isRequired,
enableFixedColumnScroll: _propTypes2.default.bool.isRequired,
enableFixedRowScroll: _propTypes2.default.bool.isRequired,
fixedColumnCount: _propTypes2.default.number.isRequired,
fixedRowCount: _propTypes2.default.number.isRequired,
style: _propTypes2.default.object.isRequired,
styleBottomLeftGrid: _propTypes2.default.object.isRequired,
styleBottomRightGrid: _propTypes2.default.object.isRequired,
styleTopLeftGrid: _propTypes2.default.object.isRequired,
styleTopRightGrid: _propTypes2.default.object.isRequired
}, MultiGrid.defaultProps = {
classNameBottomLeftGrid: "",
classNameBottomRightGrid: "",
classNameTopLeftGrid: "",
classNameTopRightGrid: "",
enableFixedColumnScroll: !1,
enableFixedRowScroll: !1,
fixedColumnCount: 0,
fixedRowCount: 0,
scrollToColumn: -1,
scrollToRow: -1,
style: {},
styleBottomLeftGrid: {},
styleBottomRightGrid: {},
styleTopLeftGrid: {},
styleTopRightGrid: {}
}, exports.default = MultiGrid;
}, /* 163 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), CellMeasurerCacheDecorator = (__webpack_require__(93),
function() {
function CellMeasurerCacheDecorator() {
var _this = this, params = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
(0, _classCallCheck3.default)(this, CellMeasurerCacheDecorator), this.columnWidth = function(_ref) {
var index = _ref.index;
_this._cellMeasurerCache.columnWidth({
index: index + _this._columnIndexOffset
});
}, this.rowHeight = function(_ref2) {
var index = _ref2.index;
_this._cellMeasurerCache.rowHeight({
index: index + _this._rowIndexOffset
});
};
var cellMeasurerCache = params.cellMeasurerCache, _params$columnIndexOf = params.columnIndexOffset, columnIndexOffset = void 0 === _params$columnIndexOf ? 0 : _params$columnIndexOf, _params$rowIndexOffse = params.rowIndexOffset, rowIndexOffset = void 0 === _params$rowIndexOffse ? 0 : _params$rowIndexOffse;
this._cellMeasurerCache = cellMeasurerCache, this._columnIndexOffset = columnIndexOffset,
this._rowIndexOffset = rowIndexOffset;
}
return (0, _createClass3.default)(CellMeasurerCacheDecorator, [ {
key: "clear",
value: function(rowIndex, columnIndex) {
this._cellMeasurerCache.clear(rowIndex + this._rowIndexOffset, columnIndex + this._columnIndexOffset);
}
}, {
key: "clearAll",
value: function() {
this._cellMeasurerCache.clearAll();
}
}, {
key: "hasFixedHeight",
value: function() {
return this._cellMeasurerCache.hasFixedHeight();
}
}, {
key: "hasFixedWidth",
value: function() {
return this._cellMeasurerCache.hasFixedWidth();
}
}, {
key: "getHeight",
value: function(rowIndex) {
var columnIndex = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0;
return this._cellMeasurerCache.getHeight(rowIndex + this._rowIndexOffset, columnIndex + this._columnIndexOffset);
}
}, {
key: "getWidth",
value: function(rowIndex) {
var columnIndex = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0;
return this._cellMeasurerCache.getWidth(rowIndex + this._rowIndexOffset, columnIndex + this._columnIndexOffset);
}
}, {
key: "has",
value: function(rowIndex) {
var columnIndex = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0;
return this._cellMeasurerCache.has(rowIndex + this._rowIndexOffset, columnIndex + this._columnIndexOffset);
}
}, {
key: "set",
value: function(rowIndex, columnIndex, width, height) {
this._cellMeasurerCache.set(rowIndex + this._rowIndexOffset, columnIndex + this._columnIndexOffset, width, height);
}
}, {
key: "defaultHeight",
get: function() {
return this._cellMeasurerCache.defaultHeight;
}
}, {
key: "defaultWidth",
get: function() {
return this._cellMeasurerCache.defaultWidth;
}
} ]), CellMeasurerCacheDecorator;
}());
exports.default = CellMeasurerCacheDecorator;
}, /* 164 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.ScrollSync = void 0;
var _ScrollSync = __webpack_require__(165), _ScrollSync2 = _interopRequireDefault(_ScrollSync);
exports.default = _ScrollSync2.default, exports.ScrollSync = _ScrollSync2.default;
}, /* 165 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _propTypes = __webpack_require__(106), _propTypes2 = _interopRequireDefault(_propTypes), _react = __webpack_require__(89), ScrollSync = function(_PureComponent) {
function ScrollSync(props, context) {
(0, _classCallCheck3.default)(this, ScrollSync);
var _this = (0, _possibleConstructorReturn3.default)(this, (ScrollSync.__proto__ || (0,
_getPrototypeOf2.default)(ScrollSync)).call(this, props, context));
return _this.state = {
clientHeight: 0,
clientWidth: 0,
scrollHeight: 0,
scrollLeft: 0,
scrollTop: 0,
scrollWidth: 0
}, _this._onScroll = _this._onScroll.bind(_this), _this;
}
return (0, _inherits3.default)(ScrollSync, _PureComponent), (0, _createClass3.default)(ScrollSync, [ {
key: "render",
value: function() {
var children = this.props.children, _state = this.state, clientHeight = _state.clientHeight, clientWidth = _state.clientWidth, scrollHeight = _state.scrollHeight, scrollLeft = _state.scrollLeft, scrollTop = _state.scrollTop, scrollWidth = _state.scrollWidth;
return children({
clientHeight: clientHeight,
clientWidth: clientWidth,
onScroll: this._onScroll,
scrollHeight: scrollHeight,
scrollLeft: scrollLeft,
scrollTop: scrollTop,
scrollWidth: scrollWidth
});
}
}, {
key: "_onScroll",
value: function(_ref) {
var clientHeight = _ref.clientHeight, clientWidth = _ref.clientWidth, scrollHeight = _ref.scrollHeight, scrollLeft = _ref.scrollLeft, scrollTop = _ref.scrollTop, scrollWidth = _ref.scrollWidth;
this.setState({
clientHeight: clientHeight,
clientWidth: clientWidth,
scrollHeight: scrollHeight,
scrollLeft: scrollLeft,
scrollTop: scrollTop,
scrollWidth: scrollWidth
});
}
} ]), ScrollSync;
}(_react.PureComponent);
ScrollSync.propTypes = {
children: _propTypes2.default.func.isRequired
}, exports.default = ScrollSync;
}, /* 166 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.Table = exports.SortIndicator = exports.SortDirection = exports.Column = exports.defaultRowRenderer = exports.defaultHeaderRenderer = exports.defaultHeaderRowRenderer = exports.defaultCellRenderer = exports.defaultCellDataGetter = void 0;
var _defaultCellDataGetter = __webpack_require__(167), _defaultCellDataGetter2 = _interopRequireDefault(_defaultCellDataGetter), _defaultCellRenderer = __webpack_require__(168), _defaultCellRenderer2 = _interopRequireDefault(_defaultCellRenderer), _defaultHeaderRowRenderer = __webpack_require__(169), _defaultHeaderRowRenderer2 = _interopRequireDefault(_defaultHeaderRowRenderer), _defaultHeaderRenderer = __webpack_require__(170), _defaultHeaderRenderer2 = _interopRequireDefault(_defaultHeaderRenderer), _defaultRowRenderer = __webpack_require__(173), _defaultRowRenderer2 = _interopRequireDefault(_defaultRowRenderer), _Column = __webpack_require__(174), _Column2 = _interopRequireDefault(_Column), _SortDirection = __webpack_require__(172), _SortDirection2 = _interopRequireDefault(_SortDirection), _SortIndicator = __webpack_require__(171), _SortIndicator2 = _interopRequireDefault(_SortIndicator), _Table = __webpack_require__(175), _Table2 = _interopRequireDefault(_Table);
exports.default = _Table2.default, exports.defaultCellDataGetter = _defaultCellDataGetter2.default,
exports.defaultCellRenderer = _defaultCellRenderer2.default, exports.defaultHeaderRowRenderer = _defaultHeaderRowRenderer2.default,
exports.defaultHeaderRenderer = _defaultHeaderRenderer2.default, exports.defaultRowRenderer = _defaultRowRenderer2.default,
exports.Column = _Column2.default, exports.SortDirection = _SortDirection2.default,
exports.SortIndicator = _SortIndicator2.default, exports.Table = _Table2.default;
}, /* 167 */
/***/
function(module, exports) {
"use strict";
function defaultCellDataGetter(_ref) {
var dataKey = _ref.dataKey, rowData = _ref.rowData;
return "function" == typeof rowData.get ? rowData.get(dataKey) : rowData[dataKey];
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.default = defaultCellDataGetter;
}, /* 168 */
/***/
function(module, exports) {
"use strict";
function defaultCellRenderer(_ref) {
var cellData = _ref.cellData;
return null == cellData ? "" : String(cellData);
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.default = defaultCellRenderer;
}, /* 169 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function defaultHeaderRowRenderer(_ref) {
var className = _ref.className, columns = _ref.columns, style = _ref.style;
return _react2.default.createElement("div", {
className: className,
role: "row",
style: style
}, columns);
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.default = defaultHeaderRowRenderer;
var _react = __webpack_require__(89), _react2 = _interopRequireDefault(_react);
}, /* 170 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function defaultHeaderRenderer(_ref) {
var dataKey = _ref.dataKey, label = _ref.label, sortBy = _ref.sortBy, sortDirection = _ref.sortDirection, showSortIndicator = sortBy === dataKey, children = [ _react2.default.createElement("span", {
className: "ReactVirtualized__Table__headerTruncatedText",
key: "label",
title: label
}, label) ];
return showSortIndicator && children.push(_react2.default.createElement(_SortIndicator2.default, {
key: "SortIndicator",
sortDirection: sortDirection
})), children;
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.default = defaultHeaderRenderer;
var _react = __webpack_require__(89), _react2 = _interopRequireDefault(_react), _SortIndicator = __webpack_require__(171), _SortIndicator2 = _interopRequireDefault(_SortIndicator);
}, /* 171 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function SortIndicator(_ref) {
var sortDirection = _ref.sortDirection, classNames = (0, _classnames2.default)("ReactVirtualized__Table__sortableHeaderIcon", {
"ReactVirtualized__Table__sortableHeaderIcon--ASC": sortDirection === _SortDirection2.default.ASC,
"ReactVirtualized__Table__sortableHeaderIcon--DESC": sortDirection === _SortDirection2.default.DESC
});
return _react2.default.createElement("svg", {
className: classNames,
width: 18,
height: 18,
viewBox: "0 0 24 24"
}, sortDirection === _SortDirection2.default.ASC ? _react2.default.createElement("path", {
d: "M7 14l5-5 5 5z"
}) : _react2.default.createElement("path", {
d: "M7 10l5 5 5-5z"
}), _react2.default.createElement("path", {
d: "M0 0h24v24H0z",
fill: "none"
}));
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.default = SortIndicator;
var _classnames = __webpack_require__(114), _classnames2 = _interopRequireDefault(_classnames), _propTypes = __webpack_require__(106), _propTypes2 = _interopRequireDefault(_propTypes), _react = __webpack_require__(89), _react2 = _interopRequireDefault(_react), _SortDirection = __webpack_require__(172), _SortDirection2 = _interopRequireDefault(_SortDirection);
SortIndicator.propTypes = {
sortDirection: _propTypes2.default.oneOf([ _SortDirection2.default.ASC, _SortDirection2.default.DESC ])
};
}, /* 172 */
/***/
function(module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: !0
});
var SortDirection = {
ASC: "ASC",
DESC: "DESC"
};
exports.default = SortDirection;
}, /* 173 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function defaultRowRenderer(_ref) {
var className = _ref.className, columns = _ref.columns, index = _ref.index, key = _ref.key, onRowClick = _ref.onRowClick, onRowDoubleClick = _ref.onRowDoubleClick, onRowMouseOut = _ref.onRowMouseOut, onRowMouseOver = _ref.onRowMouseOver, onRowRightClick = _ref.onRowRightClick, rowData = _ref.rowData, style = _ref.style, a11yProps = {};
return (onRowClick || onRowDoubleClick || onRowMouseOut || onRowMouseOver || onRowRightClick) && (a11yProps["aria-label"] = "row",
a11yProps.tabIndex = 0, onRowClick && (a11yProps.onClick = function(event) {
return onRowClick({
event: event,
index: index,
rowData: rowData
});
}), onRowDoubleClick && (a11yProps.onDoubleClick = function(event) {
return onRowDoubleClick({
event: event,
index: index,
rowData: rowData
});
}), onRowMouseOut && (a11yProps.onMouseOut = function(event) {
return onRowMouseOut({
event: event,
index: index,
rowData: rowData
});
}), onRowMouseOver && (a11yProps.onMouseOver = function(event) {
return onRowMouseOver({
event: event,
index: index,
rowData: rowData
});
}), onRowRightClick && (a11yProps.onContextMenu = function(event) {
return onRowRightClick({
event: event,
index: index,
rowData: rowData
});
})), _react2.default.createElement("div", (0, _extends3.default)({}, a11yProps, {
className: className,
key: key,
role: "row",
style: style
}), columns);
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _extends2 = __webpack_require__(100), _extends3 = _interopRequireDefault(_extends2);
exports.default = defaultRowRenderer;
var _react = __webpack_require__(89), _react2 = _interopRequireDefault(_react);
}, /* 174 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _propTypes = __webpack_require__(106), _propTypes2 = _interopRequireDefault(_propTypes), _react = __webpack_require__(89), _defaultHeaderRenderer = __webpack_require__(170), _defaultHeaderRenderer2 = _interopRequireDefault(_defaultHeaderRenderer), _defaultCellRenderer = __webpack_require__(168), _defaultCellRenderer2 = _interopRequireDefault(_defaultCellRenderer), _defaultCellDataGetter = __webpack_require__(167), _defaultCellDataGetter2 = _interopRequireDefault(_defaultCellDataGetter), _SortDirection = __webpack_require__(172), _SortDirection2 = _interopRequireDefault(_SortDirection), Column = function(_Component) {
function Column() {
return (0, _classCallCheck3.default)(this, Column), (0, _possibleConstructorReturn3.default)(this, (Column.__proto__ || (0,
_getPrototypeOf2.default)(Column)).apply(this, arguments));
}
return (0, _inherits3.default)(Column, _Component), Column;
}(_react.Component);
Column.propTypes = {
"aria-label": _propTypes2.default.string,
cellDataGetter: _propTypes2.default.func,
cellRenderer: _propTypes2.default.func,
className: _propTypes2.default.string,
columnData: _propTypes2.default.object,
dataKey: _propTypes2.default.any.isRequired,
defaultSortDirection: _propTypes2.default.oneOf([ _SortDirection2.default.ASC, _SortDirection2.default.DESC ]),
disableSort: _propTypes2.default.bool,
flexGrow: _propTypes2.default.number,
flexShrink: _propTypes2.default.number,
headerClassName: _propTypes2.default.string,
headerRenderer: _propTypes2.default.func.isRequired,
headerStyle: _propTypes2.default.object,
id: _propTypes2.default.string,
label: _propTypes2.default.node,
maxWidth: _propTypes2.default.number,
minWidth: _propTypes2.default.number,
style: _propTypes2.default.object,
width: _propTypes2.default.number.isRequired
}, Column.defaultProps = {
cellDataGetter: _defaultCellDataGetter2.default,
cellRenderer: _defaultCellRenderer2.default,
defaultSortDirection: _SortDirection2.default.ASC,
flexGrow: 0,
flexShrink: 1,
headerRenderer: _defaultHeaderRenderer2.default,
style: {}
}, exports.default = Column;
}, /* 175 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
});
var _extends2 = __webpack_require__(100), _extends3 = _interopRequireDefault(_extends2), _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _classnames = __webpack_require__(114), _classnames2 = _interopRequireDefault(_classnames), _Column = __webpack_require__(174), _Column2 = _interopRequireDefault(_Column), _propTypes = __webpack_require__(106), _propTypes2 = _interopRequireDefault(_propTypes), _react = __webpack_require__(89), _react2 = _interopRequireDefault(_react), _reactDom = __webpack_require__(96), _Grid2 = __webpack_require__(127), _Grid3 = _interopRequireDefault(_Grid2), _defaultRowRenderer = __webpack_require__(173), _defaultRowRenderer2 = _interopRequireDefault(_defaultRowRenderer), _defaultHeaderRowRenderer = __webpack_require__(169), _defaultHeaderRowRenderer2 = _interopRequireDefault(_defaultHeaderRowRenderer), _SortDirection = __webpack_require__(172), _SortDirection2 = _interopRequireDefault(_SortDirection), Table = function(_PureComponent) {
function Table(props) {
(0, _classCallCheck3.default)(this, Table);
var _this = (0, _possibleConstructorReturn3.default)(this, (Table.__proto__ || (0,
_getPrototypeOf2.default)(Table)).call(this, props));
return _this.state = {
scrollbarWidth: 0
}, _this._createColumn = _this._createColumn.bind(_this), _this._createRow = _this._createRow.bind(_this),
_this._onScroll = _this._onScroll.bind(_this), _this._onSectionRendered = _this._onSectionRendered.bind(_this),
_this._setRef = _this._setRef.bind(_this), _this;
}
return (0, _inherits3.default)(Table, _PureComponent), (0, _createClass3.default)(Table, [ {
key: "forceUpdateGrid",
value: function() {
this.Grid && this.Grid.forceUpdate();
}
}, {
key: "getOffsetForRow",
value: function(_ref) {
var alignment = _ref.alignment, index = _ref.index;
if (this.Grid) {
var _Grid$getOffsetForCel = this.Grid.getOffsetForCell({
alignment: alignment,
rowIndex: index
}), scrollTop = _Grid$getOffsetForCel.scrollTop;
return scrollTop;
}
return 0;
}
}, {
key: "invalidateCellSizeAfterRender",
value: function(_ref2) {
var columnIndex = _ref2.columnIndex, rowIndex = _ref2.rowIndex;
this.Grid && this.Grid.invalidateCellSizeAfterRender({
rowIndex: rowIndex,
columnIndex: columnIndex
});
}
}, {
key: "measureAllRows",
value: function() {
this.Grid && this.Grid.measureAllCells();
}
}, {
key: "recomputeGridSize",
value: function() {
var _ref3 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}, _ref3$columnIndex = _ref3.columnIndex, columnIndex = void 0 === _ref3$columnIndex ? 0 : _ref3$columnIndex, _ref3$rowIndex = _ref3.rowIndex, rowIndex = void 0 === _ref3$rowIndex ? 0 : _ref3$rowIndex;
this.Grid && this.Grid.recomputeGridSize({
rowIndex: rowIndex,
columnIndex: columnIndex
});
}
}, {
key: "recomputeRowHeights",
value: function() {
var index = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : 0;
this.Grid && this.Grid.recomputeGridSize({
rowIndex: index
});
}
}, {
key: "scrollToPosition",
value: function() {
var scrollTop = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : 0;
this.Grid && this.Grid.scrollToPosition({
scrollTop: scrollTop
});
}
}, {
key: "scrollToRow",
value: function() {
var index = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : 0;
this.Grid && this.Grid.scrollToCell({
columnIndex: 0,
rowIndex: index
});
}
}, {
key: "componentDidMount",
value: function() {
this._setScrollbarWidth();
}
}, {
key: "componentDidUpdate",
value: function() {
this._setScrollbarWidth();
}
}, {
key: "render",
value: function() {
var _this2 = this, _props = this.props, children = _props.children, className = _props.className, disableHeader = _props.disableHeader, gridClassName = _props.gridClassName, gridStyle = _props.gridStyle, headerHeight = _props.headerHeight, headerRowRenderer = _props.headerRowRenderer, height = _props.height, id = _props.id, noRowsRenderer = _props.noRowsRenderer, rowClassName = _props.rowClassName, rowStyle = _props.rowStyle, scrollToIndex = _props.scrollToIndex, style = _props.style, width = _props.width, scrollbarWidth = this.state.scrollbarWidth, availableRowsHeight = disableHeader ? height : height - headerHeight, rowClass = "function" == typeof rowClassName ? rowClassName({
index: -1
}) : rowClassName, rowStyleObject = "function" == typeof rowStyle ? rowStyle({
index: -1
}) : rowStyle;
return this._cachedColumnStyles = [], _react2.default.Children.toArray(children).forEach(function(column, index) {
var flexStyles = _this2._getFlexStyleForColumn(column, column.props.style);
_this2._cachedColumnStyles[index] = (0, _extends3.default)({}, flexStyles, {
overflow: "hidden"
});
}), _react2.default.createElement("div", {
className: (0, _classnames2.default)("ReactVirtualized__Table", className),
id: id,
role: "grid",
style: style
}, !disableHeader && headerRowRenderer({
className: (0, _classnames2.default)("ReactVirtualized__Table__headerRow", rowClass),
columns: this._getHeaderColumns(),
style: (0, _extends3.default)({}, rowStyleObject, {
height: headerHeight,
overflow: "hidden",
paddingRight: scrollbarWidth,
width: width
})
}), _react2.default.createElement(_Grid3.default, (0, _extends3.default)({}, this.props, {
autoContainerWidth: !0,
className: (0, _classnames2.default)("ReactVirtualized__Table__Grid", gridClassName),
cellRenderer: this._createRow,
columnWidth: width,
columnCount: 1,
height: availableRowsHeight,
id: void 0,
noContentRenderer: noRowsRenderer,
onScroll: this._onScroll,
onSectionRendered: this._onSectionRendered,
ref: this._setRef,
role: "rowgroup",
scrollbarWidth: scrollbarWidth,
scrollToRow: scrollToIndex,
style: (0, _extends3.default)({}, gridStyle, {
overflowX: "hidden"
})
})));
}
}, {
key: "_createColumn",
value: function(_ref4) {
var column = _ref4.column, columnIndex = _ref4.columnIndex, isScrolling = _ref4.isScrolling, parent = _ref4.parent, rowData = _ref4.rowData, rowIndex = _ref4.rowIndex, _column$props = column.props, cellDataGetter = _column$props.cellDataGetter, cellRenderer = _column$props.cellRenderer, className = _column$props.className, columnData = _column$props.columnData, dataKey = _column$props.dataKey, id = _column$props.id, cellData = cellDataGetter({
columnData: columnData,
dataKey: dataKey,
rowData: rowData
}), renderedCell = cellRenderer({
cellData: cellData,
columnData: columnData,
columnIndex: columnIndex,
dataKey: dataKey,
isScrolling: isScrolling,
parent: parent,
rowData: rowData,
rowIndex: rowIndex
}), style = this._cachedColumnStyles[columnIndex], title = "string" == typeof renderedCell ? renderedCell : null, a11yProps = {
role: "gridcell"
};
return id && (a11yProps["aria-describedby"] = id), _react2.default.createElement("div", (0,
_extends3.default)({}, a11yProps, {
key: "Row" + rowIndex + "-Col" + columnIndex,
className: (0, _classnames2.default)("ReactVirtualized__Table__rowColumn", className),
style: style,
title: title
}), renderedCell);
}
}, {
key: "_createHeader",
value: function(_ref5) {
var column = _ref5.column, index = _ref5.index, _props2 = this.props, headerClassName = _props2.headerClassName, headerStyle = _props2.headerStyle, onHeaderClick = _props2.onHeaderClick, sort = _props2.sort, sortBy = _props2.sortBy, sortDirection = _props2.sortDirection, _column$props2 = column.props, dataKey = _column$props2.dataKey, disableSort = _column$props2.disableSort, headerRenderer = _column$props2.headerRenderer, id = _column$props2.id, label = _column$props2.label, columnData = _column$props2.columnData, defaultSortDirection = _column$props2.defaultSortDirection, sortEnabled = !disableSort && sort, classNames = (0,
_classnames2.default)("ReactVirtualized__Table__headerColumn", headerClassName, column.props.headerClassName, {
ReactVirtualized__Table__sortableHeaderColumn: sortEnabled
}), style = this._getFlexStyleForColumn(column, (0, _extends3.default)({}, headerStyle, column.props.headerStyle)), renderedHeader = headerRenderer({
columnData: columnData,
dataKey: dataKey,
disableSort: disableSort,
label: label,
sortBy: sortBy,
sortDirection: sortDirection
}), a11yProps = {
role: "columnheader"
};
if (sortEnabled || onHeaderClick) {
var isFirstTimeSort = sortBy !== dataKey, newSortDirection = isFirstTimeSort ? defaultSortDirection : sortDirection === _SortDirection2.default.DESC ? _SortDirection2.default.ASC : _SortDirection2.default.DESC, onClick = function(event) {
sortEnabled && sort({
sortBy: dataKey,
sortDirection: newSortDirection
}), onHeaderClick && onHeaderClick({
columnData: columnData,
dataKey: dataKey,
event: event
});
}, onKeyDown = function(event) {
"Enter" !== event.key && " " !== event.key || onClick(event);
};
a11yProps["aria-label"] = column.props["aria-label"] || label || dataKey, a11yProps.tabIndex = 0,
a11yProps.onClick = onClick, a11yProps.onKeyDown = onKeyDown;
}
return sortBy === dataKey && (a11yProps["aria-sort"] = sortDirection === _SortDirection2.default.ASC ? "ascending" : "descending"),
id && (a11yProps.id = id), _react2.default.createElement("div", (0, _extends3.default)({}, a11yProps, {
key: "Header-Col" + index,
className: classNames,
style: style
}), renderedHeader);
}
}, {
key: "_createRow",
value: function(_ref6) {
var _this3 = this, index = _ref6.rowIndex, isScrolling = _ref6.isScrolling, key = _ref6.key, parent = _ref6.parent, style = _ref6.style, _props3 = this.props, children = _props3.children, onRowClick = _props3.onRowClick, onRowDoubleClick = _props3.onRowDoubleClick, onRowRightClick = _props3.onRowRightClick, onRowMouseOver = _props3.onRowMouseOver, onRowMouseOut = _props3.onRowMouseOut, rowClassName = _props3.rowClassName, rowGetter = _props3.rowGetter, rowRenderer = _props3.rowRenderer, rowStyle = _props3.rowStyle, scrollbarWidth = this.state.scrollbarWidth, rowClass = "function" == typeof rowClassName ? rowClassName({
index: index
}) : rowClassName, rowStyleObject = "function" == typeof rowStyle ? rowStyle({
index: index
}) : rowStyle, rowData = rowGetter({
index: index
}), columns = _react2.default.Children.toArray(children).map(function(column, columnIndex) {
return _this3._createColumn({
column: column,
columnIndex: columnIndex,
isScrolling: isScrolling,
parent: parent,
rowData: rowData,
rowIndex: index,
scrollbarWidth: scrollbarWidth
});
}), className = (0, _classnames2.default)("ReactVirtualized__Table__row", rowClass), flattenedStyle = (0,
_extends3.default)({}, style, rowStyleObject, {
height: this._getRowHeight(index),
overflow: "hidden",
paddingRight: scrollbarWidth
});
return rowRenderer({
className: className,
columns: columns,
index: index,
isScrolling: isScrolling,
key: key,
onRowClick: onRowClick,
onRowDoubleClick: onRowDoubleClick,
onRowRightClick: onRowRightClick,
onRowMouseOver: onRowMouseOver,
onRowMouseOut: onRowMouseOut,
rowData: rowData,
style: flattenedStyle
});
}
}, {
key: "_getFlexStyleForColumn",
value: function(column) {
var customStyle = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}, flexValue = column.props.flexGrow + " " + column.props.flexShrink + " " + column.props.width + "px", style = (0,
_extends3.default)({}, customStyle, {
flex: flexValue,
msFlex: flexValue,
WebkitFlex: flexValue
});
return column.props.maxWidth && (style.maxWidth = column.props.maxWidth), column.props.minWidth && (style.minWidth = column.props.minWidth),
style;
}
}, {
key: "_getHeaderColumns",
value: function() {
var _this4 = this, _props4 = this.props, children = _props4.children, disableHeader = _props4.disableHeader, items = disableHeader ? [] : _react2.default.Children.toArray(children);
return items.map(function(column, index) {
return _this4._createHeader({
column: column,
index: index
});
});
}
}, {
key: "_getRowHeight",
value: function(rowIndex) {
var rowHeight = this.props.rowHeight;
return "function" == typeof rowHeight ? rowHeight({
index: rowIndex
}) : rowHeight;
}
}, {
key: "_onScroll",
value: function(_ref7) {
var clientHeight = _ref7.clientHeight, scrollHeight = _ref7.scrollHeight, scrollTop = _ref7.scrollTop, onScroll = this.props.onScroll;
onScroll({
clientHeight: clientHeight,
scrollHeight: scrollHeight,
scrollTop: scrollTop
});
}
}, {
key: "_onSectionRendered",
value: function(_ref8) {
var rowOverscanStartIndex = _ref8.rowOverscanStartIndex, rowOverscanStopIndex = _ref8.rowOverscanStopIndex, rowStartIndex = _ref8.rowStartIndex, rowStopIndex = _ref8.rowStopIndex, onRowsRendered = this.props.onRowsRendered;
onRowsRendered({
overscanStartIndex: rowOverscanStartIndex,
overscanStopIndex: rowOverscanStopIndex,
startIndex: rowStartIndex,
stopIndex: rowStopIndex
});
}
}, {
key: "_setRef",
value: function(ref) {
this.Grid = ref;
}
}, {
key: "_setScrollbarWidth",
value: function() {
if (this.Grid) {
var _Grid = (0, _reactDom.findDOMNode)(this.Grid), clientWidth = _Grid.clientWidth || 0, offsetWidth = _Grid.offsetWidth || 0, scrollbarWidth = offsetWidth - clientWidth;
this.setState({
scrollbarWidth: scrollbarWidth
});
}
}
} ]), Table;
}(_react.PureComponent);
Table.propTypes = {
"aria-label": _propTypes2.default.string,
autoHeight: _propTypes2.default.bool,
children: function children(props) {
for (var children = _react2.default.Children.toArray(props.children), i = 0; i < children.length; i++) {
var childType = children[i].type;
if (childType !== _Column2.default && !(childType.prototype instanceof _Column2.default)) return new Error("Table only accepts children of type Column");
}
},
className: _propTypes2.default.string,
disableHeader: _propTypes2.default.bool,
estimatedRowSize: _propTypes2.default.number.isRequired,
gridClassName: _propTypes2.default.string,
gridStyle: _propTypes2.default.object,
headerClassName: _propTypes2.default.string,
headerHeight: _propTypes2.default.number.isRequired,
headerRowRenderer: _propTypes2.default.func,
headerStyle: _propTypes2.default.object,
height: _propTypes2.default.number.isRequired,
id: _propTypes2.default.string,
noRowsRenderer: _propTypes2.default.func,
onHeaderClick: _propTypes2.default.func,
onRowClick: _propTypes2.default.func,
onRowDoubleClick: _propTypes2.default.func,
onRowMouseOut: _propTypes2.default.func,
onRowMouseOver: _propTypes2.default.func,
onRowRightClick: _propTypes2.default.func,
onRowsRendered: _propTypes2.default.func,
onScroll: _propTypes2.default.func.isRequired,
overscanIndicesGetter: _propTypes2.default.func.isRequired,
overscanRowCount: _propTypes2.default.number.isRequired,
rowClassName: _propTypes2.default.oneOfType([ _propTypes2.default.string, _propTypes2.default.func ]),
rowGetter: _propTypes2.default.func.isRequired,
rowHeight: _propTypes2.default.oneOfType([ _propTypes2.default.number, _propTypes2.default.func ]).isRequired,
rowCount: _propTypes2.default.number.isRequired,
rowRenderer: _propTypes2.default.func,
rowStyle: _propTypes2.default.oneOfType([ _propTypes2.default.object, _propTypes2.default.func ]).isRequired,
scrollToAlignment: _propTypes2.default.oneOf([ "auto", "end", "start", "center" ]).isRequired,
scrollToIndex: _propTypes2.default.number.isRequired,
scrollTop: _propTypes2.default.number,
sort: _propTypes2.default.func,
sortBy: _propTypes2.default.string,
sortDirection: _propTypes2.default.oneOf([ _SortDirection2.default.ASC, _SortDirection2.default.DESC ]),
style: _propTypes2.default.object,
tabIndex: _propTypes2.default.number,
width: _propTypes2.default.number.isRequired
}, Table.defaultProps = {
disableHeader: !1,
estimatedRowSize: 30,
headerHeight: 0,
headerStyle: {},
noRowsRenderer: function() {
return null;
},
onRowsRendered: function() {
return null;
},
onScroll: function() {
return null;
},
overscanIndicesGetter: _Grid2.accessibilityOverscanIndicesGetter,
overscanRowCount: 10,
rowRenderer: _defaultRowRenderer2.default,
headerRowRenderer: _defaultHeaderRowRenderer2.default,
rowStyle: {},
scrollToAlignment: "auto",
scrollToIndex: -1,
style: {}
}, exports.default = Table;
}, /* 176 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.IS_SCROLLING_TIMEOUT = exports.WindowScroller = void 0;
var _WindowScroller = __webpack_require__(177), _WindowScroller2 = _interopRequireDefault(_WindowScroller);
exports.default = _WindowScroller2.default, exports.WindowScroller = _WindowScroller2.default,
exports.IS_SCROLLING_TIMEOUT = _WindowScroller.IS_SCROLLING_TIMEOUT;
}, /* 177 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.IS_SCROLLING_TIMEOUT = void 0;
var _getPrototypeOf = __webpack_require__(3), _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf), _classCallCheck2 = __webpack_require__(29), _classCallCheck3 = _interopRequireDefault(_classCallCheck2), _createClass2 = __webpack_require__(30), _createClass3 = _interopRequireDefault(_createClass2), _possibleConstructorReturn2 = __webpack_require__(34), _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2), _inherits2 = __webpack_require__(81), _inherits3 = _interopRequireDefault(_inherits2), _propTypes = __webpack_require__(106), _propTypes2 = _interopRequireDefault(_propTypes), _react = __webpack_require__(89), _reactDom = __webpack_require__(96), _reactDom2 = _interopRequireDefault(_reactDom), _onScroll = __webpack_require__(178), _dimensions = __webpack_require__(179), IS_SCROLLING_TIMEOUT = exports.IS_SCROLLING_TIMEOUT = 150, WindowScroller = function(_PureComponent) {
function WindowScroller(props) {
(0, _classCallCheck3.default)(this, WindowScroller);
var _this = (0, _possibleConstructorReturn3.default)(this, (WindowScroller.__proto__ || (0,
_getPrototypeOf2.default)(WindowScroller)).call(this, props)), _getDimensions = (0,
_dimensions.getDimensions)(props.scrollElement, props), width = _getDimensions.width, height = _getDimensions.height;
return _this.state = {
height: height,
width: width,
isScrolling: !1,
scrollLeft: 0,
scrollTop: 0
}, _this._onResize = _this._onResize.bind(_this), _this._onChildScroll = _this._onChildScroll.bind(_this),
_this.__handleWindowScrollEvent = _this.__handleWindowScrollEvent.bind(_this), _this.__resetIsScrolling = _this.__resetIsScrolling.bind(_this),
_this;
}
return (0, _inherits3.default)(WindowScroller, _PureComponent), (0, _createClass3.default)(WindowScroller, [ {
key: "updatePosition",
value: function(scrollElement) {
var props = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : this.props, onResize = this.props.onResize, _state = this.state, height = _state.height, width = _state.width;
scrollElement = scrollElement || this.props.scrollElement;
var offset = (0, _dimensions.getPositionOffset)(_reactDom2.default.findDOMNode(this), scrollElement);
this._positionFromTop = offset.top, this._positionFromLeft = offset.left;
var dimensions = (0, _dimensions.getDimensions)(scrollElement, props);
height === dimensions.height && width === dimensions.width || (this.setState({
height: dimensions.height,
width: dimensions.width
}), onResize({
height: dimensions.height,
width: dimensions.width
}));
}
}, {
key: "componentDidMount",
value: function() {
var scrollElement = this.props.scrollElement;
this.updatePosition(scrollElement), (0, _onScroll.registerScrollListener)(this, scrollElement),
window.addEventListener("resize", this._onResize, !1), this._isMounted = !0;
}
}, {
key: "componentWillReceiveProps",
value: function(nextProps) {
var scrollElement = this.props.scrollElement, nextScrollElement = nextProps.scrollElement;
scrollElement !== nextScrollElement && (this.updatePosition(nextScrollElement, nextProps),
(0, _onScroll.unregisterScrollListener)(this, scrollElement), (0, _onScroll.registerScrollListener)(this, nextScrollElement));
}
}, {
key: "componentWillUnmount",
value: function() {
(0, _onScroll.unregisterScrollListener)(this, this.props.scrollElement), window.removeEventListener("resize", this._onResize, !1),
this._isMounted = !1;
}
}, {
key: "render",
value: function() {
var children = this.props.children, _state2 = this.state, isScrolling = _state2.isScrolling, scrollTop = _state2.scrollTop, scrollLeft = _state2.scrollLeft, height = _state2.height, width = _state2.width;
return children({
onChildScroll: this._onChildScroll,
height: height,
isScrolling: isScrolling,
scrollLeft: scrollLeft,
scrollTop: scrollTop,
width: width
});
}
}, {
key: "_onChildScroll",
value: function(_ref) {
var scrollTop = _ref.scrollTop;
if (this.state.scrollTop !== scrollTop) {
var scrollElement = this.scrollElement;
"function" == typeof scrollElement.scrollTo ? scrollElement.scrollTo(0, scrollTop + this._positionFromTop) : scrollElement.scrollTop = scrollTop + this._positionFromTop;
}
}
}, {
key: "_onResize",
value: function() {
this.updatePosition();
}
}, {
key: "__handleWindowScrollEvent",
value: function() {
if (this._isMounted) {
var onScroll = this.props.onScroll, scrollElement = this.props.scrollElement, scrollOffset = (0,
_dimensions.getScrollOffset)(scrollElement), scrollLeft = Math.max(0, scrollOffset.left - this._positionFromLeft), scrollTop = Math.max(0, scrollOffset.top - this._positionFromTop);
this.setState({
isScrolling: !0,
scrollLeft: scrollLeft,
scrollTop: scrollTop
}), onScroll({
scrollLeft: scrollLeft,
scrollTop: scrollTop
});
}
}
}, {
key: "__resetIsScrolling",
value: function() {
this.setState({
isScrolling: !1
});
}
}, {
key: "scrollElement",
get: function() {
return this.props.scrollElement;
}
} ]), WindowScroller;
}(_react.PureComponent);
WindowScroller.propTypes = {
children: _propTypes2.default.func.isRequired,
onResize: _propTypes2.default.func.isRequired,
onScroll: _propTypes2.default.func.isRequired,
scrollElement: _propTypes2.default.any,
scrollingResetTimeInterval: _propTypes2.default.number.isRequired,
serverHeight: _propTypes2.default.number.isRequired,
serverWidth: _propTypes2.default.number.isRequired
}, WindowScroller.defaultProps = {
onResize: function() {},
onScroll: function() {},
scrollElement: window,
scrollingResetTimeInterval: IS_SCROLLING_TIMEOUT,
serverHeight: 0,
serverWidth: 0
}, exports.default = WindowScroller;
}, /* 178 */
/***/
function(module, exports, __webpack_require__) {
"use strict";
function enablePointerEventsIfDisabled() {
disablePointerEventsTimeoutId && (disablePointerEventsTimeoutId = null, document.body.style.pointerEvents = originalBodyPointerEvents,
originalBodyPointerEvents = null);
}
function enablePointerEventsAfterDelayCallback() {
enablePointerEventsIfDisabled(), mountedInstances.forEach(function(instance) {
return instance.__resetIsScrolling();
});
}
function enablePointerEventsAfterDelay() {
disablePointerEventsTimeoutId && (0, _requestAnimationTimeout.cancelAnimationTimeout)(disablePointerEventsTimeoutId);
var maximumTimeout = 0;
mountedInstances.forEach(function(instance) {
maximumTimeout = Math.max(maximumTimeout, instance.props.scrollingResetTimeInterval);
}), disablePointerEventsTimeoutId = (0, _requestAnimationTimeout.requestAnimationTimeout)(enablePointerEventsAfterDelayCallback, maximumTimeout);
}
function onScrollWindow(event) {
event.currentTarget === window && null == originalBodyPointerEvents && (originalBodyPointerEvents = document.body.style.pointerEvents,
document.body.style.pointerEvents = "none"), enablePointerEventsAfterDelay(), mountedInstances.forEach(function(instance) {
instance.scrollElement === event.currentTarget && instance.__handleWindowScrollEvent(event);
});
}
function registerScrollListener(component, element) {
mountedInstances.some(function(instance) {
return instance.scrollElement === element;
}) || element.addEventListener("scroll", onScrollWindow), mountedInstances.push(component);
}
function unregisterScrollListener(component, element) {
mountedInstances = mountedInstances.filter(function(instance) {
return instance !== component;
}), mountedInstances.length || (element.removeEventListener("scroll", onScrollWindow),
disablePointerEventsTimeoutId && ((0, _requestAnimationTimeout.cancelAnimationTimeout)(disablePointerEventsTimeoutId),
enablePointerEventsIfDisabled()));
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.registerScrollListener = registerScrollListener, exports.unregisterScrollListener = unregisterScrollListener;
var _requestAnimationTimeout = __webpack_require__(136), mountedInstances = [], originalBodyPointerEvents = null, disablePointerEventsTimeoutId = null;
}, /* 179 */
/***/
function(module, exports) {
"use strict";
function getDimensions(scrollElement, props) {
return scrollElement ? scrollElement === window ? {
height: "number" == typeof window.innerHeight ? window.innerHeight : 0,
width: "number" == typeof window.innerWidth ? window.innerWidth : 0
} : scrollElement.getBoundingClientRect() : {
height: props.serverHeight || 0,
width: props.serverWidth || 0
};
}
function getPositionOffset(element, container) {
var scrollOffset = container === window ? {
top: 0,
left: 0
} : getScrollOffset(container), containerElement = container === window ? document.documentElement : container, elementRect = element.getBoundingClientRect(), containerRect = containerElement.getBoundingClientRect();
return {
top: elementRect.top + scrollOffset.top - containerRect.top,
left: elementRect.left + scrollOffset.left - containerRect.left
};
}
function getScrollOffset(element) {
return element === window ? {
top: "scrollY" in window ? window.scrollY : document.documentElement.scrollTop,
left: "scrollX" in window ? window.scrollX : document.documentElement.scrollLeft
} : {
top: element.scrollTop,
left: element.scrollLeft
};
}
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.getDimensions = getDimensions, exports.getPositionOffset = getPositionOffset,
exports.getScrollOffset = getScrollOffset;
} ]);
});
//# sourceMappingURL=react-virtualized.js.map
|
react/src/components/TextField.js
|
koscim/beer-art-reviews
|
import React from 'react';
const TextField = props => {
return (
<label className="white-text">{props.label}
<input
name={props.name}
onChange={props.handlerFunction}
type="text"
value={props.content}
className="shorter-field"
/>
</label>
);
}
export default TextField;
|
include/javascript/yui/build/container/container.js
|
josesam/latinos
|
/*
Copyright (c) 2011, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.com/yui/license.html
version: 2.9.0
*/
(function () {
/**
* Config is a utility used within an Object to allow the implementer to
* maintain a list of local configuration properties and listen for changes
* to those properties dynamically using CustomEvent. The initial values are
* also maintained so that the configuration can be reset at any given point
* to its initial state.
* @namespace YAHOO.util
* @class Config
* @constructor
* @param {Object} owner The owner Object to which this Config Object belongs
*/
YAHOO.util.Config = function (owner) {
if (owner) {
this.init(owner);
}
};
var Lang = YAHOO.lang,
CustomEvent = YAHOO.util.CustomEvent,
Config = YAHOO.util.Config;
/**
* Constant representing the CustomEvent type for the config changed event.
* @property YAHOO.util.Config.CONFIG_CHANGED_EVENT
* @private
* @static
* @final
*/
Config.CONFIG_CHANGED_EVENT = "configChanged";
/**
* Constant representing the boolean type string
* @property YAHOO.util.Config.BOOLEAN_TYPE
* @private
* @static
* @final
*/
Config.BOOLEAN_TYPE = "boolean";
Config.prototype = {
/**
* Object reference to the owner of this Config Object
* @property owner
* @type Object
*/
owner: null,
/**
* Boolean flag that specifies whether a queue is currently
* being executed
* @property queueInProgress
* @type Boolean
*/
queueInProgress: false,
/**
* Maintains the local collection of configuration property objects and
* their specified values
* @property config
* @private
* @type Object
*/
config: null,
/**
* Maintains the local collection of configuration property objects as
* they were initially applied.
* This object is used when resetting a property.
* @property initialConfig
* @private
* @type Object
*/
initialConfig: null,
/**
* Maintains the local, normalized CustomEvent queue
* @property eventQueue
* @private
* @type Object
*/
eventQueue: null,
/**
* Custom Event, notifying subscribers when Config properties are set
* (setProperty is called without the silent flag
* @event configChangedEvent
*/
configChangedEvent: null,
/**
* Initializes the configuration Object and all of its local members.
* @method init
* @param {Object} owner The owner Object to which this Config
* Object belongs
*/
init: function (owner) {
this.owner = owner;
this.configChangedEvent =
this.createEvent(Config.CONFIG_CHANGED_EVENT);
this.configChangedEvent.signature = CustomEvent.LIST;
this.queueInProgress = false;
this.config = {};
this.initialConfig = {};
this.eventQueue = [];
},
/**
* Validates that the value passed in is a Boolean.
* @method checkBoolean
* @param {Object} val The value to validate
* @return {Boolean} true, if the value is valid
*/
checkBoolean: function (val) {
return (typeof val == Config.BOOLEAN_TYPE);
},
/**
* Validates that the value passed in is a number.
* @method checkNumber
* @param {Object} val The value to validate
* @return {Boolean} true, if the value is valid
*/
checkNumber: function (val) {
return (!isNaN(val));
},
/**
* Fires a configuration property event using the specified value.
* @method fireEvent
* @private
* @param {String} key The configuration property's name
* @param {value} Object The value of the correct type for the property
*/
fireEvent: function ( key, value ) {
var property = this.config[key];
if (property && property.event) {
property.event.fire(value);
}
},
/**
* Adds a property to the Config Object's private config hash.
* @method addProperty
* @param {String} key The configuration property's name
* @param {Object} propertyObject The Object containing all of this
* property's arguments
*/
addProperty: function ( key, propertyObject ) {
key = key.toLowerCase();
this.config[key] = propertyObject;
propertyObject.event = this.createEvent(key, { scope: this.owner });
propertyObject.event.signature = CustomEvent.LIST;
propertyObject.key = key;
if (propertyObject.handler) {
propertyObject.event.subscribe(propertyObject.handler,
this.owner);
}
this.setProperty(key, propertyObject.value, true);
if (! propertyObject.suppressEvent) {
this.queueProperty(key, propertyObject.value);
}
},
/**
* Returns a key-value configuration map of the values currently set in
* the Config Object.
* @method getConfig
* @return {Object} The current config, represented in a key-value map
*/
getConfig: function () {
var cfg = {},
currCfg = this.config,
prop,
property;
for (prop in currCfg) {
if (Lang.hasOwnProperty(currCfg, prop)) {
property = currCfg[prop];
if (property && property.event) {
cfg[prop] = property.value;
}
}
}
return cfg;
},
/**
* Returns the value of specified property.
* @method getProperty
* @param {String} key The name of the property
* @return {Object} The value of the specified property
*/
getProperty: function (key) {
var property = this.config[key.toLowerCase()];
if (property && property.event) {
return property.value;
} else {
return undefined;
}
},
/**
* Resets the specified property's value to its initial value.
* @method resetProperty
* @param {String} key The name of the property
* @return {Boolean} True is the property was reset, false if not
*/
resetProperty: function (key) {
key = key.toLowerCase();
var property = this.config[key];
if (property && property.event) {
if (key in this.initialConfig) {
this.setProperty(key, this.initialConfig[key]);
return true;
}
} else {
return false;
}
},
/**
* Sets the value of a property. If the silent property is passed as
* true, the property's event will not be fired.
* @method setProperty
* @param {String} key The name of the property
* @param {String} value The value to set the property to
* @param {Boolean} silent Whether the value should be set silently,
* without firing the property event.
* @return {Boolean} True, if the set was successful, false if it failed.
*/
setProperty: function (key, value, silent) {
var property;
key = key.toLowerCase();
if (this.queueInProgress && ! silent) {
// Currently running through a queue...
this.queueProperty(key,value);
return true;
} else {
property = this.config[key];
if (property && property.event) {
if (property.validator && !property.validator(value)) {
return false;
} else {
property.value = value;
if (! silent) {
this.fireEvent(key, value);
this.configChangedEvent.fire([key, value]);
}
return true;
}
} else {
return false;
}
}
},
/**
* Sets the value of a property and queues its event to execute. If the
* event is already scheduled to execute, it is
* moved from its current position to the end of the queue.
* @method queueProperty
* @param {String} key The name of the property
* @param {String} value The value to set the property to
* @return {Boolean} true, if the set was successful, false if
* it failed.
*/
queueProperty: function (key, value) {
key = key.toLowerCase();
var property = this.config[key],
foundDuplicate = false,
iLen,
queueItem,
queueItemKey,
queueItemValue,
sLen,
supercedesCheck,
qLen,
queueItemCheck,
queueItemCheckKey,
queueItemCheckValue,
i,
s,
q;
if (property && property.event) {
if (!Lang.isUndefined(value) && property.validator &&
!property.validator(value)) { // validator
return false;
} else {
if (!Lang.isUndefined(value)) {
property.value = value;
} else {
value = property.value;
}
foundDuplicate = false;
iLen = this.eventQueue.length;
for (i = 0; i < iLen; i++) {
queueItem = this.eventQueue[i];
if (queueItem) {
queueItemKey = queueItem[0];
queueItemValue = queueItem[1];
if (queueItemKey == key) {
/*
found a dupe... push to end of queue, null
current item, and break
*/
this.eventQueue[i] = null;
this.eventQueue.push(
[key, (!Lang.isUndefined(value) ?
value : queueItemValue)]);
foundDuplicate = true;
break;
}
}
}
// this is a refire, or a new property in the queue
if (! foundDuplicate && !Lang.isUndefined(value)) {
this.eventQueue.push([key, value]);
}
}
if (property.supercedes) {
sLen = property.supercedes.length;
for (s = 0; s < sLen; s++) {
supercedesCheck = property.supercedes[s];
qLen = this.eventQueue.length;
for (q = 0; q < qLen; q++) {
queueItemCheck = this.eventQueue[q];
if (queueItemCheck) {
queueItemCheckKey = queueItemCheck[0];
queueItemCheckValue = queueItemCheck[1];
if (queueItemCheckKey ==
supercedesCheck.toLowerCase() ) {
this.eventQueue.push([queueItemCheckKey,
queueItemCheckValue]);
this.eventQueue[q] = null;
break;
}
}
}
}
}
return true;
} else {
return false;
}
},
/**
* Fires the event for a property using the property's current value.
* @method refireEvent
* @param {String} key The name of the property
*/
refireEvent: function (key) {
key = key.toLowerCase();
var property = this.config[key];
if (property && property.event &&
!Lang.isUndefined(property.value)) {
if (this.queueInProgress) {
this.queueProperty(key);
} else {
this.fireEvent(key, property.value);
}
}
},
/**
* Applies a key-value Object literal to the configuration, replacing
* any existing values, and queueing the property events.
* Although the values will be set, fireQueue() must be called for their
* associated events to execute.
* @method applyConfig
* @param {Object} userConfig The configuration Object literal
* @param {Boolean} init When set to true, the initialConfig will
* be set to the userConfig passed in, so that calling a reset will
* reset the properties to the passed values.
*/
applyConfig: function (userConfig, init) {
var sKey,
oConfig;
if (init) {
oConfig = {};
for (sKey in userConfig) {
if (Lang.hasOwnProperty(userConfig, sKey)) {
oConfig[sKey.toLowerCase()] = userConfig[sKey];
}
}
this.initialConfig = oConfig;
}
for (sKey in userConfig) {
if (Lang.hasOwnProperty(userConfig, sKey)) {
this.queueProperty(sKey, userConfig[sKey]);
}
}
},
/**
* Refires the events for all configuration properties using their
* current values.
* @method refresh
*/
refresh: function () {
var prop;
for (prop in this.config) {
if (Lang.hasOwnProperty(this.config, prop)) {
this.refireEvent(prop);
}
}
},
/**
* Fires the normalized list of queued property change events
* @method fireQueue
*/
fireQueue: function () {
var i,
queueItem,
key,
value,
property;
this.queueInProgress = true;
for (i = 0;i < this.eventQueue.length; i++) {
queueItem = this.eventQueue[i];
if (queueItem) {
key = queueItem[0];
value = queueItem[1];
property = this.config[key];
property.value = value;
// Clear out queue entry, to avoid it being
// re-added to the queue by any queueProperty/supercedes
// calls which are invoked during fireEvent
this.eventQueue[i] = null;
this.fireEvent(key,value);
}
}
this.queueInProgress = false;
this.eventQueue = [];
},
/**
* Subscribes an external handler to the change event for any
* given property.
* @method subscribeToConfigEvent
* @param {String} key The property name
* @param {Function} handler The handler function to use subscribe to
* the property's event
* @param {Object} obj The Object to use for scoping the event handler
* (see CustomEvent documentation)
* @param {Boolean} overrideContext Optional. If true, will override
* "this" within the handler to map to the scope Object passed into the
* method.
* @return {Boolean} True, if the subscription was successful,
* otherwise false.
*/
subscribeToConfigEvent: function (key, handler, obj, overrideContext) {
var property = this.config[key.toLowerCase()];
if (property && property.event) {
if (!Config.alreadySubscribed(property.event, handler, obj)) {
property.event.subscribe(handler, obj, overrideContext);
}
return true;
} else {
return false;
}
},
/**
* Unsubscribes an external handler from the change event for any
* given property.
* @method unsubscribeFromConfigEvent
* @param {String} key The property name
* @param {Function} handler The handler function to use subscribe to
* the property's event
* @param {Object} obj The Object to use for scoping the event
* handler (see CustomEvent documentation)
* @return {Boolean} True, if the unsubscription was successful,
* otherwise false.
*/
unsubscribeFromConfigEvent: function (key, handler, obj) {
var property = this.config[key.toLowerCase()];
if (property && property.event) {
return property.event.unsubscribe(handler, obj);
} else {
return false;
}
},
/**
* Returns a string representation of the Config object
* @method toString
* @return {String} The Config object in string format.
*/
toString: function () {
var output = "Config";
if (this.owner) {
output += " [" + this.owner.toString() + "]";
}
return output;
},
/**
* Returns a string representation of the Config object's current
* CustomEvent queue
* @method outputEventQueue
* @return {String} The string list of CustomEvents currently queued
* for execution
*/
outputEventQueue: function () {
var output = "",
queueItem,
q,
nQueue = this.eventQueue.length;
for (q = 0; q < nQueue; q++) {
queueItem = this.eventQueue[q];
if (queueItem) {
output += queueItem[0] + "=" + queueItem[1] + ", ";
}
}
return output;
},
/**
* Sets all properties to null, unsubscribes all listeners from each
* property's change event and all listeners from the configChangedEvent.
* @method destroy
*/
destroy: function () {
var oConfig = this.config,
sProperty,
oProperty;
for (sProperty in oConfig) {
if (Lang.hasOwnProperty(oConfig, sProperty)) {
oProperty = oConfig[sProperty];
oProperty.event.unsubscribeAll();
oProperty.event = null;
}
}
this.configChangedEvent.unsubscribeAll();
this.configChangedEvent = null;
this.owner = null;
this.config = null;
this.initialConfig = null;
this.eventQueue = null;
}
};
/**
* Checks to determine if a particular function/Object pair are already
* subscribed to the specified CustomEvent
* @method YAHOO.util.Config.alreadySubscribed
* @static
* @param {YAHOO.util.CustomEvent} evt The CustomEvent for which to check
* the subscriptions
* @param {Function} fn The function to look for in the subscribers list
* @param {Object} obj The execution scope Object for the subscription
* @return {Boolean} true, if the function/Object pair is already subscribed
* to the CustomEvent passed in
*/
Config.alreadySubscribed = function (evt, fn, obj) {
var nSubscribers = evt.subscribers.length,
subsc,
i;
if (nSubscribers > 0) {
i = nSubscribers - 1;
do {
subsc = evt.subscribers[i];
if (subsc && subsc.obj == obj && subsc.fn == fn) {
return true;
}
}
while (i--);
}
return false;
};
YAHOO.lang.augmentProto(Config, YAHOO.util.EventProvider);
}());
(function () {
/**
* The Container family of components is designed to enable developers to
* create different kinds of content-containing modules on the web. Module
* and Overlay are the most basic containers, and they can be used directly
* or extended to build custom containers. Also part of the Container family
* are four UI controls that extend Module and Overlay: Tooltip, Panel,
* Dialog, and SimpleDialog.
* @module container
* @title Container
* @requires yahoo, dom, event
* @optional dragdrop, animation, button
*/
/**
* Module is a JavaScript representation of the Standard Module Format.
* Standard Module Format is a simple standard for markup containers where
* child nodes representing the header, body, and footer of the content are
* denoted using the CSS classes "hd", "bd", and "ft" respectively.
* Module is the base class for all other classes in the YUI
* Container package.
* @namespace YAHOO.widget
* @class Module
* @constructor
* @param {String} el The element ID representing the Module <em>OR</em>
* @param {HTMLElement} el The element representing the Module
* @param {Object} userConfig The configuration Object literal containing
* the configuration that should be set for this module. See configuration
* documentation for more details.
*/
YAHOO.widget.Module = function (el, userConfig) {
if (el) {
this.init(el, userConfig);
} else {
}
};
var Dom = YAHOO.util.Dom,
Config = YAHOO.util.Config,
Event = YAHOO.util.Event,
CustomEvent = YAHOO.util.CustomEvent,
Module = YAHOO.widget.Module,
UA = YAHOO.env.ua,
m_oModuleTemplate,
m_oHeaderTemplate,
m_oBodyTemplate,
m_oFooterTemplate,
/**
* Constant representing the name of the Module's events
* @property EVENT_TYPES
* @private
* @final
* @type Object
*/
EVENT_TYPES = {
"BEFORE_INIT": "beforeInit",
"INIT": "init",
"APPEND": "append",
"BEFORE_RENDER": "beforeRender",
"RENDER": "render",
"CHANGE_HEADER": "changeHeader",
"CHANGE_BODY": "changeBody",
"CHANGE_FOOTER": "changeFooter",
"CHANGE_CONTENT": "changeContent",
"DESTROY": "destroy",
"BEFORE_SHOW": "beforeShow",
"SHOW": "show",
"BEFORE_HIDE": "beforeHide",
"HIDE": "hide"
},
/**
* Constant representing the Module's configuration properties
* @property DEFAULT_CONFIG
* @private
* @final
* @type Object
*/
DEFAULT_CONFIG = {
"VISIBLE": {
key: "visible",
value: true,
validator: YAHOO.lang.isBoolean
},
"EFFECT": {
key: "effect",
suppressEvent: true,
supercedes: ["visible"]
},
"MONITOR_RESIZE": {
key: "monitorresize",
value: true
},
"APPEND_TO_DOCUMENT_BODY": {
key: "appendtodocumentbody",
value: false
}
};
/**
* Constant representing the prefix path to use for non-secure images
* @property YAHOO.widget.Module.IMG_ROOT
* @static
* @final
* @type String
*/
Module.IMG_ROOT = null;
/**
* Constant representing the prefix path to use for securely served images
* @property YAHOO.widget.Module.IMG_ROOT_SSL
* @static
* @final
* @type String
*/
Module.IMG_ROOT_SSL = null;
/**
* Constant for the default CSS class name that represents a Module
* @property YAHOO.widget.Module.CSS_MODULE
* @static
* @final
* @type String
*/
Module.CSS_MODULE = "yui-module";
/**
* CSS classname representing the module header. NOTE: The classname is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source.
* @property YAHOO.widget.Module.CSS_HEADER
* @static
* @final
* @type String
*/
Module.CSS_HEADER = "hd";
/**
* CSS classname representing the module body. NOTE: The classname is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source.
* @property YAHOO.widget.Module.CSS_BODY
* @static
* @final
* @type String
*/
Module.CSS_BODY = "bd";
/**
* CSS classname representing the module footer. NOTE: The classname is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source.
* @property YAHOO.widget.Module.CSS_FOOTER
* @static
* @final
* @type String
*/
Module.CSS_FOOTER = "ft";
/**
* Constant representing the url for the "src" attribute of the iframe
* used to monitor changes to the browser's base font size
* @property YAHOO.widget.Module.RESIZE_MONITOR_SECURE_URL
* @static
* @final
* @type String
*/
Module.RESIZE_MONITOR_SECURE_URL = "javascript:false;";
/**
* Constant representing the buffer amount (in pixels) to use when positioning
* the text resize monitor offscreen. The resize monitor is positioned
* offscreen by an amount eqaul to its offsetHeight + the buffer value.
*
* @property YAHOO.widget.Module.RESIZE_MONITOR_BUFFER
* @static
* @type Number
*/
// Set to 1, to work around pixel offset in IE8, which increases when zoom is used
Module.RESIZE_MONITOR_BUFFER = 1;
/**
* Singleton CustomEvent fired when the font size is changed in the browser.
* Opera's "zoom" functionality currently does not support text
* size detection.
* @event YAHOO.widget.Module.textResizeEvent
*/
Module.textResizeEvent = new CustomEvent("textResize");
/**
* Helper utility method, which forces a document level
* redraw for Opera, which can help remove repaint
* irregularities after applying DOM changes.
*
* @method YAHOO.widget.Module.forceDocumentRedraw
* @static
*/
Module.forceDocumentRedraw = function() {
var docEl = document.documentElement;
if (docEl) {
docEl.className += " ";
docEl.className = YAHOO.lang.trim(docEl.className);
}
};
function createModuleTemplate() {
if (!m_oModuleTemplate) {
m_oModuleTemplate = document.createElement("div");
m_oModuleTemplate.innerHTML = ("<div class=\"" +
Module.CSS_HEADER + "\"></div>" + "<div class=\"" +
Module.CSS_BODY + "\"></div><div class=\"" +
Module.CSS_FOOTER + "\"></div>");
m_oHeaderTemplate = m_oModuleTemplate.firstChild;
m_oBodyTemplate = m_oHeaderTemplate.nextSibling;
m_oFooterTemplate = m_oBodyTemplate.nextSibling;
}
return m_oModuleTemplate;
}
function createHeader() {
if (!m_oHeaderTemplate) {
createModuleTemplate();
}
return (m_oHeaderTemplate.cloneNode(false));
}
function createBody() {
if (!m_oBodyTemplate) {
createModuleTemplate();
}
return (m_oBodyTemplate.cloneNode(false));
}
function createFooter() {
if (!m_oFooterTemplate) {
createModuleTemplate();
}
return (m_oFooterTemplate.cloneNode(false));
}
Module.prototype = {
/**
* The class's constructor function
* @property contructor
* @type Function
*/
constructor: Module,
/**
* The main module element that contains the header, body, and footer
* @property element
* @type HTMLElement
*/
element: null,
/**
* The header element, denoted with CSS class "hd"
* @property header
* @type HTMLElement
*/
header: null,
/**
* The body element, denoted with CSS class "bd"
* @property body
* @type HTMLElement
*/
body: null,
/**
* The footer element, denoted with CSS class "ft"
* @property footer
* @type HTMLElement
*/
footer: null,
/**
* The id of the element
* @property id
* @type String
*/
id: null,
/**
* A string representing the root path for all images created by
* a Module instance.
* @deprecated It is recommend that any images for a Module be applied
* via CSS using the "background-image" property.
* @property imageRoot
* @type String
*/
imageRoot: Module.IMG_ROOT,
/**
* Initializes the custom events for Module which are fired
* automatically at appropriate times by the Module class.
* @method initEvents
*/
initEvents: function () {
var SIGNATURE = CustomEvent.LIST;
/**
* CustomEvent fired prior to class initalization.
* @event beforeInitEvent
* @param {class} classRef class reference of the initializing
* class, such as this.beforeInitEvent.fire(Module)
*/
this.beforeInitEvent = this.createEvent(EVENT_TYPES.BEFORE_INIT);
this.beforeInitEvent.signature = SIGNATURE;
/**
* CustomEvent fired after class initalization.
* @event initEvent
* @param {class} classRef class reference of the initializing
* class, such as this.beforeInitEvent.fire(Module)
*/
this.initEvent = this.createEvent(EVENT_TYPES.INIT);
this.initEvent.signature = SIGNATURE;
/**
* CustomEvent fired when the Module is appended to the DOM
* @event appendEvent
*/
this.appendEvent = this.createEvent(EVENT_TYPES.APPEND);
this.appendEvent.signature = SIGNATURE;
/**
* CustomEvent fired before the Module is rendered
* @event beforeRenderEvent
*/
this.beforeRenderEvent = this.createEvent(EVENT_TYPES.BEFORE_RENDER);
this.beforeRenderEvent.signature = SIGNATURE;
/**
* CustomEvent fired after the Module is rendered
* @event renderEvent
*/
this.renderEvent = this.createEvent(EVENT_TYPES.RENDER);
this.renderEvent.signature = SIGNATURE;
/**
* CustomEvent fired when the header content of the Module
* is modified
* @event changeHeaderEvent
* @param {String/HTMLElement} content String/element representing
* the new header content
*/
this.changeHeaderEvent = this.createEvent(EVENT_TYPES.CHANGE_HEADER);
this.changeHeaderEvent.signature = SIGNATURE;
/**
* CustomEvent fired when the body content of the Module is modified
* @event changeBodyEvent
* @param {String/HTMLElement} content String/element representing
* the new body content
*/
this.changeBodyEvent = this.createEvent(EVENT_TYPES.CHANGE_BODY);
this.changeBodyEvent.signature = SIGNATURE;
/**
* CustomEvent fired when the footer content of the Module
* is modified
* @event changeFooterEvent
* @param {String/HTMLElement} content String/element representing
* the new footer content
*/
this.changeFooterEvent = this.createEvent(EVENT_TYPES.CHANGE_FOOTER);
this.changeFooterEvent.signature = SIGNATURE;
/**
* CustomEvent fired when the content of the Module is modified
* @event changeContentEvent
*/
this.changeContentEvent = this.createEvent(EVENT_TYPES.CHANGE_CONTENT);
this.changeContentEvent.signature = SIGNATURE;
/**
* CustomEvent fired when the Module is destroyed
* @event destroyEvent
*/
this.destroyEvent = this.createEvent(EVENT_TYPES.DESTROY);
this.destroyEvent.signature = SIGNATURE;
/**
* CustomEvent fired before the Module is shown
* @event beforeShowEvent
*/
this.beforeShowEvent = this.createEvent(EVENT_TYPES.BEFORE_SHOW);
this.beforeShowEvent.signature = SIGNATURE;
/**
* CustomEvent fired after the Module is shown
* @event showEvent
*/
this.showEvent = this.createEvent(EVENT_TYPES.SHOW);
this.showEvent.signature = SIGNATURE;
/**
* CustomEvent fired before the Module is hidden
* @event beforeHideEvent
*/
this.beforeHideEvent = this.createEvent(EVENT_TYPES.BEFORE_HIDE);
this.beforeHideEvent.signature = SIGNATURE;
/**
* CustomEvent fired after the Module is hidden
* @event hideEvent
*/
this.hideEvent = this.createEvent(EVENT_TYPES.HIDE);
this.hideEvent.signature = SIGNATURE;
},
/**
* String identifying whether the current platform is windows or mac. This property
* currently only identifies these 2 platforms, and returns false otherwise.
* @property platform
* @deprecated Use YAHOO.env.ua
* @type {String|Boolean}
*/
platform: function () {
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1) {
return "windows";
} else if (ua.indexOf("macintosh") != -1) {
return "mac";
} else {
return false;
}
}(),
/**
* String representing the user-agent of the browser
* @deprecated Use YAHOO.env.ua
* @property browser
* @type {String|Boolean}
*/
browser: function () {
var ua = navigator.userAgent.toLowerCase();
/*
Check Opera first in case of spoof and check Safari before
Gecko since Safari's user agent string includes "like Gecko"
*/
if (ua.indexOf('opera') != -1) {
return 'opera';
} else if (ua.indexOf('msie 7') != -1) {
return 'ie7';
} else if (ua.indexOf('msie') != -1) {
return 'ie';
} else if (ua.indexOf('safari') != -1) {
return 'safari';
} else if (ua.indexOf('gecko') != -1) {
return 'gecko';
} else {
return false;
}
}(),
/**
* Boolean representing whether or not the current browsing context is
* secure (https)
* @property isSecure
* @type Boolean
*/
isSecure: function () {
if (window.location.href.toLowerCase().indexOf("https") === 0) {
return true;
} else {
return false;
}
}(),
/**
* Initializes the custom events for Module which are fired
* automatically at appropriate times by the Module class.
*/
initDefaultConfig: function () {
// Add properties //
/**
* Specifies whether the Module is visible on the page.
* @config visible
* @type Boolean
* @default true
*/
this.cfg.addProperty(DEFAULT_CONFIG.VISIBLE.key, {
handler: this.configVisible,
value: DEFAULT_CONFIG.VISIBLE.value,
validator: DEFAULT_CONFIG.VISIBLE.validator
});
/**
* <p>
* Object or array of objects representing the ContainerEffect
* classes that are active for animating the container.
* </p>
* <p>
* <strong>NOTE:</strong> Although this configuration
* property is introduced at the Module level, an out of the box
* implementation is not shipped for the Module class so setting
* the proroperty on the Module class has no effect. The Overlay
* class is the first class to provide out of the box ContainerEffect
* support.
* </p>
* @config effect
* @type Object
* @default null
*/
this.cfg.addProperty(DEFAULT_CONFIG.EFFECT.key, {
handler: this.configEffect,
suppressEvent: DEFAULT_CONFIG.EFFECT.suppressEvent,
supercedes: DEFAULT_CONFIG.EFFECT.supercedes
});
/**
* Specifies whether to create a special proxy iframe to monitor
* for user font resizing in the document
* @config monitorresize
* @type Boolean
* @default true
*/
this.cfg.addProperty(DEFAULT_CONFIG.MONITOR_RESIZE.key, {
handler: this.configMonitorResize,
value: DEFAULT_CONFIG.MONITOR_RESIZE.value
});
/**
* Specifies if the module should be rendered as the first child
* of document.body or appended as the last child when render is called
* with document.body as the "appendToNode".
* <p>
* Appending to the body while the DOM is still being constructed can
* lead to Operation Aborted errors in IE hence this flag is set to
* false by default.
* </p>
*
* @config appendtodocumentbody
* @type Boolean
* @default false
*/
this.cfg.addProperty(DEFAULT_CONFIG.APPEND_TO_DOCUMENT_BODY.key, {
value: DEFAULT_CONFIG.APPEND_TO_DOCUMENT_BODY.value
});
},
/**
* The Module class's initialization method, which is executed for
* Module and all of its subclasses. This method is automatically
* called by the constructor, and sets up all DOM references for
* pre-existing markup, and creates required markup if it is not
* already present.
* <p>
* If the element passed in does not have an id, one will be generated
* for it.
* </p>
* @method init
* @param {String} el The element ID representing the Module <em>OR</em>
* @param {HTMLElement} el The element representing the Module
* @param {Object} userConfig The configuration Object literal
* containing the configuration that should be set for this module.
* See configuration documentation for more details.
*/
init: function (el, userConfig) {
var elId, child;
this.initEvents();
this.beforeInitEvent.fire(Module);
/**
* The Module's Config object used for monitoring
* configuration properties.
* @property cfg
* @type YAHOO.util.Config
*/
this.cfg = new Config(this);
if (this.isSecure) {
this.imageRoot = Module.IMG_ROOT_SSL;
}
if (typeof el == "string") {
elId = el;
el = document.getElementById(el);
if (! el) {
el = (createModuleTemplate()).cloneNode(false);
el.id = elId;
}
}
this.id = Dom.generateId(el);
this.element = el;
child = this.element.firstChild;
if (child) {
var fndHd = false, fndBd = false, fndFt = false;
do {
// We're looking for elements
if (1 == child.nodeType) {
if (!fndHd && Dom.hasClass(child, Module.CSS_HEADER)) {
this.header = child;
fndHd = true;
} else if (!fndBd && Dom.hasClass(child, Module.CSS_BODY)) {
this.body = child;
fndBd = true;
} else if (!fndFt && Dom.hasClass(child, Module.CSS_FOOTER)){
this.footer = child;
fndFt = true;
}
}
} while ((child = child.nextSibling));
}
this.initDefaultConfig();
Dom.addClass(this.element, Module.CSS_MODULE);
if (userConfig) {
this.cfg.applyConfig(userConfig, true);
}
/*
Subscribe to the fireQueue() method of Config so that any
queued configuration changes are excecuted upon render of
the Module
*/
if (!Config.alreadySubscribed(this.renderEvent, this.cfg.fireQueue, this.cfg)) {
this.renderEvent.subscribe(this.cfg.fireQueue, this.cfg, true);
}
this.initEvent.fire(Module);
},
/**
* Initialize an empty IFRAME that is placed out of the visible area
* that can be used to detect text resize.
* @method initResizeMonitor
*/
initResizeMonitor: function () {
var isGeckoWin = (UA.gecko && this.platform == "windows");
if (isGeckoWin) {
// Help prevent spinning loading icon which
// started with FireFox 2.0.0.8/Win
var self = this;
setTimeout(function(){self._initResizeMonitor();}, 0);
} else {
this._initResizeMonitor();
}
},
/**
* Create and initialize the text resize monitoring iframe.
*
* @protected
* @method _initResizeMonitor
*/
_initResizeMonitor : function() {
var oDoc,
oIFrame,
sHTML;
function fireTextResize() {
Module.textResizeEvent.fire();
}
if (!UA.opera) {
oIFrame = Dom.get("_yuiResizeMonitor");
var supportsCWResize = this._supportsCWResize();
if (!oIFrame) {
oIFrame = document.createElement("iframe");
if (this.isSecure && Module.RESIZE_MONITOR_SECURE_URL && UA.ie) {
oIFrame.src = Module.RESIZE_MONITOR_SECURE_URL;
}
if (!supportsCWResize) {
// Can't monitor on contentWindow, so fire from inside iframe
sHTML = ["<html><head><script ",
"type=\"text/javascript\">",
"window.onresize=function(){window.parent.",
"YAHOO.widget.Module.textResizeEvent.",
"fire();};<",
"\/script></head>",
"<body></body></html>"].join('');
oIFrame.src = "data:text/html;charset=utf-8," + encodeURIComponent(sHTML);
}
oIFrame.id = "_yuiResizeMonitor";
oIFrame.title = "Text Resize Monitor";
oIFrame.tabIndex = -1;
oIFrame.setAttribute("role", "presentation");
/*
Need to set "position" property before inserting the
iframe into the document or Safari's status bar will
forever indicate the iframe is loading
(See YUILibrary bug #1723064)
*/
oIFrame.style.position = "absolute";
oIFrame.style.visibility = "hidden";
var db = document.body,
fc = db.firstChild;
if (fc) {
db.insertBefore(oIFrame, fc);
} else {
db.appendChild(oIFrame);
}
// Setting the background color fixes an issue with IE6/IE7, where
// elements in the DOM, with -ve margin-top which positioned them
// offscreen (so they would be overlapped by the iframe and its -ve top
// setting), would have their -ve margin-top ignored, when the iframe
// was added.
oIFrame.style.backgroundColor = "transparent";
oIFrame.style.borderWidth = "0";
oIFrame.style.width = "2em";
oIFrame.style.height = "2em";
oIFrame.style.left = "0";
oIFrame.style.top = (-1 * (oIFrame.offsetHeight + Module.RESIZE_MONITOR_BUFFER)) + "px";
oIFrame.style.visibility = "visible";
/*
Don't open/close the document for Gecko like we used to, since it
leads to duplicate cookies. (See YUILibrary bug #1721755)
*/
if (UA.webkit) {
oDoc = oIFrame.contentWindow.document;
oDoc.open();
oDoc.close();
}
}
if (oIFrame && oIFrame.contentWindow) {
Module.textResizeEvent.subscribe(this.onDomResize, this, true);
if (!Module.textResizeInitialized) {
if (supportsCWResize) {
if (!Event.on(oIFrame.contentWindow, "resize", fireTextResize)) {
/*
This will fail in IE if document.domain has
changed, so we must change the listener to
use the oIFrame element instead
*/
Event.on(oIFrame, "resize", fireTextResize);
}
}
Module.textResizeInitialized = true;
}
this.resizeMonitor = oIFrame;
}
}
},
/**
* Text resize monitor helper method.
* Determines if the browser supports resize events on iframe content windows.
*
* @private
* @method _supportsCWResize
*/
_supportsCWResize : function() {
/*
Gecko 1.8.0 (FF1.5), 1.8.1.0-5 (FF2) won't fire resize on contentWindow.
Gecko 1.8.1.6+ (FF2.0.0.6+) and all other browsers will fire resize on contentWindow.
We don't want to start sniffing for patch versions, so fire textResize the same
way on all FF2 flavors
*/
var bSupported = true;
if (UA.gecko && UA.gecko <= 1.8) {
bSupported = false;
}
return bSupported;
},
/**
* Event handler fired when the resize monitor element is resized.
* @method onDomResize
* @param {DOMEvent} e The DOM resize event
* @param {Object} obj The scope object passed to the handler
*/
onDomResize: function (e, obj) {
var nTop = -1 * (this.resizeMonitor.offsetHeight + Module.RESIZE_MONITOR_BUFFER);
this.resizeMonitor.style.top = nTop + "px";
this.resizeMonitor.style.left = "0";
},
/**
* Sets the Module's header content to the markup specified, or appends
* the passed element to the header.
*
* If no header is present, one will
* be automatically created. An empty string can be passed to the method
* to clear the contents of the header.
*
* @method setHeader
* @param {HTML} headerContent The markup used to set the header content.
* As a convenience, non HTMLElement objects can also be passed into
* the method, and will be treated as strings, with the header innerHTML
* set to their default toString implementations.
*
* <p>NOTE: Markup passed into this method is added to the DOM as HTML, and should be escaped by the implementor if coming from an external source.</p>
*
* <em>OR</em>
* @param {HTMLElement} headerContent The HTMLElement to append to
* <em>OR</em>
* @param {DocumentFragment} headerContent The document fragment
* containing elements which are to be added to the header
*/
setHeader: function (headerContent) {
var oHeader = this.header || (this.header = createHeader());
if (headerContent.nodeName) {
oHeader.innerHTML = "";
oHeader.appendChild(headerContent);
} else {
oHeader.innerHTML = headerContent;
}
if (this._rendered) {
this._renderHeader();
}
this.changeHeaderEvent.fire(headerContent);
this.changeContentEvent.fire();
},
/**
* Appends the passed element to the header. If no header is present,
* one will be automatically created.
* @method appendToHeader
* @param {HTMLElement | DocumentFragment} element The element to
* append to the header. In the case of a document fragment, the
* children of the fragment will be appended to the header.
*/
appendToHeader: function (element) {
var oHeader = this.header || (this.header = createHeader());
oHeader.appendChild(element);
this.changeHeaderEvent.fire(element);
this.changeContentEvent.fire();
},
/**
* Sets the Module's body content to the HTML specified.
*
* If no body is present, one will be automatically created.
*
* An empty string can be passed to the method to clear the contents of the body.
* @method setBody
* @param {HTML} bodyContent The HTML used to set the body content
* As a convenience, non HTMLElement objects can also be passed into
* the method, and will be treated as strings, with the body innerHTML
* set to their default toString implementations.
*
* <p>NOTE: Markup passed into this method is added to the DOM as HTML, and should be escaped by the implementor if coming from an external source.</p>
*
* <em>OR</em>
* @param {HTMLElement} bodyContent The HTMLElement to add as the first and only
* child of the body element.
* <em>OR</em>
* @param {DocumentFragment} bodyContent The document fragment
* containing elements which are to be added to the body
*/
setBody: function (bodyContent) {
var oBody = this.body || (this.body = createBody());
if (bodyContent.nodeName) {
oBody.innerHTML = "";
oBody.appendChild(bodyContent);
} else {
oBody.innerHTML = bodyContent;
}
if (this._rendered) {
this._renderBody();
}
this.changeBodyEvent.fire(bodyContent);
this.changeContentEvent.fire();
},
/**
* Appends the passed element to the body. If no body is present, one
* will be automatically created.
* @method appendToBody
* @param {HTMLElement | DocumentFragment} element The element to
* append to the body. In the case of a document fragment, the
* children of the fragment will be appended to the body.
*
*/
appendToBody: function (element) {
var oBody = this.body || (this.body = createBody());
oBody.appendChild(element);
this.changeBodyEvent.fire(element);
this.changeContentEvent.fire();
},
/**
* Sets the Module's footer content to the HTML specified, or appends
* the passed element to the footer. If no footer is present, one will
* be automatically created. An empty string can be passed to the method
* to clear the contents of the footer.
* @method setFooter
* @param {HTML} footerContent The HTML used to set the footer
* As a convenience, non HTMLElement objects can also be passed into
* the method, and will be treated as strings, with the footer innerHTML
* set to their default toString implementations.
*
* <p>NOTE: Markup passed into this method is added to the DOM as HTML, and should be escaped by the implementor if coming from an external source.</p>
*
* <em>OR</em>
* @param {HTMLElement} footerContent The HTMLElement to append to
* the footer
* <em>OR</em>
* @param {DocumentFragment} footerContent The document fragment containing
* elements which are to be added to the footer
*/
setFooter: function (footerContent) {
var oFooter = this.footer || (this.footer = createFooter());
if (footerContent.nodeName) {
oFooter.innerHTML = "";
oFooter.appendChild(footerContent);
} else {
oFooter.innerHTML = footerContent;
}
if (this._rendered) {
this._renderFooter();
}
this.changeFooterEvent.fire(footerContent);
this.changeContentEvent.fire();
},
/**
* Appends the passed element to the footer. If no footer is present,
* one will be automatically created.
* @method appendToFooter
* @param {HTMLElement | DocumentFragment} element The element to
* append to the footer. In the case of a document fragment, the
* children of the fragment will be appended to the footer
*/
appendToFooter: function (element) {
var oFooter = this.footer || (this.footer = createFooter());
oFooter.appendChild(element);
this.changeFooterEvent.fire(element);
this.changeContentEvent.fire();
},
/**
* Renders the Module by inserting the elements that are not already
* in the main Module into their correct places. Optionally appends
* the Module to the specified node prior to the render's execution.
* <p>
* For Modules without existing markup, the appendToNode argument
* is REQUIRED. If this argument is ommitted and the current element is
* not present in the document, the function will return false,
* indicating that the render was a failure.
* </p>
* <p>
* NOTE: As of 2.3.1, if the appendToNode is the document's body element
* then the module is rendered as the first child of the body element,
* and not appended to it, to avoid Operation Aborted errors in IE when
* rendering the module before window's load event is fired. You can
* use the appendtodocumentbody configuration property to change this
* to append to document.body if required.
* </p>
* @method render
* @param {String} appendToNode The element id to which the Module
* should be appended to prior to rendering <em>OR</em>
* @param {HTMLElement} appendToNode The element to which the Module
* should be appended to prior to rendering
* @param {HTMLElement} moduleElement OPTIONAL. The element that
* represents the actual Standard Module container.
* @return {Boolean} Success or failure of the render
*/
render: function (appendToNode, moduleElement) {
var me = this;
function appendTo(parentNode) {
if (typeof parentNode == "string") {
parentNode = document.getElementById(parentNode);
}
if (parentNode) {
me._addToParent(parentNode, me.element);
me.appendEvent.fire();
}
}
this.beforeRenderEvent.fire();
if (! moduleElement) {
moduleElement = this.element;
}
if (appendToNode) {
appendTo(appendToNode);
} else {
// No node was passed in. If the element is not already in the Dom, this fails
if (! Dom.inDocument(this.element)) {
return false;
}
}
this._renderHeader(moduleElement);
this._renderBody(moduleElement);
this._renderFooter(moduleElement);
this._rendered = true;
this.renderEvent.fire();
return true;
},
/**
* Renders the currently set header into it's proper position under the
* module element. If the module element is not provided, "this.element"
* is used.
*
* @method _renderHeader
* @protected
* @param {HTMLElement} moduleElement Optional. A reference to the module element
*/
_renderHeader: function(moduleElement){
moduleElement = moduleElement || this.element;
// Need to get everything into the DOM if it isn't already
if (this.header && !Dom.inDocument(this.header)) {
// There is a header, but it's not in the DOM yet. Need to add it.
var firstChild = moduleElement.firstChild;
if (firstChild) {
moduleElement.insertBefore(this.header, firstChild);
} else {
moduleElement.appendChild(this.header);
}
}
},
/**
* Renders the currently set body into it's proper position under the
* module element. If the module element is not provided, "this.element"
* is used.
*
* @method _renderBody
* @protected
* @param {HTMLElement} moduleElement Optional. A reference to the module element.
*/
_renderBody: function(moduleElement){
moduleElement = moduleElement || this.element;
if (this.body && !Dom.inDocument(this.body)) {
// There is a body, but it's not in the DOM yet. Need to add it.
if (this.footer && Dom.isAncestor(moduleElement, this.footer)) {
moduleElement.insertBefore(this.body, this.footer);
} else {
moduleElement.appendChild(this.body);
}
}
},
/**
* Renders the currently set footer into it's proper position under the
* module element. If the module element is not provided, "this.element"
* is used.
*
* @method _renderFooter
* @protected
* @param {HTMLElement} moduleElement Optional. A reference to the module element
*/
_renderFooter: function(moduleElement){
moduleElement = moduleElement || this.element;
if (this.footer && !Dom.inDocument(this.footer)) {
// There is a footer, but it's not in the DOM yet. Need to add it.
moduleElement.appendChild(this.footer);
}
},
/**
* Removes the Module element from the DOM, sets all child elements to null, and purges the bounding element of event listeners.
* @method destroy
* @param {boolean} shallowPurge If true, only the parent element's DOM event listeners are purged. If false, or not provided, all children are also purged of DOM event listeners.
* NOTE: The flag is a "shallowPurge" flag, as opposed to what may be a more intuitive "purgeChildren" flag to maintain backwards compatibility with behavior prior to 2.9.0.
*/
destroy: function (shallowPurge) {
var parent,
purgeChildren = !(shallowPurge);
if (this.element) {
Event.purgeElement(this.element, purgeChildren);
parent = this.element.parentNode;
}
if (parent) {
parent.removeChild(this.element);
}
this.element = null;
this.header = null;
this.body = null;
this.footer = null;
Module.textResizeEvent.unsubscribe(this.onDomResize, this);
this.cfg.destroy();
this.cfg = null;
this.destroyEvent.fire();
},
/**
* Shows the Module element by setting the visible configuration
* property to true. Also fires two events: beforeShowEvent prior to
* the visibility change, and showEvent after.
* @method show
*/
show: function () {
this.cfg.setProperty("visible", true);
},
/**
* Hides the Module element by setting the visible configuration
* property to false. Also fires two events: beforeHideEvent prior to
* the visibility change, and hideEvent after.
* @method hide
*/
hide: function () {
this.cfg.setProperty("visible", false);
},
// BUILT-IN EVENT HANDLERS FOR MODULE //
/**
* Default event handler for changing the visibility property of a
* Module. By default, this is achieved by switching the "display" style
* between "block" and "none".
* This method is responsible for firing showEvent and hideEvent.
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
* @method configVisible
*/
configVisible: function (type, args, obj) {
var visible = args[0];
if (visible) {
if(this.beforeShowEvent.fire()) {
Dom.setStyle(this.element, "display", "block");
this.showEvent.fire();
}
} else {
if (this.beforeHideEvent.fire()) {
Dom.setStyle(this.element, "display", "none");
this.hideEvent.fire();
}
}
},
/**
* Default event handler for the "effect" configuration property
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
* @method configEffect
*/
configEffect: function (type, args, obj) {
this._cachedEffects = (this.cacheEffects) ? this._createEffects(args[0]) : null;
},
/**
* If true, ContainerEffects (and Anim instances) are cached when "effect" is set, and reused.
* If false, new instances are created each time the container is hidden or shown, as was the
* behavior prior to 2.9.0.
*
* @property cacheEffects
* @since 2.9.0
* @default true
* @type boolean
*/
cacheEffects : true,
/**
* Creates an array of ContainerEffect instances from the provided configs
*
* @method _createEffects
* @param {Array|Object} effectCfg An effect configuration or array of effect configurations
* @return {Array} An array of ContainerEffect instances.
* @protected
*/
_createEffects: function(effectCfg) {
var effectInstances = null,
n,
i,
eff;
if (effectCfg) {
if (effectCfg instanceof Array) {
effectInstances = [];
n = effectCfg.length;
for (i = 0; i < n; i++) {
eff = effectCfg[i];
if (eff.effect) {
effectInstances[effectInstances.length] = eff.effect(this, eff.duration);
}
}
} else if (effectCfg.effect) {
effectInstances = [effectCfg.effect(this, effectCfg.duration)];
}
}
return effectInstances;
},
/**
* Default event handler for the "monitorresize" configuration property
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
* @method configMonitorResize
*/
configMonitorResize: function (type, args, obj) {
var monitor = args[0];
if (monitor) {
this.initResizeMonitor();
} else {
Module.textResizeEvent.unsubscribe(this.onDomResize, this, true);
this.resizeMonitor = null;
}
},
/**
* This method is a protected helper, used when constructing the DOM structure for the module
* to account for situations which may cause Operation Aborted errors in IE. It should not
* be used for general DOM construction.
* <p>
* If the parentNode is not document.body, the element is appended as the last element.
* </p>
* <p>
* If the parentNode is document.body the element is added as the first child to help
* prevent Operation Aborted errors in IE.
* </p>
*
* @param {parentNode} The HTML element to which the element will be added
* @param {element} The HTML element to be added to parentNode's children
* @method _addToParent
* @protected
*/
_addToParent: function(parentNode, element) {
if (!this.cfg.getProperty("appendtodocumentbody") && parentNode === document.body && parentNode.firstChild) {
parentNode.insertBefore(element, parentNode.firstChild);
} else {
parentNode.appendChild(element);
}
},
/**
* Returns a String representation of the Object.
* @method toString
* @return {String} The string representation of the Module
*/
toString: function () {
return "Module " + this.id;
}
};
YAHOO.lang.augmentProto(Module, YAHOO.util.EventProvider);
}());
(function () {
/**
* Overlay is a Module that is absolutely positioned above the page flow. It
* has convenience methods for positioning and sizing, as well as options for
* controlling zIndex and constraining the Overlay's position to the current
* visible viewport. Overlay also contains a dynamicly generated IFRAME which
* is placed beneath it for Internet Explorer 6 and 5.x so that it will be
* properly rendered above SELECT elements.
* @namespace YAHOO.widget
* @class Overlay
* @extends YAHOO.widget.Module
* @param {String} el The element ID representing the Overlay <em>OR</em>
* @param {HTMLElement} el The element representing the Overlay
* @param {Object} userConfig The configuration object literal containing
* the configuration that should be set for this Overlay. See configuration
* documentation for more details.
* @constructor
*/
YAHOO.widget.Overlay = function (el, userConfig) {
YAHOO.widget.Overlay.superclass.constructor.call(this, el, userConfig);
};
var Lang = YAHOO.lang,
CustomEvent = YAHOO.util.CustomEvent,
Module = YAHOO.widget.Module,
Event = YAHOO.util.Event,
Dom = YAHOO.util.Dom,
Config = YAHOO.util.Config,
UA = YAHOO.env.ua,
Overlay = YAHOO.widget.Overlay,
_SUBSCRIBE = "subscribe",
_UNSUBSCRIBE = "unsubscribe",
_CONTAINED = "contained",
m_oIFrameTemplate,
/**
* Constant representing the name of the Overlay's events
* @property EVENT_TYPES
* @private
* @final
* @type Object
*/
EVENT_TYPES = {
"BEFORE_MOVE": "beforeMove",
"MOVE": "move"
},
/**
* Constant representing the Overlay's configuration properties
* @property DEFAULT_CONFIG
* @private
* @final
* @type Object
*/
DEFAULT_CONFIG = {
"X": {
key: "x",
validator: Lang.isNumber,
suppressEvent: true,
supercedes: ["iframe"]
},
"Y": {
key: "y",
validator: Lang.isNumber,
suppressEvent: true,
supercedes: ["iframe"]
},
"XY": {
key: "xy",
suppressEvent: true,
supercedes: ["iframe"]
},
"CONTEXT": {
key: "context",
suppressEvent: true,
supercedes: ["iframe"]
},
"FIXED_CENTER": {
key: "fixedcenter",
value: false,
supercedes: ["iframe", "visible"]
},
"WIDTH": {
key: "width",
suppressEvent: true,
supercedes: ["context", "fixedcenter", "iframe"]
},
"HEIGHT": {
key: "height",
suppressEvent: true,
supercedes: ["context", "fixedcenter", "iframe"]
},
"AUTO_FILL_HEIGHT" : {
key: "autofillheight",
supercedes: ["height"],
value:"body"
},
"ZINDEX": {
key: "zindex",
value: null
},
"CONSTRAIN_TO_VIEWPORT": {
key: "constraintoviewport",
value: false,
validator: Lang.isBoolean,
supercedes: ["iframe", "x", "y", "xy"]
},
"IFRAME": {
key: "iframe",
value: (UA.ie == 6 ? true : false),
validator: Lang.isBoolean,
supercedes: ["zindex"]
},
"PREVENT_CONTEXT_OVERLAP": {
key: "preventcontextoverlap",
value: false,
validator: Lang.isBoolean,
supercedes: ["constraintoviewport"]
}
};
/**
* The URL that will be placed in the iframe
* @property YAHOO.widget.Overlay.IFRAME_SRC
* @static
* @final
* @type String
*/
Overlay.IFRAME_SRC = "javascript:false;";
/**
* Number representing how much the iframe shim should be offset from each
* side of an Overlay instance, in pixels.
* @property YAHOO.widget.Overlay.IFRAME_SRC
* @default 3
* @static
* @final
* @type Number
*/
Overlay.IFRAME_OFFSET = 3;
/**
* Number representing the minimum distance an Overlay instance should be
* positioned relative to the boundaries of the browser's viewport, in pixels.
* @property YAHOO.widget.Overlay.VIEWPORT_OFFSET
* @default 10
* @static
* @final
* @type Number
*/
Overlay.VIEWPORT_OFFSET = 10;
/**
* Constant representing the top left corner of an element, used for
* configuring the context element alignment
* @property YAHOO.widget.Overlay.TOP_LEFT
* @static
* @final
* @type String
*/
Overlay.TOP_LEFT = "tl";
/**
* Constant representing the top right corner of an element, used for
* configuring the context element alignment
* @property YAHOO.widget.Overlay.TOP_RIGHT
* @static
* @final
* @type String
*/
Overlay.TOP_RIGHT = "tr";
/**
* Constant representing the top bottom left corner of an element, used for
* configuring the context element alignment
* @property YAHOO.widget.Overlay.BOTTOM_LEFT
* @static
* @final
* @type String
*/
Overlay.BOTTOM_LEFT = "bl";
/**
* Constant representing the bottom right corner of an element, used for
* configuring the context element alignment
* @property YAHOO.widget.Overlay.BOTTOM_RIGHT
* @static
* @final
* @type String
*/
Overlay.BOTTOM_RIGHT = "br";
Overlay.PREVENT_OVERLAP_X = {
"tltr": true,
"blbr": true,
"brbl": true,
"trtl": true
};
Overlay.PREVENT_OVERLAP_Y = {
"trbr": true,
"tlbl": true,
"bltl": true,
"brtr": true
};
/**
* Constant representing the default CSS class used for an Overlay
* @property YAHOO.widget.Overlay.CSS_OVERLAY
* @static
* @final
* @type String
*/
Overlay.CSS_OVERLAY = "yui-overlay";
/**
* Constant representing the default hidden CSS class used for an Overlay. This class is
* applied to the overlay's outer DIV whenever it's hidden.
*
* @property YAHOO.widget.Overlay.CSS_HIDDEN
* @static
* @final
* @type String
*/
Overlay.CSS_HIDDEN = "yui-overlay-hidden";
/**
* Constant representing the default CSS class used for an Overlay iframe shim.
*
* @property YAHOO.widget.Overlay.CSS_IFRAME
* @static
* @final
* @type String
*/
Overlay.CSS_IFRAME = "yui-overlay-iframe";
/**
* Constant representing the names of the standard module elements
* used in the overlay.
* @property YAHOO.widget.Overlay.STD_MOD_RE
* @static
* @final
* @type RegExp
*/
Overlay.STD_MOD_RE = /^\s*?(body|footer|header)\s*?$/i;
/**
* A singleton CustomEvent used for reacting to the DOM event for
* window scroll
* @event YAHOO.widget.Overlay.windowScrollEvent
*/
Overlay.windowScrollEvent = new CustomEvent("windowScroll");
/**
* A singleton CustomEvent used for reacting to the DOM event for
* window resize
* @event YAHOO.widget.Overlay.windowResizeEvent
*/
Overlay.windowResizeEvent = new CustomEvent("windowResize");
/**
* The DOM event handler used to fire the CustomEvent for window scroll
* @method YAHOO.widget.Overlay.windowScrollHandler
* @static
* @param {DOMEvent} e The DOM scroll event
*/
Overlay.windowScrollHandler = function (e) {
var t = Event.getTarget(e);
// - Webkit (Safari 2/3) and Opera 9.2x bubble scroll events from elements to window
// - FF2/3 and IE6/7, Opera 9.5x don't bubble scroll events from elements to window
// - IE doesn't recognize scroll registered on the document.
//
// Also, when document view is scrolled, IE doesn't provide a target,
// rest of the browsers set target to window.document, apart from opera
// which sets target to window.
if (!t || t === window || t === window.document) {
if (UA.ie) {
if (! window.scrollEnd) {
window.scrollEnd = -1;
}
clearTimeout(window.scrollEnd);
window.scrollEnd = setTimeout(function () {
Overlay.windowScrollEvent.fire();
}, 1);
} else {
Overlay.windowScrollEvent.fire();
}
}
};
/**
* The DOM event handler used to fire the CustomEvent for window resize
* @method YAHOO.widget.Overlay.windowResizeHandler
* @static
* @param {DOMEvent} e The DOM resize event
*/
Overlay.windowResizeHandler = function (e) {
if (UA.ie) {
if (! window.resizeEnd) {
window.resizeEnd = -1;
}
clearTimeout(window.resizeEnd);
window.resizeEnd = setTimeout(function () {
Overlay.windowResizeEvent.fire();
}, 100);
} else {
Overlay.windowResizeEvent.fire();
}
};
/**
* A boolean that indicated whether the window resize and scroll events have
* already been subscribed to.
* @property YAHOO.widget.Overlay._initialized
* @private
* @type Boolean
*/
Overlay._initialized = null;
if (Overlay._initialized === null) {
Event.on(window, "scroll", Overlay.windowScrollHandler);
Event.on(window, "resize", Overlay.windowResizeHandler);
Overlay._initialized = true;
}
/**
* Internal map of special event types, which are provided
* by the instance. It maps the event type to the custom event
* instance. Contains entries for the "windowScroll", "windowResize" and
* "textResize" static container events.
*
* @property YAHOO.widget.Overlay._TRIGGER_MAP
* @type Object
* @static
* @private
*/
Overlay._TRIGGER_MAP = {
"windowScroll" : Overlay.windowScrollEvent,
"windowResize" : Overlay.windowResizeEvent,
"textResize" : Module.textResizeEvent
};
YAHOO.extend(Overlay, Module, {
/**
* <p>
* Array of default event types which will trigger
* context alignment for the Overlay class.
* </p>
* <p>The array is empty by default for Overlay,
* but maybe populated in future releases, so classes extending
* Overlay which need to define their own set of CONTEXT_TRIGGERS
* should concatenate their super class's prototype.CONTEXT_TRIGGERS
* value with their own array of values.
* </p>
* <p>
* E.g.:
* <code>CustomOverlay.prototype.CONTEXT_TRIGGERS = YAHOO.widget.Overlay.prototype.CONTEXT_TRIGGERS.concat(["windowScroll"]);</code>
* </p>
*
* @property CONTEXT_TRIGGERS
* @type Array
* @final
*/
CONTEXT_TRIGGERS : [],
/**
* The Overlay initialization method, which is executed for Overlay and
* all of its subclasses. This method is automatically called by the
* constructor, and sets up all DOM references for pre-existing markup,
* and creates required markup if it is not already present.
* @method init
* @param {String} el The element ID representing the Overlay <em>OR</em>
* @param {HTMLElement} el The element representing the Overlay
* @param {Object} userConfig The configuration object literal
* containing the configuration that should be set for this Overlay.
* See configuration documentation for more details.
*/
init: function (el, userConfig) {
/*
Note that we don't pass the user config in here yet because we
only want it executed once, at the lowest subclass level
*/
Overlay.superclass.init.call(this, el/*, userConfig*/);
this.beforeInitEvent.fire(Overlay);
Dom.addClass(this.element, Overlay.CSS_OVERLAY);
if (userConfig) {
this.cfg.applyConfig(userConfig, true);
}
if (this.platform == "mac" && UA.gecko) {
if (! Config.alreadySubscribed(this.showEvent,
this.showMacGeckoScrollbars, this)) {
this.showEvent.subscribe(this.showMacGeckoScrollbars,
this, true);
}
if (! Config.alreadySubscribed(this.hideEvent,
this.hideMacGeckoScrollbars, this)) {
this.hideEvent.subscribe(this.hideMacGeckoScrollbars,
this, true);
}
}
this.initEvent.fire(Overlay);
},
/**
* Initializes the custom events for Overlay which are fired
* automatically at appropriate times by the Overlay class.
* @method initEvents
*/
initEvents: function () {
Overlay.superclass.initEvents.call(this);
var SIGNATURE = CustomEvent.LIST;
/**
* CustomEvent fired before the Overlay is moved.
* @event beforeMoveEvent
* @param {Number} x x coordinate
* @param {Number} y y coordinate
*/
this.beforeMoveEvent = this.createEvent(EVENT_TYPES.BEFORE_MOVE);
this.beforeMoveEvent.signature = SIGNATURE;
/**
* CustomEvent fired after the Overlay is moved.
* @event moveEvent
* @param {Number} x x coordinate
* @param {Number} y y coordinate
*/
this.moveEvent = this.createEvent(EVENT_TYPES.MOVE);
this.moveEvent.signature = SIGNATURE;
},
/**
* Initializes the class's configurable properties which can be changed
* using the Overlay's Config object (cfg).
* @method initDefaultConfig
*/
initDefaultConfig: function () {
Overlay.superclass.initDefaultConfig.call(this);
var cfg = this.cfg;
// Add overlay config properties //
/**
* The absolute x-coordinate position of the Overlay
* @config x
* @type Number
* @default null
*/
cfg.addProperty(DEFAULT_CONFIG.X.key, {
handler: this.configX,
validator: DEFAULT_CONFIG.X.validator,
suppressEvent: DEFAULT_CONFIG.X.suppressEvent,
supercedes: DEFAULT_CONFIG.X.supercedes
});
/**
* The absolute y-coordinate position of the Overlay
* @config y
* @type Number
* @default null
*/
cfg.addProperty(DEFAULT_CONFIG.Y.key, {
handler: this.configY,
validator: DEFAULT_CONFIG.Y.validator,
suppressEvent: DEFAULT_CONFIG.Y.suppressEvent,
supercedes: DEFAULT_CONFIG.Y.supercedes
});
/**
* An array with the absolute x and y positions of the Overlay
* @config xy
* @type Number[]
* @default null
*/
cfg.addProperty(DEFAULT_CONFIG.XY.key, {
handler: this.configXY,
suppressEvent: DEFAULT_CONFIG.XY.suppressEvent,
supercedes: DEFAULT_CONFIG.XY.supercedes
});
/**
* <p>
* The array of context arguments for context-sensitive positioning.
* </p>
*
* <p>
* The format of the array is: <code>[contextElementOrId, overlayCorner, contextCorner, arrayOfTriggerEvents (optional), xyOffset (optional)]</code>, the
* the 5 array elements described in detail below:
* </p>
*
* <dl>
* <dt>contextElementOrId <String|HTMLElement></dt>
* <dd>A reference to the context element to which the overlay should be aligned (or it's id).</dd>
* <dt>overlayCorner <String></dt>
* <dd>The corner of the overlay which is to be used for alignment. This corner will be aligned to the
* corner of the context element defined by the "contextCorner" entry which follows. Supported string values are:
* "tr" (top right), "tl" (top left), "br" (bottom right), or "bl" (bottom left).</dd>
* <dt>contextCorner <String></dt>
* <dd>The corner of the context element which is to be used for alignment. Supported string values are the same ones listed for the "overlayCorner" entry above.</dd>
* <dt>arrayOfTriggerEvents (optional) <Array[String|CustomEvent]></dt>
* <dd>
* <p>
* By default, context alignment is a one time operation, aligning the Overlay to the context element when context configuration property is set, or when the <a href="#method_align">align</a>
* method is invoked. However, you can use the optional "arrayOfTriggerEvents" entry to define the list of events which should force the overlay to re-align itself with the context element.
* This is useful in situations where the layout of the document may change, resulting in the context element's position being modified.
* </p>
* <p>
* The array can contain either event type strings for events the instance publishes (e.g. "beforeShow") or CustomEvent instances. Additionally the following
* 3 static container event types are also currently supported : <code>"windowResize", "windowScroll", "textResize"</code> (defined in <a href="#property__TRIGGER_MAP">_TRIGGER_MAP</a> private property).
* </p>
* </dd>
* <dt>xyOffset <Number[]></dt>
* <dd>
* A 2 element Array specifying the X and Y pixel amounts by which the Overlay should be offset from the aligned corner. e.g. [5,0] offsets the Overlay 5 pixels to the left, <em>after</em> aligning the given context corners.
* NOTE: If using this property and no triggers need to be defined, the arrayOfTriggerEvents property should be set to null to maintain correct array positions for the arguments.
* </dd>
* </dl>
*
* <p>
* For example, setting this property to <code>["img1", "tl", "bl"]</code> will
* align the Overlay's top left corner to the bottom left corner of the
* context element with id "img1".
* </p>
* <p>
* Setting this property to <code>["img1", "tl", "bl", null, [0,5]</code> will
* align the Overlay's top left corner to the bottom left corner of the
* context element with id "img1", and then offset it by 5 pixels on the Y axis (providing a 5 pixel gap between the bottom of the context element and top of the overlay).
* </p>
* <p>
* Adding the optional trigger values: <code>["img1", "tl", "bl", ["beforeShow", "windowResize"], [0,5]]</code>,
* will re-align the overlay position, whenever the "beforeShow" or "windowResize" events are fired.
* </p>
*
* @config context
* @type Array
* @default null
*/
cfg.addProperty(DEFAULT_CONFIG.CONTEXT.key, {
handler: this.configContext,
suppressEvent: DEFAULT_CONFIG.CONTEXT.suppressEvent,
supercedes: DEFAULT_CONFIG.CONTEXT.supercedes
});
/**
* Determines whether or not the Overlay should be anchored
* to the center of the viewport.
*
* <p>This property can be set to:</p>
*
* <dl>
* <dt>true</dt>
* <dd>
* To enable fixed center positioning
* <p>
* When enabled, the overlay will
* be positioned in the center of viewport when initially displayed, and
* will remain in the center of the viewport whenever the window is
* scrolled or resized.
* </p>
* <p>
* If the overlay is too big for the viewport,
* it's top left corner will be aligned with the top left corner of the viewport.
* </p>
* </dd>
* <dt>false</dt>
* <dd>
* To disable fixed center positioning.
* <p>In this case the overlay can still be
* centered as a one-off operation, by invoking the <code>center()</code> method,
* however it will not remain centered when the window is scrolled/resized.
* </dd>
* <dt>"contained"<dt>
* <dd>To enable fixed center positioning, as with the <code>true</code> option.
* <p>However, unlike setting the property to <code>true</code>,
* when the property is set to <code>"contained"</code>, if the overlay is
* too big for the viewport, it will not get automatically centered when the
* user scrolls or resizes the window (until the window is large enough to contain the
* overlay). This is useful in cases where the Overlay has both header and footer
* UI controls which the user may need to access.
* </p>
* </dd>
* </dl>
*
* @config fixedcenter
* @type Boolean | String
* @default false
*/
cfg.addProperty(DEFAULT_CONFIG.FIXED_CENTER.key, {
handler: this.configFixedCenter,
value: DEFAULT_CONFIG.FIXED_CENTER.value,
validator: DEFAULT_CONFIG.FIXED_CENTER.validator,
supercedes: DEFAULT_CONFIG.FIXED_CENTER.supercedes
});
/**
* CSS width of the Overlay.
* @config width
* @type String
* @default null
*/
cfg.addProperty(DEFAULT_CONFIG.WIDTH.key, {
handler: this.configWidth,
suppressEvent: DEFAULT_CONFIG.WIDTH.suppressEvent,
supercedes: DEFAULT_CONFIG.WIDTH.supercedes
});
/**
* CSS height of the Overlay.
* @config height
* @type String
* @default null
*/
cfg.addProperty(DEFAULT_CONFIG.HEIGHT.key, {
handler: this.configHeight,
suppressEvent: DEFAULT_CONFIG.HEIGHT.suppressEvent,
supercedes: DEFAULT_CONFIG.HEIGHT.supercedes
});
/**
* Standard module element which should auto fill out the height of the Overlay if the height config property is set.
* Supported values are "header", "body", "footer".
*
* @config autofillheight
* @type String
* @default null
*/
cfg.addProperty(DEFAULT_CONFIG.AUTO_FILL_HEIGHT.key, {
handler: this.configAutoFillHeight,
value : DEFAULT_CONFIG.AUTO_FILL_HEIGHT.value,
validator : this._validateAutoFill,
supercedes: DEFAULT_CONFIG.AUTO_FILL_HEIGHT.supercedes
});
/**
* CSS z-index of the Overlay.
* @config zIndex
* @type Number
* @default null
*/
cfg.addProperty(DEFAULT_CONFIG.ZINDEX.key, {
handler: this.configzIndex,
value: DEFAULT_CONFIG.ZINDEX.value
});
/**
* True if the Overlay should be prevented from being positioned
* out of the viewport.
* @config constraintoviewport
* @type Boolean
* @default false
*/
cfg.addProperty(DEFAULT_CONFIG.CONSTRAIN_TO_VIEWPORT.key, {
handler: this.configConstrainToViewport,
value: DEFAULT_CONFIG.CONSTRAIN_TO_VIEWPORT.value,
validator: DEFAULT_CONFIG.CONSTRAIN_TO_VIEWPORT.validator,
supercedes: DEFAULT_CONFIG.CONSTRAIN_TO_VIEWPORT.supercedes
});
/**
* @config iframe
* @description Boolean indicating whether or not the Overlay should
* have an IFRAME shim; used to prevent SELECT elements from
* poking through an Overlay instance in IE6. When set to "true",
* the iframe shim is created when the Overlay instance is intially
* made visible.
* @type Boolean
* @default true for IE6 and below, false for all other browsers.
*/
cfg.addProperty(DEFAULT_CONFIG.IFRAME.key, {
handler: this.configIframe,
value: DEFAULT_CONFIG.IFRAME.value,
validator: DEFAULT_CONFIG.IFRAME.validator,
supercedes: DEFAULT_CONFIG.IFRAME.supercedes
});
/**
* @config preventcontextoverlap
* @description Boolean indicating whether or not the Overlay should overlap its
* context element (defined using the "context" configuration property) when the
* "constraintoviewport" configuration property is set to "true".
* @type Boolean
* @default false
*/
cfg.addProperty(DEFAULT_CONFIG.PREVENT_CONTEXT_OVERLAP.key, {
value: DEFAULT_CONFIG.PREVENT_CONTEXT_OVERLAP.value,
validator: DEFAULT_CONFIG.PREVENT_CONTEXT_OVERLAP.validator,
supercedes: DEFAULT_CONFIG.PREVENT_CONTEXT_OVERLAP.supercedes
});
},
/**
* Moves the Overlay to the specified position. This function is
* identical to calling this.cfg.setProperty("xy", [x,y]);
* @method moveTo
* @param {Number} x The Overlay's new x position
* @param {Number} y The Overlay's new y position
*/
moveTo: function (x, y) {
this.cfg.setProperty("xy", [x, y]);
},
/**
* Adds a CSS class ("hide-scrollbars") and removes a CSS class
* ("show-scrollbars") to the Overlay to fix a bug in Gecko on Mac OS X
* (https://bugzilla.mozilla.org/show_bug.cgi?id=187435)
* @method hideMacGeckoScrollbars
*/
hideMacGeckoScrollbars: function () {
Dom.replaceClass(this.element, "show-scrollbars", "hide-scrollbars");
},
/**
* Adds a CSS class ("show-scrollbars") and removes a CSS class
* ("hide-scrollbars") to the Overlay to fix a bug in Gecko on Mac OS X
* (https://bugzilla.mozilla.org/show_bug.cgi?id=187435)
* @method showMacGeckoScrollbars
*/
showMacGeckoScrollbars: function () {
Dom.replaceClass(this.element, "hide-scrollbars", "show-scrollbars");
},
/**
* Internal implementation to set the visibility of the overlay in the DOM.
*
* @method _setDomVisibility
* @param {boolean} visible Whether to show or hide the Overlay's outer element
* @protected
*/
_setDomVisibility : function(show) {
Dom.setStyle(this.element, "visibility", (show) ? "visible" : "hidden");
var hiddenClass = Overlay.CSS_HIDDEN;
if (show) {
Dom.removeClass(this.element, hiddenClass);
} else {
Dom.addClass(this.element, hiddenClass);
}
},
// BEGIN BUILT-IN PROPERTY EVENT HANDLERS //
/**
* The default event handler fired when the "visible" property is
* changed. This method is responsible for firing showEvent
* and hideEvent.
* @method configVisible
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configVisible: function (type, args, obj) {
var visible = args[0],
currentVis = Dom.getStyle(this.element, "visibility"),
effects = this._cachedEffects || this._createEffects(this.cfg.getProperty("effect")),
isMacGecko = (this.platform == "mac" && UA.gecko),
alreadySubscribed = Config.alreadySubscribed,
ei, e, j, k, h,
nEffectInstances;
if (currentVis == "inherit") {
e = this.element.parentNode;
while (e.nodeType != 9 && e.nodeType != 11) {
currentVis = Dom.getStyle(e, "visibility");
if (currentVis != "inherit") {
break;
}
e = e.parentNode;
}
if (currentVis == "inherit") {
currentVis = "visible";
}
}
if (visible) { // Show
if (isMacGecko) {
this.showMacGeckoScrollbars();
}
if (effects) { // Animate in
if (visible) { // Animate in if not showing
// Fading out is a bit of a hack, but didn't want to risk doing
// something broader (e.g a generic this._animatingOut) for 2.9.0
if (currentVis != "visible" || currentVis === "" || this._fadingOut) {
if (this.beforeShowEvent.fire()) {
nEffectInstances = effects.length;
for (j = 0; j < nEffectInstances; j++) {
ei = effects[j];
if (j === 0 && !alreadySubscribed(ei.animateInCompleteEvent, this.showEvent.fire, this.showEvent)) {
ei.animateInCompleteEvent.subscribe(this.showEvent.fire, this.showEvent, true);
}
ei.animateIn();
}
}
}
}
} else { // Show
if (currentVis != "visible" || currentVis === "") {
if (this.beforeShowEvent.fire()) {
this._setDomVisibility(true);
this.cfg.refireEvent("iframe");
this.showEvent.fire();
}
} else {
this._setDomVisibility(true);
}
}
} else { // Hide
if (isMacGecko) {
this.hideMacGeckoScrollbars();
}
if (effects) { // Animate out if showing
if (currentVis == "visible" || this._fadingIn) {
if (this.beforeHideEvent.fire()) {
nEffectInstances = effects.length;
for (k = 0; k < nEffectInstances; k++) {
h = effects[k];
if (k === 0 && !alreadySubscribed(h.animateOutCompleteEvent, this.hideEvent.fire, this.hideEvent)) {
h.animateOutCompleteEvent.subscribe(this.hideEvent.fire, this.hideEvent, true);
}
h.animateOut();
}
}
} else if (currentVis === "") {
this._setDomVisibility(false);
}
} else { // Simple hide
if (currentVis == "visible" || currentVis === "") {
if (this.beforeHideEvent.fire()) {
this._setDomVisibility(false);
this.hideEvent.fire();
}
} else {
this._setDomVisibility(false);
}
}
}
},
/**
* Fixed center event handler used for centering on scroll/resize, but only if
* the overlay is visible and, if "fixedcenter" is set to "contained", only if
* the overlay fits within the viewport.
*
* @method doCenterOnDOMEvent
*/
doCenterOnDOMEvent: function () {
var cfg = this.cfg,
fc = cfg.getProperty("fixedcenter");
if (cfg.getProperty("visible")) {
if (fc && (fc !== _CONTAINED || this.fitsInViewport())) {
this.center();
}
}
},
/**
* Determines if the Overlay (including the offset value defined by Overlay.VIEWPORT_OFFSET)
* will fit entirely inside the viewport, in both dimensions - width and height.
*
* @method fitsInViewport
* @return boolean true if the Overlay will fit, false if not
*/
fitsInViewport : function() {
var nViewportOffset = Overlay.VIEWPORT_OFFSET,
element = this.element,
elementWidth = element.offsetWidth,
elementHeight = element.offsetHeight,
viewportWidth = Dom.getViewportWidth(),
viewportHeight = Dom.getViewportHeight();
return ((elementWidth + nViewportOffset < viewportWidth) && (elementHeight + nViewportOffset < viewportHeight));
},
/**
* The default event handler fired when the "fixedcenter" property
* is changed.
* @method configFixedCenter
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configFixedCenter: function (type, args, obj) {
var val = args[0],
alreadySubscribed = Config.alreadySubscribed,
windowResizeEvent = Overlay.windowResizeEvent,
windowScrollEvent = Overlay.windowScrollEvent;
if (val) {
this.center();
if (!alreadySubscribed(this.beforeShowEvent, this.center)) {
this.beforeShowEvent.subscribe(this.center);
}
if (!alreadySubscribed(windowResizeEvent, this.doCenterOnDOMEvent, this)) {
windowResizeEvent.subscribe(this.doCenterOnDOMEvent, this, true);
}
if (!alreadySubscribed(windowScrollEvent, this.doCenterOnDOMEvent, this)) {
windowScrollEvent.subscribe(this.doCenterOnDOMEvent, this, true);
}
} else {
this.beforeShowEvent.unsubscribe(this.center);
windowResizeEvent.unsubscribe(this.doCenterOnDOMEvent, this);
windowScrollEvent.unsubscribe(this.doCenterOnDOMEvent, this);
}
},
/**
* The default event handler fired when the "height" property is changed.
* @method configHeight
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configHeight: function (type, args, obj) {
var height = args[0],
el = this.element;
Dom.setStyle(el, "height", height);
this.cfg.refireEvent("iframe");
},
/**
* The default event handler fired when the "autofillheight" property is changed.
* @method configAutoFillHeight
*
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configAutoFillHeight: function (type, args, obj) {
var fillEl = args[0],
cfg = this.cfg,
autoFillHeight = "autofillheight",
height = "height",
currEl = cfg.getProperty(autoFillHeight),
autoFill = this._autoFillOnHeightChange;
cfg.unsubscribeFromConfigEvent(height, autoFill);
Module.textResizeEvent.unsubscribe(autoFill);
this.changeContentEvent.unsubscribe(autoFill);
if (currEl && fillEl !== currEl && this[currEl]) {
Dom.setStyle(this[currEl], height, "");
}
if (fillEl) {
fillEl = Lang.trim(fillEl.toLowerCase());
cfg.subscribeToConfigEvent(height, autoFill, this[fillEl], this);
Module.textResizeEvent.subscribe(autoFill, this[fillEl], this);
this.changeContentEvent.subscribe(autoFill, this[fillEl], this);
cfg.setProperty(autoFillHeight, fillEl, true);
}
},
/**
* The default event handler fired when the "width" property is changed.
* @method configWidth
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configWidth: function (type, args, obj) {
var width = args[0],
el = this.element;
Dom.setStyle(el, "width", width);
this.cfg.refireEvent("iframe");
},
/**
* The default event handler fired when the "zIndex" property is changed.
* @method configzIndex
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configzIndex: function (type, args, obj) {
var zIndex = args[0],
el = this.element;
if (! zIndex) {
zIndex = Dom.getStyle(el, "zIndex");
if (! zIndex || isNaN(zIndex)) {
zIndex = 0;
}
}
if (this.iframe || this.cfg.getProperty("iframe") === true) {
if (zIndex <= 0) {
zIndex = 1;
}
}
Dom.setStyle(el, "zIndex", zIndex);
this.cfg.setProperty("zIndex", zIndex, true);
if (this.iframe) {
this.stackIframe();
}
},
/**
* The default event handler fired when the "xy" property is changed.
* @method configXY
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configXY: function (type, args, obj) {
var pos = args[0],
x = pos[0],
y = pos[1];
this.cfg.setProperty("x", x);
this.cfg.setProperty("y", y);
this.beforeMoveEvent.fire([x, y]);
x = this.cfg.getProperty("x");
y = this.cfg.getProperty("y");
this.cfg.refireEvent("iframe");
this.moveEvent.fire([x, y]);
},
/**
* The default event handler fired when the "x" property is changed.
* @method configX
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configX: function (type, args, obj) {
var x = args[0],
y = this.cfg.getProperty("y");
this.cfg.setProperty("x", x, true);
this.cfg.setProperty("y", y, true);
this.beforeMoveEvent.fire([x, y]);
x = this.cfg.getProperty("x");
y = this.cfg.getProperty("y");
Dom.setX(this.element, x, true);
this.cfg.setProperty("xy", [x, y], true);
this.cfg.refireEvent("iframe");
this.moveEvent.fire([x, y]);
},
/**
* The default event handler fired when the "y" property is changed.
* @method configY
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configY: function (type, args, obj) {
var x = this.cfg.getProperty("x"),
y = args[0];
this.cfg.setProperty("x", x, true);
this.cfg.setProperty("y", y, true);
this.beforeMoveEvent.fire([x, y]);
x = this.cfg.getProperty("x");
y = this.cfg.getProperty("y");
Dom.setY(this.element, y, true);
this.cfg.setProperty("xy", [x, y], true);
this.cfg.refireEvent("iframe");
this.moveEvent.fire([x, y]);
},
/**
* Shows the iframe shim, if it has been enabled.
* @method showIframe
*/
showIframe: function () {
var oIFrame = this.iframe,
oParentNode;
if (oIFrame) {
oParentNode = this.element.parentNode;
if (oParentNode != oIFrame.parentNode) {
this._addToParent(oParentNode, oIFrame);
}
oIFrame.style.display = "block";
}
},
/**
* Hides the iframe shim, if it has been enabled.
* @method hideIframe
*/
hideIframe: function () {
if (this.iframe) {
this.iframe.style.display = "none";
}
},
/**
* Syncronizes the size and position of iframe shim to that of its
* corresponding Overlay instance.
* @method syncIframe
*/
syncIframe: function () {
var oIFrame = this.iframe,
oElement = this.element,
nOffset = Overlay.IFRAME_OFFSET,
nDimensionOffset = (nOffset * 2),
aXY;
if (oIFrame) {
// Size <iframe>
oIFrame.style.width = (oElement.offsetWidth + nDimensionOffset + "px");
oIFrame.style.height = (oElement.offsetHeight + nDimensionOffset + "px");
// Position <iframe>
aXY = this.cfg.getProperty("xy");
if (!Lang.isArray(aXY) || (isNaN(aXY[0]) || isNaN(aXY[1]))) {
this.syncPosition();
aXY = this.cfg.getProperty("xy");
}
Dom.setXY(oIFrame, [(aXY[0] - nOffset), (aXY[1] - nOffset)]);
}
},
/**
* Sets the zindex of the iframe shim, if it exists, based on the zindex of
* the Overlay element. The zindex of the iframe is set to be one less
* than the Overlay element's zindex.
*
* <p>NOTE: This method will not bump up the zindex of the Overlay element
* to ensure that the iframe shim has a non-negative zindex.
* If you require the iframe zindex to be 0 or higher, the zindex of
* the Overlay element should be set to a value greater than 0, before
* this method is called.
* </p>
* @method stackIframe
*/
stackIframe: function () {
if (this.iframe) {
var overlayZ = Dom.getStyle(this.element, "zIndex");
if (!YAHOO.lang.isUndefined(overlayZ) && !isNaN(overlayZ)) {
Dom.setStyle(this.iframe, "zIndex", (overlayZ - 1));
}
}
},
/**
* The default event handler fired when the "iframe" property is changed.
* @method configIframe
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configIframe: function (type, args, obj) {
var bIFrame = args[0];
function createIFrame() {
var oIFrame = this.iframe,
oElement = this.element,
oParent;
if (!oIFrame) {
if (!m_oIFrameTemplate) {
m_oIFrameTemplate = document.createElement("iframe");
if (this.isSecure) {
m_oIFrameTemplate.src = Overlay.IFRAME_SRC;
}
/*
Set the opacity of the <iframe> to 0 so that it
doesn't modify the opacity of any transparent
elements that may be on top of it (like a shadow).
*/
if (UA.ie) {
m_oIFrameTemplate.style.filter = "alpha(opacity=0)";
/*
Need to set the "frameBorder" property to 0
supress the default <iframe> border in IE.
Setting the CSS "border" property alone
doesn't supress it.
*/
m_oIFrameTemplate.frameBorder = 0;
}
else {
m_oIFrameTemplate.style.opacity = "0";
}
m_oIFrameTemplate.style.position = "absolute";
m_oIFrameTemplate.style.border = "none";
m_oIFrameTemplate.style.margin = "0";
m_oIFrameTemplate.style.padding = "0";
m_oIFrameTemplate.style.display = "none";
m_oIFrameTemplate.tabIndex = -1;
m_oIFrameTemplate.className = Overlay.CSS_IFRAME;
}
oIFrame = m_oIFrameTemplate.cloneNode(false);
oIFrame.id = this.id + "_f";
oParent = oElement.parentNode;
var parentNode = oParent || document.body;
this._addToParent(parentNode, oIFrame);
this.iframe = oIFrame;
}
/*
Show the <iframe> before positioning it since the "setXY"
method of DOM requires the element be in the document
and visible.
*/
this.showIframe();
/*
Syncronize the size and position of the <iframe> to that
of the Overlay.
*/
this.syncIframe();
this.stackIframe();
// Add event listeners to update the <iframe> when necessary
if (!this._hasIframeEventListeners) {
this.showEvent.subscribe(this.showIframe);
this.hideEvent.subscribe(this.hideIframe);
this.changeContentEvent.subscribe(this.syncIframe);
this._hasIframeEventListeners = true;
}
}
function onBeforeShow() {
createIFrame.call(this);
this.beforeShowEvent.unsubscribe(onBeforeShow);
this._iframeDeferred = false;
}
if (bIFrame) { // <iframe> shim is enabled
if (this.cfg.getProperty("visible")) {
createIFrame.call(this);
} else {
if (!this._iframeDeferred) {
this.beforeShowEvent.subscribe(onBeforeShow);
this._iframeDeferred = true;
}
}
} else { // <iframe> shim is disabled
this.hideIframe();
if (this._hasIframeEventListeners) {
this.showEvent.unsubscribe(this.showIframe);
this.hideEvent.unsubscribe(this.hideIframe);
this.changeContentEvent.unsubscribe(this.syncIframe);
this._hasIframeEventListeners = false;
}
}
},
/**
* Set's the container's XY value from DOM if not already set.
*
* Differs from syncPosition, in that the XY value is only sync'd with DOM if
* not already set. The method also refire's the XY config property event, so any
* beforeMove, Move event listeners are invoked.
*
* @method _primeXYFromDOM
* @protected
*/
_primeXYFromDOM : function() {
if (YAHOO.lang.isUndefined(this.cfg.getProperty("xy"))) {
// Set CFG XY based on DOM XY
this.syncPosition();
// Account for XY being set silently in syncPosition (no moveTo fired/called)
this.cfg.refireEvent("xy");
this.beforeShowEvent.unsubscribe(this._primeXYFromDOM);
}
},
/**
* The default event handler fired when the "constraintoviewport"
* property is changed.
* @method configConstrainToViewport
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for
* the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configConstrainToViewport: function (type, args, obj) {
var val = args[0];
if (val) {
if (! Config.alreadySubscribed(this.beforeMoveEvent, this.enforceConstraints, this)) {
this.beforeMoveEvent.subscribe(this.enforceConstraints, this, true);
}
if (! Config.alreadySubscribed(this.beforeShowEvent, this._primeXYFromDOM)) {
this.beforeShowEvent.subscribe(this._primeXYFromDOM);
}
} else {
this.beforeShowEvent.unsubscribe(this._primeXYFromDOM);
this.beforeMoveEvent.unsubscribe(this.enforceConstraints, this);
}
},
/**
* The default event handler fired when the "context" property
* is changed.
*
* @method configContext
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configContext: function (type, args, obj) {
var contextArgs = args[0],
contextEl,
elementMagnetCorner,
contextMagnetCorner,
triggers,
offset,
defTriggers = this.CONTEXT_TRIGGERS;
if (contextArgs) {
contextEl = contextArgs[0];
elementMagnetCorner = contextArgs[1];
contextMagnetCorner = contextArgs[2];
triggers = contextArgs[3];
offset = contextArgs[4];
if (defTriggers && defTriggers.length > 0) {
triggers = (triggers || []).concat(defTriggers);
}
if (contextEl) {
if (typeof contextEl == "string") {
this.cfg.setProperty("context", [
document.getElementById(contextEl),
elementMagnetCorner,
contextMagnetCorner,
triggers,
offset],
true);
}
if (elementMagnetCorner && contextMagnetCorner) {
this.align(elementMagnetCorner, contextMagnetCorner, offset);
}
if (this._contextTriggers) {
// Unsubscribe Old Set
this._processTriggers(this._contextTriggers, _UNSUBSCRIBE, this._alignOnTrigger);
}
if (triggers) {
// Subscribe New Set
this._processTriggers(triggers, _SUBSCRIBE, this._alignOnTrigger);
this._contextTriggers = triggers;
}
}
}
},
/**
* Custom Event handler for context alignment triggers. Invokes the align method
*
* @method _alignOnTrigger
* @protected
*
* @param {String} type The event type (not used by the default implementation)
* @param {Any[]} args The array of arguments for the trigger event (not used by the default implementation)
*/
_alignOnTrigger: function(type, args) {
this.align();
},
/**
* Helper method to locate the custom event instance for the event name string
* passed in. As a convenience measure, any custom events passed in are returned.
*
* @method _findTriggerCE
* @private
*
* @param {String|CustomEvent} t Either a CustomEvent, or event type (e.g. "windowScroll") for which a
* custom event instance needs to be looked up from the Overlay._TRIGGER_MAP.
*/
_findTriggerCE : function(t) {
var tce = null;
if (t instanceof CustomEvent) {
tce = t;
} else if (Overlay._TRIGGER_MAP[t]) {
tce = Overlay._TRIGGER_MAP[t];
}
return tce;
},
/**
* Utility method that subscribes or unsubscribes the given
* function from the list of trigger events provided.
*
* @method _processTriggers
* @protected
*
* @param {Array[String|CustomEvent]} triggers An array of either CustomEvents, event type strings
* (e.g. "beforeShow", "windowScroll") to/from which the provided function should be
* subscribed/unsubscribed respectively.
*
* @param {String} mode Either "subscribe" or "unsubscribe", specifying whether or not
* we are subscribing or unsubscribing trigger listeners
*
* @param {Function} fn The function to be subscribed/unsubscribed to/from the trigger event.
* Context is always set to the overlay instance, and no additional object argument
* get passed to the subscribed function.
*/
_processTriggers : function(triggers, mode, fn) {
var t, tce;
for (var i = 0, l = triggers.length; i < l; ++i) {
t = triggers[i];
tce = this._findTriggerCE(t);
if (tce) {
tce[mode](fn, this, true);
} else {
this[mode](t, fn);
}
}
},
// END BUILT-IN PROPERTY EVENT HANDLERS //
/**
* Aligns the Overlay to its context element using the specified corner
* points (represented by the constants TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT,
* and BOTTOM_RIGHT.
* @method align
* @param {String} elementAlign The String representing the corner of
* the Overlay that should be aligned to the context element
* @param {String} contextAlign The corner of the context element
* that the elementAlign corner should stick to.
* @param {Number[]} xyOffset Optional. A 2 element array specifying the x and y pixel offsets which should be applied
* after aligning the element and context corners. For example, passing in [5, -10] for this value, would offset the
* Overlay by 5 pixels along the X axis (horizontally) and -10 pixels along the Y axis (vertically) after aligning the specified corners.
*/
align: function (elementAlign, contextAlign, xyOffset) {
var contextArgs = this.cfg.getProperty("context"),
me = this,
context,
element,
contextRegion;
function doAlign(v, h) {
var alignX = null, alignY = null;
switch (elementAlign) {
case Overlay.TOP_LEFT:
alignX = h;
alignY = v;
break;
case Overlay.TOP_RIGHT:
alignX = h - element.offsetWidth;
alignY = v;
break;
case Overlay.BOTTOM_LEFT:
alignX = h;
alignY = v - element.offsetHeight;
break;
case Overlay.BOTTOM_RIGHT:
alignX = h - element.offsetWidth;
alignY = v - element.offsetHeight;
break;
}
if (alignX !== null && alignY !== null) {
if (xyOffset) {
alignX += xyOffset[0];
alignY += xyOffset[1];
}
me.moveTo(alignX, alignY);
}
}
if (contextArgs) {
context = contextArgs[0];
element = this.element;
me = this;
if (! elementAlign) {
elementAlign = contextArgs[1];
}
if (! contextAlign) {
contextAlign = contextArgs[2];
}
if (!xyOffset && contextArgs[4]) {
xyOffset = contextArgs[4];
}
if (element && context) {
contextRegion = Dom.getRegion(context);
switch (contextAlign) {
case Overlay.TOP_LEFT:
doAlign(contextRegion.top, contextRegion.left);
break;
case Overlay.TOP_RIGHT:
doAlign(contextRegion.top, contextRegion.right);
break;
case Overlay.BOTTOM_LEFT:
doAlign(contextRegion.bottom, contextRegion.left);
break;
case Overlay.BOTTOM_RIGHT:
doAlign(contextRegion.bottom, contextRegion.right);
break;
}
}
}
},
/**
* The default event handler executed when the moveEvent is fired, if the
* "constraintoviewport" is set to true.
* @method enforceConstraints
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
enforceConstraints: function (type, args, obj) {
var pos = args[0];
var cXY = this.getConstrainedXY(pos[0], pos[1]);
this.cfg.setProperty("x", cXY[0], true);
this.cfg.setProperty("y", cXY[1], true);
this.cfg.setProperty("xy", cXY, true);
},
/**
* Shared implementation method for getConstrainedX and getConstrainedY.
*
* <p>
* Given a coordinate value, returns the calculated coordinate required to
* position the Overlay if it is to be constrained to the viewport, based on the
* current element size, viewport dimensions, scroll values and preventoverlap
* settings
* </p>
*
* @method _getConstrainedPos
* @protected
* @param {String} pos The coordinate which needs to be constrained, either "x" or "y"
* @param {Number} The coordinate value which needs to be constrained
* @return {Number} The constrained coordinate value
*/
_getConstrainedPos: function(pos, val) {
var overlayEl = this.element,
buffer = Overlay.VIEWPORT_OFFSET,
x = (pos == "x"),
overlaySize = (x) ? overlayEl.offsetWidth : overlayEl.offsetHeight,
viewportSize = (x) ? Dom.getViewportWidth() : Dom.getViewportHeight(),
docScroll = (x) ? Dom.getDocumentScrollLeft() : Dom.getDocumentScrollTop(),
overlapPositions = (x) ? Overlay.PREVENT_OVERLAP_X : Overlay.PREVENT_OVERLAP_Y,
context = this.cfg.getProperty("context"),
bOverlayFitsInViewport = (overlaySize + buffer < viewportSize),
bPreventContextOverlap = this.cfg.getProperty("preventcontextoverlap") && context && overlapPositions[(context[1] + context[2])],
minConstraint = docScroll + buffer,
maxConstraint = docScroll + viewportSize - overlaySize - buffer,
constrainedVal = val;
if (val < minConstraint || val > maxConstraint) {
if (bPreventContextOverlap) {
constrainedVal = this._preventOverlap(pos, context[0], overlaySize, viewportSize, docScroll);
} else {
if (bOverlayFitsInViewport) {
if (val < minConstraint) {
constrainedVal = minConstraint;
} else if (val > maxConstraint) {
constrainedVal = maxConstraint;
}
} else {
constrainedVal = minConstraint;
}
}
}
return constrainedVal;
},
/**
* Helper method, used to position the Overlap to prevent overlap with the
* context element (used when preventcontextoverlap is enabled)
*
* @method _preventOverlap
* @protected
* @param {String} pos The coordinate to prevent overlap for, either "x" or "y".
* @param {HTMLElement} contextEl The context element
* @param {Number} overlaySize The related overlay dimension value (for "x", the width, for "y", the height)
* @param {Number} viewportSize The related viewport dimension value (for "x", the width, for "y", the height)
* @param {Object} docScroll The related document scroll value (for "x", the scrollLeft, for "y", the scrollTop)
*
* @return {Number} The new coordinate value which was set to prevent overlap
*/
_preventOverlap : function(pos, contextEl, overlaySize, viewportSize, docScroll) {
var x = (pos == "x"),
buffer = Overlay.VIEWPORT_OFFSET,
overlay = this,
contextElPos = ((x) ? Dom.getX(contextEl) : Dom.getY(contextEl)) - docScroll,
contextElSize = (x) ? contextEl.offsetWidth : contextEl.offsetHeight,
minRegionSize = contextElPos - buffer,
maxRegionSize = (viewportSize - (contextElPos + contextElSize)) - buffer,
bFlipped = false,
flip = function () {
var flippedVal;
if ((overlay.cfg.getProperty(pos) - docScroll) > contextElPos) {
flippedVal = (contextElPos - overlaySize);
} else {
flippedVal = (contextElPos + contextElSize);
}
overlay.cfg.setProperty(pos, (flippedVal + docScroll), true);
return flippedVal;
},
setPosition = function () {
var displayRegionSize = ((overlay.cfg.getProperty(pos) - docScroll) > contextElPos) ? maxRegionSize : minRegionSize,
position;
if (overlaySize > displayRegionSize) {
if (bFlipped) {
/*
All possible positions and values have been
tried, but none were successful, so fall back
to the original size and position.
*/
flip();
} else {
flip();
bFlipped = true;
position = setPosition();
}
}
return position;
};
setPosition();
return this.cfg.getProperty(pos);
},
/**
* Given x coordinate value, returns the calculated x coordinate required to
* position the Overlay if it is to be constrained to the viewport, based on the
* current element size, viewport dimensions and scroll values.
*
* @param {Number} x The X coordinate value to be constrained
* @return {Number} The constrained x coordinate
*/
getConstrainedX: function (x) {
return this._getConstrainedPos("x", x);
},
/**
* Given y coordinate value, returns the calculated y coordinate required to
* position the Overlay if it is to be constrained to the viewport, based on the
* current element size, viewport dimensions and scroll values.
*
* @param {Number} y The Y coordinate value to be constrained
* @return {Number} The constrained y coordinate
*/
getConstrainedY : function (y) {
return this._getConstrainedPos("y", y);
},
/**
* Given x, y coordinate values, returns the calculated coordinates required to
* position the Overlay if it is to be constrained to the viewport, based on the
* current element size, viewport dimensions and scroll values.
*
* @param {Number} x The X coordinate value to be constrained
* @param {Number} y The Y coordinate value to be constrained
* @return {Array} The constrained x and y coordinates at index 0 and 1 respectively;
*/
getConstrainedXY: function(x, y) {
return [this.getConstrainedX(x), this.getConstrainedY(y)];
},
/**
* Centers the container in the viewport.
* @method center
*/
center: function () {
var nViewportOffset = Overlay.VIEWPORT_OFFSET,
elementWidth = this.element.offsetWidth,
elementHeight = this.element.offsetHeight,
viewPortWidth = Dom.getViewportWidth(),
viewPortHeight = Dom.getViewportHeight(),
x,
y;
if (elementWidth < viewPortWidth) {
x = (viewPortWidth / 2) - (elementWidth / 2) + Dom.getDocumentScrollLeft();
} else {
x = nViewportOffset + Dom.getDocumentScrollLeft();
}
if (elementHeight < viewPortHeight) {
y = (viewPortHeight / 2) - (elementHeight / 2) + Dom.getDocumentScrollTop();
} else {
y = nViewportOffset + Dom.getDocumentScrollTop();
}
this.cfg.setProperty("xy", [parseInt(x, 10), parseInt(y, 10)]);
this.cfg.refireEvent("iframe");
if (UA.webkit) {
this.forceContainerRedraw();
}
},
/**
* Synchronizes the Panel's "xy", "x", and "y" properties with the
* Panel's position in the DOM. This is primarily used to update
* position information during drag & drop.
* @method syncPosition
*/
syncPosition: function () {
var pos = Dom.getXY(this.element);
this.cfg.setProperty("x", pos[0], true);
this.cfg.setProperty("y", pos[1], true);
this.cfg.setProperty("xy", pos, true);
},
/**
* Event handler fired when the resize monitor element is resized.
* @method onDomResize
* @param {DOMEvent} e The resize DOM event
* @param {Object} obj The scope object
*/
onDomResize: function (e, obj) {
var me = this;
Overlay.superclass.onDomResize.call(this, e, obj);
setTimeout(function () {
me.syncPosition();
me.cfg.refireEvent("iframe");
me.cfg.refireEvent("context");
}, 0);
},
/**
* Determines the content box height of the given element (height of the element, without padding or borders) in pixels.
*
* @method _getComputedHeight
* @private
* @param {HTMLElement} el The element for which the content height needs to be determined
* @return {Number} The content box height of the given element, or null if it could not be determined.
*/
_getComputedHeight : (function() {
if (document.defaultView && document.defaultView.getComputedStyle) {
return function(el) {
var height = null;
if (el.ownerDocument && el.ownerDocument.defaultView) {
var computed = el.ownerDocument.defaultView.getComputedStyle(el, '');
if (computed) {
height = parseInt(computed.height, 10);
}
}
return (Lang.isNumber(height)) ? height : null;
};
} else {
return function(el) {
var height = null;
if (el.style.pixelHeight) {
height = el.style.pixelHeight;
}
return (Lang.isNumber(height)) ? height : null;
};
}
})(),
/**
* autofillheight validator. Verifies that the autofill value is either null
* or one of the strings : "body", "header" or "footer".
*
* @method _validateAutoFillHeight
* @protected
* @param {String} val
* @return true, if valid, false otherwise
*/
_validateAutoFillHeight : function(val) {
return (!val) || (Lang.isString(val) && Overlay.STD_MOD_RE.test(val));
},
/**
* The default custom event handler executed when the overlay's height is changed,
* if the autofillheight property has been set.
*
* @method _autoFillOnHeightChange
* @protected
* @param {String} type The event type
* @param {Array} args The array of arguments passed to event subscribers
* @param {HTMLElement} el The header, body or footer element which is to be resized to fill
* out the containers height
*/
_autoFillOnHeightChange : function(type, args, el) {
var height = this.cfg.getProperty("height");
if ((height && height !== "auto") || (height === 0)) {
this.fillHeight(el);
}
},
/**
* Returns the sub-pixel height of the el, using getBoundingClientRect, if available,
* otherwise returns the offsetHeight
* @method _getPreciseHeight
* @private
* @param {HTMLElement} el
* @return {Float} The sub-pixel height if supported by the browser, else the rounded height.
*/
_getPreciseHeight : function(el) {
var height = el.offsetHeight;
if (el.getBoundingClientRect) {
var rect = el.getBoundingClientRect();
height = rect.bottom - rect.top;
}
return height;
},
/**
* <p>
* Sets the height on the provided header, body or footer element to
* fill out the height of the container. It determines the height of the
* containers content box, based on it's configured height value, and
* sets the height of the autofillheight element to fill out any
* space remaining after the other standard module element heights
* have been accounted for.
* </p>
* <p><strong>NOTE:</strong> This method is not designed to work if an explicit
* height has not been set on the container, since for an "auto" height container,
* the heights of the header/body/footer will drive the height of the container.</p>
*
* @method fillHeight
* @param {HTMLElement} el The element which should be resized to fill out the height
* of the container element.
*/
fillHeight : function(el) {
if (el) {
var container = this.innerElement || this.element,
containerEls = [this.header, this.body, this.footer],
containerEl,
total = 0,
filled = 0,
remaining = 0,
validEl = false;
for (var i = 0, l = containerEls.length; i < l; i++) {
containerEl = containerEls[i];
if (containerEl) {
if (el !== containerEl) {
filled += this._getPreciseHeight(containerEl);
} else {
validEl = true;
}
}
}
if (validEl) {
if (UA.ie || UA.opera) {
// Need to set height to 0, to allow height to be reduced
Dom.setStyle(el, 'height', 0 + 'px');
}
total = this._getComputedHeight(container);
// Fallback, if we can't get computed value for content height
if (total === null) {
Dom.addClass(container, "yui-override-padding");
total = container.clientHeight; // Content, No Border, 0 Padding (set by yui-override-padding)
Dom.removeClass(container, "yui-override-padding");
}
remaining = Math.max(total - filled, 0);
Dom.setStyle(el, "height", remaining + "px");
// Re-adjust height if required, to account for el padding and border
if (el.offsetHeight != remaining) {
remaining = Math.max(remaining - (el.offsetHeight - remaining), 0);
}
Dom.setStyle(el, "height", remaining + "px");
}
}
},
/**
* Places the Overlay on top of all other instances of
* YAHOO.widget.Overlay.
* @method bringToTop
*/
bringToTop: function () {
var aOverlays = [],
oElement = this.element;
function compareZIndexDesc(p_oOverlay1, p_oOverlay2) {
var sZIndex1 = Dom.getStyle(p_oOverlay1, "zIndex"),
sZIndex2 = Dom.getStyle(p_oOverlay2, "zIndex"),
nZIndex1 = (!sZIndex1 || isNaN(sZIndex1)) ? 0 : parseInt(sZIndex1, 10),
nZIndex2 = (!sZIndex2 || isNaN(sZIndex2)) ? 0 : parseInt(sZIndex2, 10);
if (nZIndex1 > nZIndex2) {
return -1;
} else if (nZIndex1 < nZIndex2) {
return 1;
} else {
return 0;
}
}
function isOverlayElement(p_oElement) {
var isOverlay = Dom.hasClass(p_oElement, Overlay.CSS_OVERLAY),
Panel = YAHOO.widget.Panel;
if (isOverlay && !Dom.isAncestor(oElement, p_oElement)) {
if (Panel && Dom.hasClass(p_oElement, Panel.CSS_PANEL)) {
aOverlays[aOverlays.length] = p_oElement.parentNode;
} else {
aOverlays[aOverlays.length] = p_oElement;
}
}
}
Dom.getElementsBy(isOverlayElement, "div", document.body);
aOverlays.sort(compareZIndexDesc);
var oTopOverlay = aOverlays[0],
nTopZIndex;
if (oTopOverlay) {
nTopZIndex = Dom.getStyle(oTopOverlay, "zIndex");
if (!isNaN(nTopZIndex)) {
var bRequiresBump = false;
if (oTopOverlay != oElement) {
bRequiresBump = true;
} else if (aOverlays.length > 1) {
var nNextZIndex = Dom.getStyle(aOverlays[1], "zIndex");
// Don't rely on DOM order to stack if 2 overlays are at the same zindex.
if (!isNaN(nNextZIndex) && (nTopZIndex == nNextZIndex)) {
bRequiresBump = true;
}
}
if (bRequiresBump) {
this.cfg.setProperty("zindex", (parseInt(nTopZIndex, 10) + 2));
}
}
}
},
/**
* Removes the Overlay element from the DOM and sets all child
* elements to null.
* @method destroy
* @param {boolean} shallowPurge If true, only the parent element's DOM event listeners are purged. If false, or not provided, all children are also purged of DOM event listeners.
* NOTE: The flag is a "shallowPurge" flag, as opposed to what may be a more intuitive "purgeChildren" flag to maintain backwards compatibility with behavior prior to 2.9.0.
*/
destroy: function (shallowPurge) {
if (this.iframe) {
this.iframe.parentNode.removeChild(this.iframe);
}
this.iframe = null;
Overlay.windowResizeEvent.unsubscribe(
this.doCenterOnDOMEvent, this);
Overlay.windowScrollEvent.unsubscribe(
this.doCenterOnDOMEvent, this);
Module.textResizeEvent.unsubscribe(this._autoFillOnHeightChange);
if (this._contextTriggers) {
// Unsubscribe context triggers - to cover context triggers which listen for global
// events such as windowResize and windowScroll. Easier just to unsubscribe all
this._processTriggers(this._contextTriggers, _UNSUBSCRIBE, this._alignOnTrigger);
}
Overlay.superclass.destroy.call(this, shallowPurge);
},
/**
* Can be used to force the container to repaint/redraw it's contents.
* <p>
* By default applies and then removes a 1px bottom margin through the
* application/removal of a "yui-force-redraw" class.
* </p>
* <p>
* It is currently used by Overlay to force a repaint for webkit
* browsers, when centering.
* </p>
* @method forceContainerRedraw
*/
forceContainerRedraw : function() {
var c = this;
Dom.addClass(c.element, "yui-force-redraw");
setTimeout(function() {
Dom.removeClass(c.element, "yui-force-redraw");
}, 0);
},
/**
* Returns a String representation of the object.
* @method toString
* @return {String} The string representation of the Overlay.
*/
toString: function () {
return "Overlay " + this.id;
}
});
}());
(function () {
/**
* OverlayManager is used for maintaining the focus status of
* multiple Overlays.
* @namespace YAHOO.widget
* @namespace YAHOO.widget
* @class OverlayManager
* @constructor
* @param {Array} overlays Optional. A collection of Overlays to register
* with the manager.
* @param {Object} userConfig The object literal representing the user
* configuration of the OverlayManager
*/
YAHOO.widget.OverlayManager = function (userConfig) {
this.init(userConfig);
};
var Overlay = YAHOO.widget.Overlay,
Event = YAHOO.util.Event,
Dom = YAHOO.util.Dom,
Config = YAHOO.util.Config,
CustomEvent = YAHOO.util.CustomEvent,
OverlayManager = YAHOO.widget.OverlayManager;
/**
* The CSS class representing a focused Overlay
* @property OverlayManager.CSS_FOCUSED
* @static
* @final
* @type String
*/
OverlayManager.CSS_FOCUSED = "focused";
OverlayManager.prototype = {
/**
* The class's constructor function
* @property contructor
* @type Function
*/
constructor: OverlayManager,
/**
* The array of Overlays that are currently registered
* @property overlays
* @type YAHOO.widget.Overlay[]
*/
overlays: null,
/**
* Initializes the default configuration of the OverlayManager
* @method initDefaultConfig
*/
initDefaultConfig: function () {
/**
* The collection of registered Overlays in use by
* the OverlayManager
* @config overlays
* @type YAHOO.widget.Overlay[]
* @default null
*/
this.cfg.addProperty("overlays", { suppressEvent: true } );
/**
* The default DOM event that should be used to focus an Overlay
* @config focusevent
* @type String
* @default "mousedown"
*/
this.cfg.addProperty("focusevent", { value: "mousedown" } );
},
/**
* Initializes the OverlayManager
* @method init
* @param {Overlay[]} overlays Optional. A collection of Overlays to
* register with the manager.
* @param {Object} userConfig The object literal representing the user
* configuration of the OverlayManager
*/
init: function (userConfig) {
/**
* The OverlayManager's Config object used for monitoring
* configuration properties.
* @property cfg
* @type Config
*/
this.cfg = new Config(this);
this.initDefaultConfig();
if (userConfig) {
this.cfg.applyConfig(userConfig, true);
}
this.cfg.fireQueue();
/**
* The currently activated Overlay
* @property activeOverlay
* @private
* @type YAHOO.widget.Overlay
*/
var activeOverlay = null;
/**
* Returns the currently focused Overlay
* @method getActive
* @return {Overlay} The currently focused Overlay
*/
this.getActive = function () {
return activeOverlay;
};
/**
* Focuses the specified Overlay
* @method focus
* @param {Overlay} overlay The Overlay to focus
* @param {String} overlay The id of the Overlay to focus
*/
this.focus = function (overlay) {
var o = this.find(overlay);
if (o) {
o.focus();
}
};
/**
* Removes the specified Overlay from the manager
* @method remove
* @param {Overlay} overlay The Overlay to remove
* @param {String} overlay The id of the Overlay to remove
*/
this.remove = function (overlay) {
var o = this.find(overlay),
originalZ;
if (o) {
if (activeOverlay == o) {
activeOverlay = null;
}
var bDestroyed = (o.element === null && o.cfg === null) ? true : false;
if (!bDestroyed) {
// Set it's zindex so that it's sorted to the end.
originalZ = Dom.getStyle(o.element, "zIndex");
o.cfg.setProperty("zIndex", -1000, true);
}
this.overlays.sort(this.compareZIndexDesc);
this.overlays = this.overlays.slice(0, (this.overlays.length - 1));
o.hideEvent.unsubscribe(o.blur);
o.destroyEvent.unsubscribe(this._onOverlayDestroy, o);
o.focusEvent.unsubscribe(this._onOverlayFocusHandler, o);
o.blurEvent.unsubscribe(this._onOverlayBlurHandler, o);
if (!bDestroyed) {
Event.removeListener(o.element, this.cfg.getProperty("focusevent"), this._onOverlayElementFocus);
o.cfg.setProperty("zIndex", originalZ, true);
o.cfg.setProperty("manager", null);
}
/* _managed Flag for custom or existing. Don't want to remove existing */
if (o.focusEvent._managed) { o.focusEvent = null; }
if (o.blurEvent._managed) { o.blurEvent = null; }
if (o.focus._managed) { o.focus = null; }
if (o.blur._managed) { o.blur = null; }
}
};
/**
* Removes focus from all registered Overlays in the manager
* @method blurAll
*/
this.blurAll = function () {
var nOverlays = this.overlays.length,
i;
if (nOverlays > 0) {
i = nOverlays - 1;
do {
this.overlays[i].blur();
}
while(i--);
}
};
/**
* Updates the state of the OverlayManager and overlay, as a result of the overlay
* being blurred.
*
* @method _manageBlur
* @param {Overlay} overlay The overlay instance which got blurred.
* @protected
*/
this._manageBlur = function (overlay) {
var changed = false;
if (activeOverlay == overlay) {
Dom.removeClass(activeOverlay.element, OverlayManager.CSS_FOCUSED);
activeOverlay = null;
changed = true;
}
return changed;
};
/**
* Updates the state of the OverlayManager and overlay, as a result of the overlay
* receiving focus.
*
* @method _manageFocus
* @param {Overlay} overlay The overlay instance which got focus.
* @protected
*/
this._manageFocus = function(overlay) {
var changed = false;
if (activeOverlay != overlay) {
if (activeOverlay) {
activeOverlay.blur();
}
activeOverlay = overlay;
this.bringToTop(activeOverlay);
Dom.addClass(activeOverlay.element, OverlayManager.CSS_FOCUSED);
changed = true;
}
return changed;
};
var overlays = this.cfg.getProperty("overlays");
if (! this.overlays) {
this.overlays = [];
}
if (overlays) {
this.register(overlays);
this.overlays.sort(this.compareZIndexDesc);
}
},
/**
* @method _onOverlayElementFocus
* @description Event handler for the DOM event that is used to focus
* the Overlay instance as specified by the "focusevent"
* configuration property.
* @private
* @param {Event} p_oEvent Object representing the DOM event
* object passed back by the event utility (Event).
*/
_onOverlayElementFocus: function (p_oEvent) {
var oTarget = Event.getTarget(p_oEvent),
oClose = this.close;
if (oClose && (oTarget == oClose || Dom.isAncestor(oClose, oTarget))) {
this.blur();
} else {
this.focus();
}
},
/**
* @method _onOverlayDestroy
* @description "destroy" event handler for the Overlay.
* @private
* @param {String} p_sType String representing the name of the event
* that was fired.
* @param {Array} p_aArgs Array of arguments sent when the event
* was fired.
* @param {Overlay} p_oOverlay Object representing the overlay that
* fired the event.
*/
_onOverlayDestroy: function (p_sType, p_aArgs, p_oOverlay) {
this.remove(p_oOverlay);
},
/**
* @method _onOverlayFocusHandler
*
* @description focusEvent Handler, used to delegate to _manageFocus with the correct arguments.
*
* @private
* @param {String} p_sType String representing the name of the event
* that was fired.
* @param {Array} p_aArgs Array of arguments sent when the event
* was fired.
* @param {Overlay} p_oOverlay Object representing the overlay that
* fired the event.
*/
_onOverlayFocusHandler: function(p_sType, p_aArgs, p_oOverlay) {
this._manageFocus(p_oOverlay);
},
/**
* @method _onOverlayBlurHandler
* @description blurEvent Handler, used to delegate to _manageBlur with the correct arguments.
*
* @private
* @param {String} p_sType String representing the name of the event
* that was fired.
* @param {Array} p_aArgs Array of arguments sent when the event
* was fired.
* @param {Overlay} p_oOverlay Object representing the overlay that
* fired the event.
*/
_onOverlayBlurHandler: function(p_sType, p_aArgs, p_oOverlay) {
this._manageBlur(p_oOverlay);
},
/**
* Subscribes to the Overlay based instance focusEvent, to allow the OverlayManager to
* monitor focus state.
*
* If the instance already has a focusEvent (e.g. Menu), OverlayManager will subscribe
* to the existing focusEvent, however if a focusEvent or focus method does not exist
* on the instance, the _bindFocus method will add them, and the focus method will
* update the OverlayManager's state directly.
*
* @method _bindFocus
* @param {Overlay} overlay The overlay for which focus needs to be managed
* @protected
*/
_bindFocus : function(overlay) {
var mgr = this;
if (!overlay.focusEvent) {
overlay.focusEvent = overlay.createEvent("focus");
overlay.focusEvent.signature = CustomEvent.LIST;
overlay.focusEvent._managed = true;
} else {
overlay.focusEvent.subscribe(mgr._onOverlayFocusHandler, overlay, mgr);
}
if (!overlay.focus) {
Event.on(overlay.element, mgr.cfg.getProperty("focusevent"), mgr._onOverlayElementFocus, null, overlay);
overlay.focus = function () {
if (mgr._manageFocus(this)) {
// For Panel/Dialog
if (this.cfg.getProperty("visible") && this.focusFirst) {
this.focusFirst();
}
this.focusEvent.fire();
}
};
overlay.focus._managed = true;
}
},
/**
* Subscribes to the Overlay based instance's blurEvent to allow the OverlayManager to
* monitor blur state.
*
* If the instance already has a blurEvent (e.g. Menu), OverlayManager will subscribe
* to the existing blurEvent, however if a blurEvent or blur method does not exist
* on the instance, the _bindBlur method will add them, and the blur method
* update the OverlayManager's state directly.
*
* @method _bindBlur
* @param {Overlay} overlay The overlay for which blur needs to be managed
* @protected
*/
_bindBlur : function(overlay) {
var mgr = this;
if (!overlay.blurEvent) {
overlay.blurEvent = overlay.createEvent("blur");
overlay.blurEvent.signature = CustomEvent.LIST;
overlay.focusEvent._managed = true;
} else {
overlay.blurEvent.subscribe(mgr._onOverlayBlurHandler, overlay, mgr);
}
if (!overlay.blur) {
overlay.blur = function () {
if (mgr._manageBlur(this)) {
this.blurEvent.fire();
}
};
overlay.blur._managed = true;
}
overlay.hideEvent.subscribe(overlay.blur);
},
/**
* Subscribes to the Overlay based instance's destroyEvent, to allow the Overlay
* to be removed for the OverlayManager when destroyed.
*
* @method _bindDestroy
* @param {Overlay} overlay The overlay instance being managed
* @protected
*/
_bindDestroy : function(overlay) {
var mgr = this;
overlay.destroyEvent.subscribe(mgr._onOverlayDestroy, overlay, mgr);
},
/**
* Ensures the zIndex configuration property on the managed overlay based instance
* is set to the computed zIndex value from the DOM (with "auto" translating to 0).
*
* @method _syncZIndex
* @param {Overlay} overlay The overlay instance being managed
* @protected
*/
_syncZIndex : function(overlay) {
var zIndex = Dom.getStyle(overlay.element, "zIndex");
if (!isNaN(zIndex)) {
overlay.cfg.setProperty("zIndex", parseInt(zIndex, 10));
} else {
overlay.cfg.setProperty("zIndex", 0);
}
},
/**
* Registers an Overlay or an array of Overlays with the manager. Upon
* registration, the Overlay receives functions for focus and blur,
* along with CustomEvents for each.
*
* @method register
* @param {Overlay} overlay An Overlay to register with the manager.
* @param {Overlay[]} overlay An array of Overlays to register with
* the manager.
* @return {boolean} true if any Overlays are registered.
*/
register: function (overlay) {
var registered = false,
i,
n;
if (overlay instanceof Overlay) {
overlay.cfg.addProperty("manager", { value: this } );
this._bindFocus(overlay);
this._bindBlur(overlay);
this._bindDestroy(overlay);
this._syncZIndex(overlay);
this.overlays.push(overlay);
this.bringToTop(overlay);
registered = true;
} else if (overlay instanceof Array) {
for (i = 0, n = overlay.length; i < n; i++) {
registered = this.register(overlay[i]) || registered;
}
}
return registered;
},
/**
* Places the specified Overlay instance on top of all other
* Overlay instances.
* @method bringToTop
* @param {YAHOO.widget.Overlay} p_oOverlay Object representing an
* Overlay instance.
* @param {String} p_oOverlay String representing the id of an
* Overlay instance.
*/
bringToTop: function (p_oOverlay) {
var oOverlay = this.find(p_oOverlay),
nTopZIndex,
oTopOverlay,
aOverlays;
if (oOverlay) {
aOverlays = this.overlays;
aOverlays.sort(this.compareZIndexDesc);
oTopOverlay = aOverlays[0];
if (oTopOverlay) {
nTopZIndex = Dom.getStyle(oTopOverlay.element, "zIndex");
if (!isNaN(nTopZIndex)) {
var bRequiresBump = false;
if (oTopOverlay !== oOverlay) {
bRequiresBump = true;
} else if (aOverlays.length > 1) {
var nNextZIndex = Dom.getStyle(aOverlays[1].element, "zIndex");
// Don't rely on DOM order to stack if 2 overlays are at the same zindex.
if (!isNaN(nNextZIndex) && (nTopZIndex == nNextZIndex)) {
bRequiresBump = true;
}
}
if (bRequiresBump) {
oOverlay.cfg.setProperty("zindex", (parseInt(nTopZIndex, 10) + 2));
}
}
aOverlays.sort(this.compareZIndexDesc);
}
}
},
/**
* Attempts to locate an Overlay by instance or ID.
* @method find
* @param {Overlay} overlay An Overlay to locate within the manager
* @param {String} overlay An Overlay id to locate within the manager
* @return {Overlay} The requested Overlay, if found, or null if it
* cannot be located.
*/
find: function (overlay) {
var isInstance = overlay instanceof Overlay,
overlays = this.overlays,
n = overlays.length,
found = null,
o,
i;
if (isInstance || typeof overlay == "string") {
for (i = n-1; i >= 0; i--) {
o = overlays[i];
if ((isInstance && (o === overlay)) || (o.id == overlay)) {
found = o;
break;
}
}
}
return found;
},
/**
* Used for sorting the manager's Overlays by z-index.
* @method compareZIndexDesc
* @private
* @return {Number} 0, 1, or -1, depending on where the Overlay should
* fall in the stacking order.
*/
compareZIndexDesc: function (o1, o2) {
var zIndex1 = (o1.cfg) ? o1.cfg.getProperty("zIndex") : null, // Sort invalid (destroyed)
zIndex2 = (o2.cfg) ? o2.cfg.getProperty("zIndex") : null; // objects at bottom.
if (zIndex1 === null && zIndex2 === null) {
return 0;
} else if (zIndex1 === null){
return 1;
} else if (zIndex2 === null) {
return -1;
} else if (zIndex1 > zIndex2) {
return -1;
} else if (zIndex1 < zIndex2) {
return 1;
} else {
return 0;
}
},
/**
* Shows all Overlays in the manager.
* @method showAll
*/
showAll: function () {
var overlays = this.overlays,
n = overlays.length,
i;
for (i = n - 1; i >= 0; i--) {
overlays[i].show();
}
},
/**
* Hides all Overlays in the manager.
* @method hideAll
*/
hideAll: function () {
var overlays = this.overlays,
n = overlays.length,
i;
for (i = n - 1; i >= 0; i--) {
overlays[i].hide();
}
},
/**
* Returns a string representation of the object.
* @method toString
* @return {String} The string representation of the OverlayManager
*/
toString: function () {
return "OverlayManager";
}
};
}());
(function () {
/**
* Tooltip is an implementation of Overlay that behaves like an OS tooltip,
* displaying when the user mouses over a particular element, and
* disappearing on mouse out.
* @namespace YAHOO.widget
* @class Tooltip
* @extends YAHOO.widget.Overlay
* @constructor
* @param {String} el The element ID representing the Tooltip <em>OR</em>
* @param {HTMLElement} el The element representing the Tooltip
* @param {Object} userConfig The configuration object literal containing
* the configuration that should be set for this Overlay. See configuration
* documentation for more details.
*/
YAHOO.widget.Tooltip = function (el, userConfig) {
YAHOO.widget.Tooltip.superclass.constructor.call(this, el, userConfig);
};
var Lang = YAHOO.lang,
Event = YAHOO.util.Event,
CustomEvent = YAHOO.util.CustomEvent,
Dom = YAHOO.util.Dom,
Tooltip = YAHOO.widget.Tooltip,
UA = YAHOO.env.ua,
bIEQuirks = (UA.ie && (UA.ie <= 6 || document.compatMode == "BackCompat")),
m_oShadowTemplate,
/**
* Constant representing the Tooltip's configuration properties
* @property DEFAULT_CONFIG
* @private
* @final
* @type Object
*/
DEFAULT_CONFIG = {
"PREVENT_OVERLAP": {
key: "preventoverlap",
value: true,
validator: Lang.isBoolean,
supercedes: ["x", "y", "xy"]
},
"SHOW_DELAY": {
key: "showdelay",
value: 200,
validator: Lang.isNumber
},
"AUTO_DISMISS_DELAY": {
key: "autodismissdelay",
value: 5000,
validator: Lang.isNumber
},
"HIDE_DELAY": {
key: "hidedelay",
value: 250,
validator: Lang.isNumber
},
"TEXT": {
key: "text",
suppressEvent: true
},
"CONTAINER": {
key: "container"
},
"DISABLED": {
key: "disabled",
value: false,
suppressEvent: true
},
"XY_OFFSET": {
key: "xyoffset",
value: [0, 25],
suppressEvent: true
}
},
/**
* Constant representing the name of the Tooltip's events
* @property EVENT_TYPES
* @private
* @final
* @type Object
*/
EVENT_TYPES = {
"CONTEXT_MOUSE_OVER": "contextMouseOver",
"CONTEXT_MOUSE_OUT": "contextMouseOut",
"CONTEXT_TRIGGER": "contextTrigger"
};
/**
* Constant representing the Tooltip CSS class
* @property YAHOO.widget.Tooltip.CSS_TOOLTIP
* @static
* @final
* @type String
*/
Tooltip.CSS_TOOLTIP = "yui-tt";
function restoreOriginalWidth(sOriginalWidth, sForcedWidth) {
var oConfig = this.cfg,
sCurrentWidth = oConfig.getProperty("width");
if (sCurrentWidth == sForcedWidth) {
oConfig.setProperty("width", sOriginalWidth);
}
}
/*
changeContent event handler that sets a Tooltip instance's "width"
configuration property to the value of its root HTML
elements's offsetWidth if a specific width has not been set.
*/
function setWidthToOffsetWidth(p_sType, p_aArgs) {
if ("_originalWidth" in this) {
restoreOriginalWidth.call(this, this._originalWidth, this._forcedWidth);
}
var oBody = document.body,
oConfig = this.cfg,
sOriginalWidth = oConfig.getProperty("width"),
sNewWidth,
oClone;
if ((!sOriginalWidth || sOriginalWidth == "auto") &&
(oConfig.getProperty("container") != oBody ||
oConfig.getProperty("x") >= Dom.getViewportWidth() ||
oConfig.getProperty("y") >= Dom.getViewportHeight())) {
oClone = this.element.cloneNode(true);
oClone.style.visibility = "hidden";
oClone.style.top = "0px";
oClone.style.left = "0px";
oBody.appendChild(oClone);
sNewWidth = (oClone.offsetWidth + "px");
oBody.removeChild(oClone);
oClone = null;
oConfig.setProperty("width", sNewWidth);
oConfig.refireEvent("xy");
this._originalWidth = sOriginalWidth || "";
this._forcedWidth = sNewWidth;
}
}
// "onDOMReady" that renders the ToolTip
function onDOMReady(p_sType, p_aArgs, p_oObject) {
this.render(p_oObject);
}
// "init" event handler that automatically renders the Tooltip
function onInit() {
Event.onDOMReady(onDOMReady, this.cfg.getProperty("container"), this);
}
YAHOO.extend(Tooltip, YAHOO.widget.Overlay, {
/**
* The Tooltip initialization method. This method is automatically
* called by the constructor. A Tooltip is automatically rendered by
* the init method, and it also is set to be invisible by default,
* and constrained to viewport by default as well.
* @method init
* @param {String} el The element ID representing the Tooltip <em>OR</em>
* @param {HTMLElement} el The element representing the Tooltip
* @param {Object} userConfig The configuration object literal
* containing the configuration that should be set for this Tooltip.
* See configuration documentation for more details.
*/
init: function (el, userConfig) {
Tooltip.superclass.init.call(this, el);
this.beforeInitEvent.fire(Tooltip);
Dom.addClass(this.element, Tooltip.CSS_TOOLTIP);
if (userConfig) {
this.cfg.applyConfig(userConfig, true);
}
this.cfg.queueProperty("visible", false);
this.cfg.queueProperty("constraintoviewport", true);
this.setBody("");
this.subscribe("changeContent", setWidthToOffsetWidth);
this.subscribe("init", onInit);
this.subscribe("render", this.onRender);
this.initEvent.fire(Tooltip);
},
/**
* Initializes the custom events for Tooltip
* @method initEvents
*/
initEvents: function () {
Tooltip.superclass.initEvents.call(this);
var SIGNATURE = CustomEvent.LIST;
/**
* CustomEvent fired when user mouses over a context element. Returning false from
* a subscriber to this event will prevent the tooltip from being displayed for
* the current context element.
*
* @event contextMouseOverEvent
* @param {HTMLElement} context The context element which the user just moused over
* @param {DOMEvent} e The DOM event object, associated with the mouse over
*/
this.contextMouseOverEvent = this.createEvent(EVENT_TYPES.CONTEXT_MOUSE_OVER);
this.contextMouseOverEvent.signature = SIGNATURE;
/**
* CustomEvent fired when the user mouses out of a context element.
*
* @event contextMouseOutEvent
* @param {HTMLElement} context The context element which the user just moused out of
* @param {DOMEvent} e The DOM event object, associated with the mouse out
*/
this.contextMouseOutEvent = this.createEvent(EVENT_TYPES.CONTEXT_MOUSE_OUT);
this.contextMouseOutEvent.signature = SIGNATURE;
/**
* CustomEvent fired just before the tooltip is displayed for the current context.
* <p>
* You can subscribe to this event if you need to set up the text for the
* tooltip based on the context element for which it is about to be displayed.
* </p>
* <p>This event differs from the beforeShow event in following respects:</p>
* <ol>
* <li>
* When moving from one context element to another, if the tooltip is not
* hidden (the <code>hidedelay</code> is not reached), the beforeShow and Show events will not
* be fired when the tooltip is displayed for the new context since it is already visible.
* However the contextTrigger event is always fired before displaying the tooltip for
* a new context.
* </li>
* <li>
* The trigger event provides access to the context element, allowing you to
* set the text of the tooltip based on context element for which the tooltip is
* triggered.
* </li>
* </ol>
* <p>
* It is not possible to prevent the tooltip from being displayed
* using this event. You can use the contextMouseOverEvent if you need to prevent
* the tooltip from being displayed.
* </p>
* @event contextTriggerEvent
* @param {HTMLElement} context The context element for which the tooltip is triggered
*/
this.contextTriggerEvent = this.createEvent(EVENT_TYPES.CONTEXT_TRIGGER);
this.contextTriggerEvent.signature = SIGNATURE;
},
/**
* Initializes the class's configurable properties which can be
* changed using the Overlay's Config object (cfg).
* @method initDefaultConfig
*/
initDefaultConfig: function () {
Tooltip.superclass.initDefaultConfig.call(this);
/**
* Specifies whether the Tooltip should be kept from overlapping
* its context element.
* @config preventoverlap
* @type Boolean
* @default true
*/
this.cfg.addProperty(DEFAULT_CONFIG.PREVENT_OVERLAP.key, {
value: DEFAULT_CONFIG.PREVENT_OVERLAP.value,
validator: DEFAULT_CONFIG.PREVENT_OVERLAP.validator,
supercedes: DEFAULT_CONFIG.PREVENT_OVERLAP.supercedes
});
/**
* The number of milliseconds to wait before showing a Tooltip
* on mouseover.
* @config showdelay
* @type Number
* @default 200
*/
this.cfg.addProperty(DEFAULT_CONFIG.SHOW_DELAY.key, {
handler: this.configShowDelay,
value: 200,
validator: DEFAULT_CONFIG.SHOW_DELAY.validator
});
/**
* The number of milliseconds to wait before automatically
* dismissing a Tooltip after the mouse has been resting on the
* context element.
* @config autodismissdelay
* @type Number
* @default 5000
*/
this.cfg.addProperty(DEFAULT_CONFIG.AUTO_DISMISS_DELAY.key, {
handler: this.configAutoDismissDelay,
value: DEFAULT_CONFIG.AUTO_DISMISS_DELAY.value,
validator: DEFAULT_CONFIG.AUTO_DISMISS_DELAY.validator
});
/**
* The number of milliseconds to wait before hiding a Tooltip
* after mouseout.
* @config hidedelay
* @type Number
* @default 250
*/
this.cfg.addProperty(DEFAULT_CONFIG.HIDE_DELAY.key, {
handler: this.configHideDelay,
value: DEFAULT_CONFIG.HIDE_DELAY.value,
validator: DEFAULT_CONFIG.HIDE_DELAY.validator
});
/**
* Specifies the Tooltip's text. The text is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source.
* @config text
* @type HTML
* @default null
*/
this.cfg.addProperty(DEFAULT_CONFIG.TEXT.key, {
handler: this.configText,
suppressEvent: DEFAULT_CONFIG.TEXT.suppressEvent
});
/**
* Specifies the container element that the Tooltip's markup
* should be rendered into.
* @config container
* @type HTMLElement/String
* @default document.body
*/
this.cfg.addProperty(DEFAULT_CONFIG.CONTAINER.key, {
handler: this.configContainer,
value: document.body
});
/**
* Specifies whether or not the tooltip is disabled. Disabled tooltips
* will not be displayed. If the tooltip is driven by the title attribute
* of the context element, the title attribute will still be removed for
* disabled tooltips, to prevent default tooltip behavior.
*
* @config disabled
* @type Boolean
* @default false
*/
this.cfg.addProperty(DEFAULT_CONFIG.DISABLED.key, {
handler: this.configContainer,
value: DEFAULT_CONFIG.DISABLED.value,
supressEvent: DEFAULT_CONFIG.DISABLED.suppressEvent
});
/**
* Specifies the XY offset from the mouse position, where the tooltip should be displayed, specified
* as a 2 element array (e.g. [10, 20]);
*
* @config xyoffset
* @type Array
* @default [0, 25]
*/
this.cfg.addProperty(DEFAULT_CONFIG.XY_OFFSET.key, {
value: DEFAULT_CONFIG.XY_OFFSET.value.concat(),
supressEvent: DEFAULT_CONFIG.XY_OFFSET.suppressEvent
});
/**
* Specifies the element or elements that the Tooltip should be
* anchored to on mouseover.
* @config context
* @type HTMLElement[]/String[]
* @default null
*/
/**
* String representing the width of the Tooltip. <em>Please note:
* </em> As of version 2.3 if either no value or a value of "auto"
* is specified, and the Toolip's "container" configuration property
* is set to something other than <code>document.body</code> or
* its "context" element resides outside the immediately visible
* portion of the document, the width of the Tooltip will be
* calculated based on the offsetWidth of its root HTML and set just
* before it is made visible. The original value will be
* restored when the Tooltip is hidden. This ensures the Tooltip is
* rendered at a usable width. For more information see
* YUILibrary bug #1685496 and YUILibrary
* bug #1735423.
* @config width
* @type String
* @default null
*/
},
// BEGIN BUILT-IN PROPERTY EVENT HANDLERS //
/**
* The default event handler fired when the "text" property is changed.
* @method configText
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configText: function (type, args, obj) {
var text = args[0];
if (text) {
this.setBody(text);
}
},
/**
* The default event handler fired when the "container" property
* is changed.
* @method configContainer
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For
* configuration handlers, args[0] will equal the newly applied value
* for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configContainer: function (type, args, obj) {
var container = args[0];
if (typeof container == 'string') {
this.cfg.setProperty("container", document.getElementById(container), true);
}
},
/**
* @method _removeEventListeners
* @description Removes all of the DOM event handlers from the HTML
* element(s) that trigger the display of the tooltip.
* @protected
*/
_removeEventListeners: function () {
var aElements = this._context,
nElements,
oElement,
i;
if (aElements) {
nElements = aElements.length;
if (nElements > 0) {
i = nElements - 1;
do {
oElement = aElements[i];
Event.removeListener(oElement, "mouseover", this.onContextMouseOver);
Event.removeListener(oElement, "mousemove", this.onContextMouseMove);
Event.removeListener(oElement, "mouseout", this.onContextMouseOut);
}
while (i--);
}
}
},
/**
* The default event handler fired when the "context" property
* is changed.
* @method configContext
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configContext: function (type, args, obj) {
var context = args[0],
aElements,
nElements,
oElement,
i;
if (context) {
// Normalize parameter into an array
if (! (context instanceof Array)) {
if (typeof context == "string") {
this.cfg.setProperty("context", [document.getElementById(context)], true);
} else { // Assuming this is an element
this.cfg.setProperty("context", [context], true);
}
context = this.cfg.getProperty("context");
}
// Remove any existing mouseover/mouseout listeners
this._removeEventListeners();
// Add mouseover/mouseout listeners to context elements
this._context = context;
aElements = this._context;
if (aElements) {
nElements = aElements.length;
if (nElements > 0) {
i = nElements - 1;
do {
oElement = aElements[i];
Event.on(oElement, "mouseover", this.onContextMouseOver, this);
Event.on(oElement, "mousemove", this.onContextMouseMove, this);
Event.on(oElement, "mouseout", this.onContextMouseOut, this);
}
while (i--);
}
}
}
},
// END BUILT-IN PROPERTY EVENT HANDLERS //
// BEGIN BUILT-IN DOM EVENT HANDLERS //
/**
* The default event handler fired when the user moves the mouse while
* over the context element.
* @method onContextMouseMove
* @param {DOMEvent} e The current DOM event
* @param {Object} obj The object argument
*/
onContextMouseMove: function (e, obj) {
obj.pageX = Event.getPageX(e);
obj.pageY = Event.getPageY(e);
},
/**
* The default event handler fired when the user mouses over the
* context element.
* @method onContextMouseOver
* @param {DOMEvent} e The current DOM event
* @param {Object} obj The object argument
*/
onContextMouseOver: function (e, obj) {
var context = this;
if (context.title) {
obj._tempTitle = context.title;
context.title = "";
}
// Fire first, to honor disabled set in the listner
if (obj.fireEvent("contextMouseOver", context, e) !== false && !obj.cfg.getProperty("disabled")) {
// Stop the tooltip from being hidden (set on last mouseout)
if (obj.hideProcId) {
clearTimeout(obj.hideProcId);
obj.hideProcId = null;
}
Event.on(context, "mousemove", obj.onContextMouseMove, obj);
/**
* The unique process ID associated with the thread responsible
* for showing the Tooltip.
* @type int
*/
obj.showProcId = obj.doShow(e, context);
}
},
/**
* The default event handler fired when the user mouses out of
* the context element.
* @method onContextMouseOut
* @param {DOMEvent} e The current DOM event
* @param {Object} obj The object argument
*/
onContextMouseOut: function (e, obj) {
var el = this;
if (obj._tempTitle) {
el.title = obj._tempTitle;
obj._tempTitle = null;
}
if (obj.showProcId) {
clearTimeout(obj.showProcId);
obj.showProcId = null;
}
if (obj.hideProcId) {
clearTimeout(obj.hideProcId);
obj.hideProcId = null;
}
obj.fireEvent("contextMouseOut", el, e);
obj.hideProcId = setTimeout(function () {
obj.hide();
}, obj.cfg.getProperty("hidedelay"));
},
// END BUILT-IN DOM EVENT HANDLERS //
/**
* Processes the showing of the Tooltip by setting the timeout delay
* and offset of the Tooltip.
* @method doShow
* @param {DOMEvent} e The current DOM event
* @param {HTMLElement} context The current context element
* @return {Number} The process ID of the timeout function associated
* with doShow
*/
doShow: function (e, context) {
var offset = this.cfg.getProperty("xyoffset"),
xOffset = offset[0],
yOffset = offset[1],
me = this;
if (UA.opera && context.tagName &&
context.tagName.toUpperCase() == "A") {
yOffset += 12;
}
return setTimeout(function () {
var txt = me.cfg.getProperty("text");
// title does not over-ride text
if (me._tempTitle && (txt === "" || YAHOO.lang.isUndefined(txt) || YAHOO.lang.isNull(txt))) {
me.setBody(me._tempTitle);
} else {
me.cfg.refireEvent("text");
}
me.moveTo(me.pageX + xOffset, me.pageY + yOffset);
if (me.cfg.getProperty("preventoverlap")) {
me.preventOverlap(me.pageX, me.pageY);
}
Event.removeListener(context, "mousemove", me.onContextMouseMove);
me.contextTriggerEvent.fire(context);
me.show();
me.hideProcId = me.doHide();
}, this.cfg.getProperty("showdelay"));
},
/**
* Sets the timeout for the auto-dismiss delay, which by default is 5
* seconds, meaning that a tooltip will automatically dismiss itself
* after 5 seconds of being displayed.
* @method doHide
*/
doHide: function () {
var me = this;
return setTimeout(function () {
me.hide();
}, this.cfg.getProperty("autodismissdelay"));
},
/**
* Fired when the Tooltip is moved, this event handler is used to
* prevent the Tooltip from overlapping with its context element.
* @method preventOverlay
* @param {Number} pageX The x coordinate position of the mouse pointer
* @param {Number} pageY The y coordinate position of the mouse pointer
*/
preventOverlap: function (pageX, pageY) {
var height = this.element.offsetHeight,
mousePoint = new YAHOO.util.Point(pageX, pageY),
elementRegion = Dom.getRegion(this.element);
elementRegion.top -= 5;
elementRegion.left -= 5;
elementRegion.right += 5;
elementRegion.bottom += 5;
if (elementRegion.contains(mousePoint)) {
this.cfg.setProperty("y", (pageY - height - 5));
}
},
/**
* @method onRender
* @description "render" event handler for the Tooltip.
* @param {String} p_sType String representing the name of the event
* that was fired.
* @param {Array} p_aArgs Array of arguments sent when the event
* was fired.
*/
onRender: function (p_sType, p_aArgs) {
function sizeShadow() {
var oElement = this.element,
oShadow = this.underlay;
if (oShadow) {
oShadow.style.width = (oElement.offsetWidth + 6) + "px";
oShadow.style.height = (oElement.offsetHeight + 1) + "px";
}
}
function addShadowVisibleClass() {
Dom.addClass(this.underlay, "yui-tt-shadow-visible");
if (UA.ie) {
this.forceUnderlayRedraw();
}
}
function removeShadowVisibleClass() {
Dom.removeClass(this.underlay, "yui-tt-shadow-visible");
}
function createShadow() {
var oShadow = this.underlay,
oElement,
Module,
nIE,
me;
if (!oShadow) {
oElement = this.element;
Module = YAHOO.widget.Module;
nIE = UA.ie;
me = this;
if (!m_oShadowTemplate) {
m_oShadowTemplate = document.createElement("div");
m_oShadowTemplate.className = "yui-tt-shadow";
}
oShadow = m_oShadowTemplate.cloneNode(false);
oElement.appendChild(oShadow);
this.underlay = oShadow;
// Backward compatibility, even though it's probably
// intended to be "private", it isn't marked as such in the api docs
this._shadow = this.underlay;
addShadowVisibleClass.call(this);
this.subscribe("beforeShow", addShadowVisibleClass);
this.subscribe("hide", removeShadowVisibleClass);
if (bIEQuirks) {
window.setTimeout(function () {
sizeShadow.call(me);
}, 0);
this.cfg.subscribeToConfigEvent("width", sizeShadow);
this.cfg.subscribeToConfigEvent("height", sizeShadow);
this.subscribe("changeContent", sizeShadow);
Module.textResizeEvent.subscribe(sizeShadow, this, true);
this.subscribe("destroy", function () {
Module.textResizeEvent.unsubscribe(sizeShadow, this);
});
}
}
}
function onBeforeShow() {
createShadow.call(this);
this.unsubscribe("beforeShow", onBeforeShow);
}
if (this.cfg.getProperty("visible")) {
createShadow.call(this);
} else {
this.subscribe("beforeShow", onBeforeShow);
}
},
/**
* Forces the underlay element to be repainted, through the application/removal
* of a yui-force-redraw class to the underlay element.
*
* @method forceUnderlayRedraw
*/
forceUnderlayRedraw : function() {
var tt = this;
Dom.addClass(tt.underlay, "yui-force-redraw");
setTimeout(function() {Dom.removeClass(tt.underlay, "yui-force-redraw");}, 0);
},
/**
* Removes the Tooltip element from the DOM and sets all child
* elements to null.
* @method destroy
*/
destroy: function () {
// Remove any existing mouseover/mouseout listeners
this._removeEventListeners();
Tooltip.superclass.destroy.call(this);
},
/**
* Returns a string representation of the object.
* @method toString
* @return {String} The string representation of the Tooltip
*/
toString: function () {
return "Tooltip " + this.id;
}
});
}());
(function () {
/**
* Panel is an implementation of Overlay that behaves like an OS window,
* with a draggable header and an optional close icon at the top right.
* @namespace YAHOO.widget
* @class Panel
* @extends YAHOO.widget.Overlay
* @constructor
* @param {String} el The element ID representing the Panel <em>OR</em>
* @param {HTMLElement} el The element representing the Panel
* @param {Object} userConfig The configuration object literal containing
* the configuration that should be set for this Panel. See configuration
* documentation for more details.
*/
YAHOO.widget.Panel = function (el, userConfig) {
YAHOO.widget.Panel.superclass.constructor.call(this, el, userConfig);
};
var _currentModal = null;
var Lang = YAHOO.lang,
Util = YAHOO.util,
Dom = Util.Dom,
Event = Util.Event,
CustomEvent = Util.CustomEvent,
KeyListener = YAHOO.util.KeyListener,
Config = Util.Config,
Overlay = YAHOO.widget.Overlay,
Panel = YAHOO.widget.Panel,
UA = YAHOO.env.ua,
bIEQuirks = (UA.ie && (UA.ie <= 6 || document.compatMode == "BackCompat")),
m_oMaskTemplate,
m_oUnderlayTemplate,
m_oCloseIconTemplate,
/**
* Constant representing the name of the Panel's events
* @property EVENT_TYPES
* @private
* @final
* @type Object
*/
EVENT_TYPES = {
"BEFORE_SHOW_MASK" : "beforeShowMask",
"BEFORE_HIDE_MASK" : "beforeHideMask",
"SHOW_MASK": "showMask",
"HIDE_MASK": "hideMask",
"DRAG": "drag"
},
/**
* Constant representing the Panel's configuration properties
* @property DEFAULT_CONFIG
* @private
* @final
* @type Object
*/
DEFAULT_CONFIG = {
"CLOSE": {
key: "close",
value: true,
validator: Lang.isBoolean,
supercedes: ["visible"]
},
"DRAGGABLE": {
key: "draggable",
value: (Util.DD ? true : false),
validator: Lang.isBoolean,
supercedes: ["visible"]
},
"DRAG_ONLY" : {
key: "dragonly",
value: false,
validator: Lang.isBoolean,
supercedes: ["draggable"]
},
"UNDERLAY": {
key: "underlay",
value: "shadow",
supercedes: ["visible"]
},
"MODAL": {
key: "modal",
value: false,
validator: Lang.isBoolean,
supercedes: ["visible", "zindex"]
},
"KEY_LISTENERS": {
key: "keylisteners",
suppressEvent: true,
supercedes: ["visible"]
},
"STRINGS" : {
key: "strings",
supercedes: ["close"],
validator: Lang.isObject,
value: {
close: "Close"
}
}
};
/**
* Constant representing the default CSS class used for a Panel
* @property YAHOO.widget.Panel.CSS_PANEL
* @static
* @final
* @type String
*/
Panel.CSS_PANEL = "yui-panel";
/**
* Constant representing the default CSS class used for a Panel's
* wrapping container
* @property YAHOO.widget.Panel.CSS_PANEL_CONTAINER
* @static
* @final
* @type String
*/
Panel.CSS_PANEL_CONTAINER = "yui-panel-container";
/**
* Constant representing the default set of focusable elements
* on the pagewhich Modal Panels will prevent access to, when
* the modal mask is displayed
*
* @property YAHOO.widget.Panel.FOCUSABLE
* @static
* @type Array
*/
Panel.FOCUSABLE = [
"a",
"button",
"select",
"textarea",
"input",
"iframe"
];
// Private CustomEvent listeners
/*
"beforeRender" event handler that creates an empty header for a Panel
instance if its "draggable" configuration property is set to "true"
and no header has been created.
*/
function createHeader(p_sType, p_aArgs) {
if (!this.header && this.cfg.getProperty("draggable")) {
this.setHeader(" ");
}
}
/*
"hide" event handler that sets a Panel instance's "width"
configuration property back to its original value before
"setWidthToOffsetWidth" was called.
*/
function restoreOriginalWidth(p_sType, p_aArgs, p_oObject) {
var sOriginalWidth = p_oObject[0],
sNewWidth = p_oObject[1],
oConfig = this.cfg,
sCurrentWidth = oConfig.getProperty("width");
if (sCurrentWidth == sNewWidth) {
oConfig.setProperty("width", sOriginalWidth);
}
this.unsubscribe("hide", restoreOriginalWidth, p_oObject);
}
/*
"beforeShow" event handler that sets a Panel instance's "width"
configuration property to the value of its root HTML
elements's offsetWidth
*/
function setWidthToOffsetWidth(p_sType, p_aArgs) {
var oConfig,
sOriginalWidth,
sNewWidth;
if (bIEQuirks) {
oConfig = this.cfg;
sOriginalWidth = oConfig.getProperty("width");
if (!sOriginalWidth || sOriginalWidth == "auto") {
sNewWidth = (this.element.offsetWidth + "px");
oConfig.setProperty("width", sNewWidth);
this.subscribe("hide", restoreOriginalWidth,
[(sOriginalWidth || ""), sNewWidth]);
}
}
}
YAHOO.extend(Panel, Overlay, {
/**
* The Overlay initialization method, which is executed for Overlay and
* all of its subclasses. This method is automatically called by the
* constructor, and sets up all DOM references for pre-existing markup,
* and creates required markup if it is not already present.
* @method init
* @param {String} el The element ID representing the Overlay <em>OR</em>
* @param {HTMLElement} el The element representing the Overlay
* @param {Object} userConfig The configuration object literal
* containing the configuration that should be set for this Overlay.
* See configuration documentation for more details.
*/
init: function (el, userConfig) {
/*
Note that we don't pass the user config in here yet because
we only want it executed once, at the lowest subclass level
*/
Panel.superclass.init.call(this, el/*, userConfig*/);
this.beforeInitEvent.fire(Panel);
Dom.addClass(this.element, Panel.CSS_PANEL);
this.buildWrapper();
if (userConfig) {
this.cfg.applyConfig(userConfig, true);
}
this.subscribe("showMask", this._addFocusHandlers);
this.subscribe("hideMask", this._removeFocusHandlers);
this.subscribe("beforeRender", createHeader);
this.subscribe("render", function() {
this.setFirstLastFocusable();
this.subscribe("changeContent", this.setFirstLastFocusable);
});
this.subscribe("show", this._focusOnShow);
this.initEvent.fire(Panel);
},
/**
* @method _onElementFocus
* @private
*
* "focus" event handler for a focuable element. Used to automatically
* blur the element when it receives focus to ensure that a Panel
* instance's modality is not compromised.
*
* @param {Event} e The DOM event object
*/
_onElementFocus : function(e){
if(_currentModal === this) {
var target = Event.getTarget(e),
doc = document.documentElement,
insideDoc = (target !== doc && target !== window);
// mask and documentElement checks added for IE, which focuses on the mask when it's clicked on, and focuses on
// the documentElement, when the document scrollbars are clicked on
if (insideDoc && target !== this.element && target !== this.mask && !Dom.isAncestor(this.element, target)) {
try {
this._focusFirstModal();
} catch(err){
// Just in case we fail to focus
try {
if (insideDoc && target !== document.body) {
target.blur();
}
} catch(err2) { }
}
}
}
},
/**
* Focuses on the first element if present, otherwise falls back to the focus mechanisms used for
* modality. This method does not try/catch focus failures. The caller is responsible for catching exceptions,
* and taking remedial measures.
*
* @method _focusFirstModal
*/
_focusFirstModal : function() {
var el = this.firstElement;
if (el) {
el.focus();
} else {
if (this._modalFocus) {
this._modalFocus.focus();
} else {
this.innerElement.focus();
}
}
},
/**
* @method _addFocusHandlers
* @protected
*
* "showMask" event handler that adds a "focus" event handler to all
* focusable elements in the document to enforce a Panel instance's
* modality from being compromised.
*
* @param p_sType {String} Custom event type
* @param p_aArgs {Array} Custom event arguments
*/
_addFocusHandlers: function(p_sType, p_aArgs) {
if (!this.firstElement) {
if (UA.webkit || UA.opera) {
if (!this._modalFocus) {
this._createHiddenFocusElement();
}
} else {
this.innerElement.tabIndex = 0;
}
}
this._setTabLoop(this.firstElement, this.lastElement);
Event.onFocus(document.documentElement, this._onElementFocus, this, true);
_currentModal = this;
},
/**
* Creates a hidden focusable element, used to focus on,
* to enforce modality for browsers in which focus cannot
* be applied to the container box.
*
* @method _createHiddenFocusElement
* @private
*/
_createHiddenFocusElement : function() {
var e = document.createElement("button");
e.style.height = "1px";
e.style.width = "1px";
e.style.position = "absolute";
e.style.left = "-10000em";
e.style.opacity = 0;
e.tabIndex = -1;
this.innerElement.appendChild(e);
this._modalFocus = e;
},
/**
* @method _removeFocusHandlers
* @protected
*
* "hideMask" event handler that removes all "focus" event handlers added
* by the "addFocusEventHandlers" method.
*
* @param p_sType {String} Event type
* @param p_aArgs {Array} Event Arguments
*/
_removeFocusHandlers: function(p_sType, p_aArgs) {
Event.removeFocusListener(document.documentElement, this._onElementFocus, this);
if (_currentModal == this) {
_currentModal = null;
}
},
/**
* Focus handler for the show event
*
* @method _focusOnShow
* @param {String} type Event Type
* @param {Array} args Event arguments
* @param {Object} obj Additional data
*/
_focusOnShow : function(type, args, obj) {
if (args && args[1]) {
Event.stopEvent(args[1]);
}
if (!this.focusFirst(type, args, obj)) {
if (this.cfg.getProperty("modal")) {
this._focusFirstModal();
}
}
},
/**
* Sets focus to the first element in the Panel.
*
* @method focusFirst
* @return {Boolean} true, if successfully focused, false otherwise
*/
focusFirst: function (type, args, obj) {
var el = this.firstElement, focused = false;
if (args && args[1]) {
Event.stopEvent(args[1]);
}
if (el) {
try {
el.focus();
focused = true;
} catch(err) {
// Ignore
}
}
return focused;
},
/**
* Sets focus to the last element in the Panel.
*
* @method focusLast
* @return {Boolean} true, if successfully focused, false otherwise
*/
focusLast: function (type, args, obj) {
var el = this.lastElement, focused = false;
if (args && args[1]) {
Event.stopEvent(args[1]);
}
if (el) {
try {
el.focus();
focused = true;
} catch(err) {
// Ignore
}
}
return focused;
},
/**
* Protected internal method for setTabLoop, which can be used by
* subclasses to jump in and modify the arguments passed in if required.
*
* @method _setTabLoop
* @param {HTMLElement} firstElement
* @param {HTMLElement} lastElement
* @protected
*
*/
_setTabLoop : function(firstElement, lastElement) {
this.setTabLoop(firstElement, lastElement);
},
/**
* Sets up a tab, shift-tab loop between the first and last elements
* provided. NOTE: Sets up the preventBackTab and preventTabOut KeyListener
* instance properties, which are reset everytime this method is invoked.
*
* @method setTabLoop
* @param {HTMLElement} firstElement
* @param {HTMLElement} lastElement
*
*/
setTabLoop : function(firstElement, lastElement) {
var backTab = this.preventBackTab, tab = this.preventTabOut,
showEvent = this.showEvent, hideEvent = this.hideEvent;
if (backTab) {
backTab.disable();
showEvent.unsubscribe(backTab.enable, backTab);
hideEvent.unsubscribe(backTab.disable, backTab);
backTab = this.preventBackTab = null;
}
if (tab) {
tab.disable();
showEvent.unsubscribe(tab.enable, tab);
hideEvent.unsubscribe(tab.disable,tab);
tab = this.preventTabOut = null;
}
if (firstElement) {
this.preventBackTab = new KeyListener(firstElement,
{shift:true, keys:9},
{fn:this.focusLast, scope:this, correctScope:true}
);
backTab = this.preventBackTab;
showEvent.subscribe(backTab.enable, backTab, true);
hideEvent.subscribe(backTab.disable,backTab, true);
}
if (lastElement) {
this.preventTabOut = new KeyListener(lastElement,
{shift:false, keys:9},
{fn:this.focusFirst, scope:this, correctScope:true}
);
tab = this.preventTabOut;
showEvent.subscribe(tab.enable, tab, true);
hideEvent.subscribe(tab.disable,tab, true);
}
},
/**
* Returns an array of the currently focusable items which reside within
* Panel. The set of focusable elements the method looks for are defined
* in the Panel.FOCUSABLE static property
*
* @method getFocusableElements
* @param {HTMLElement} root element to start from.
*/
getFocusableElements : function(root) {
root = root || this.innerElement;
var focusable = {}, panel = this;
for (var i = 0; i < Panel.FOCUSABLE.length; i++) {
focusable[Panel.FOCUSABLE[i]] = true;
}
// Not looking by Tag, since we want elements in DOM order
return Dom.getElementsBy(function(el) { return panel._testIfFocusable(el, focusable); }, null, root);
},
/**
* This is the test method used by getFocusableElements, to determine which elements to
* include in the focusable elements list. Users may override this to customize behavior.
*
* @method _testIfFocusable
* @param {Object} el The element being tested
* @param {Object} focusable The hash of known focusable elements, created by an array-to-map operation on Panel.FOCUSABLE
* @protected
*/
_testIfFocusable: function(el, focusable) {
if (el.focus && el.type !== "hidden" && !el.disabled && focusable[el.tagName.toLowerCase()]) {
return true;
}
return false;
},
/**
* Sets the firstElement and lastElement instance properties
* to the first and last focusable elements in the Panel.
*
* @method setFirstLastFocusable
*/
setFirstLastFocusable : function() {
this.firstElement = null;
this.lastElement = null;
var elements = this.getFocusableElements();
this.focusableElements = elements;
if (elements.length > 0) {
this.firstElement = elements[0];
this.lastElement = elements[elements.length - 1];
}
if (this.cfg.getProperty("modal")) {
this._setTabLoop(this.firstElement, this.lastElement);
}
},
/**
* Initializes the custom events for Module which are fired
* automatically at appropriate times by the Module class.
*/
initEvents: function () {
Panel.superclass.initEvents.call(this);
var SIGNATURE = CustomEvent.LIST;
/**
* CustomEvent fired after the modality mask is shown
* @event showMaskEvent
*/
this.showMaskEvent = this.createEvent(EVENT_TYPES.SHOW_MASK);
this.showMaskEvent.signature = SIGNATURE;
/**
* CustomEvent fired before the modality mask is shown. Subscribers can return false to prevent the
* mask from being shown
* @event beforeShowMaskEvent
*/
this.beforeShowMaskEvent = this.createEvent(EVENT_TYPES.BEFORE_SHOW_MASK);
this.beforeShowMaskEvent.signature = SIGNATURE;
/**
* CustomEvent fired after the modality mask is hidden
* @event hideMaskEvent
*/
this.hideMaskEvent = this.createEvent(EVENT_TYPES.HIDE_MASK);
this.hideMaskEvent.signature = SIGNATURE;
/**
* CustomEvent fired before the modality mask is hidden. Subscribers can return false to prevent the
* mask from being hidden
* @event beforeHideMaskEvent
*/
this.beforeHideMaskEvent = this.createEvent(EVENT_TYPES.BEFORE_HIDE_MASK);
this.beforeHideMaskEvent.signature = SIGNATURE;
/**
* CustomEvent when the Panel is dragged
* @event dragEvent
*/
this.dragEvent = this.createEvent(EVENT_TYPES.DRAG);
this.dragEvent.signature = SIGNATURE;
},
/**
* Initializes the class's configurable properties which can be changed
* using the Panel's Config object (cfg).
* @method initDefaultConfig
*/
initDefaultConfig: function () {
Panel.superclass.initDefaultConfig.call(this);
// Add panel config properties //
/**
* True if the Panel should display a "close" button
* @config close
* @type Boolean
* @default true
*/
this.cfg.addProperty(DEFAULT_CONFIG.CLOSE.key, {
handler: this.configClose,
value: DEFAULT_CONFIG.CLOSE.value,
validator: DEFAULT_CONFIG.CLOSE.validator,
supercedes: DEFAULT_CONFIG.CLOSE.supercedes
});
/**
* Boolean specifying if the Panel should be draggable. The default
* value is "true" if the Drag and Drop utility is included,
* otherwise it is "false." <strong>PLEASE NOTE:</strong> There is a
* known issue in IE 6 (Strict Mode and Quirks Mode) and IE 7
* (Quirks Mode) where Panels that either don't have a value set for
* their "width" configuration property, or their "width"
* configuration property is set to "auto" will only be draggable by
* placing the mouse on the text of the Panel's header element.
* To fix this bug, draggable Panels missing a value for their
* "width" configuration property, or whose "width" configuration
* property is set to "auto" will have it set to the value of
* their root HTML element's offsetWidth before they are made
* visible. The calculated width is then removed when the Panel is
* hidden. <em>This fix is only applied to draggable Panels in IE 6
* (Strict Mode and Quirks Mode) and IE 7 (Quirks Mode)</em>. For
* more information on this issue see:
* YUILibrary bugs #1726972 and #1589210.
* @config draggable
* @type Boolean
* @default true
*/
this.cfg.addProperty(DEFAULT_CONFIG.DRAGGABLE.key, {
handler: this.configDraggable,
value: (Util.DD) ? true : false,
validator: DEFAULT_CONFIG.DRAGGABLE.validator,
supercedes: DEFAULT_CONFIG.DRAGGABLE.supercedes
});
/**
* Boolean specifying if the draggable Panel should be drag only, not interacting with drop
* targets on the page.
* <p>
* When set to true, draggable Panels will not check to see if they are over drop targets,
* or fire the DragDrop events required to support drop target interaction (onDragEnter,
* onDragOver, onDragOut, onDragDrop etc.).
* If the Panel is not designed to be dropped on any target elements on the page, then this
* flag can be set to true to improve performance.
* </p>
* <p>
* When set to false, all drop target related events will be fired.
* </p>
* <p>
* The property is set to false by default to maintain backwards compatibility but should be
* set to true if drop target interaction is not required for the Panel, to improve performance.</p>
*
* @config dragOnly
* @type Boolean
* @default false
*/
this.cfg.addProperty(DEFAULT_CONFIG.DRAG_ONLY.key, {
value: DEFAULT_CONFIG.DRAG_ONLY.value,
validator: DEFAULT_CONFIG.DRAG_ONLY.validator,
supercedes: DEFAULT_CONFIG.DRAG_ONLY.supercedes
});
/**
* Sets the type of underlay to display for the Panel. Valid values
* are "shadow," "matte," and "none". <strong>PLEASE NOTE:</strong>
* The creation of the underlay element is deferred until the Panel
* is initially made visible. For Gecko-based browsers on Mac
* OS X the underlay elment is always created as it is used as a
* shim to prevent Aqua scrollbars below a Panel instance from poking
* through it (See YUILibrary bug #1723530).
* @config underlay
* @type String
* @default shadow
*/
this.cfg.addProperty(DEFAULT_CONFIG.UNDERLAY.key, {
handler: this.configUnderlay,
value: DEFAULT_CONFIG.UNDERLAY.value,
supercedes: DEFAULT_CONFIG.UNDERLAY.supercedes
});
/**
* True if the Panel should be displayed in a modal fashion,
* automatically creating a transparent mask over the document that
* will not be removed until the Panel is dismissed.
* @config modal
* @type Boolean
* @default false
*/
this.cfg.addProperty(DEFAULT_CONFIG.MODAL.key, {
handler: this.configModal,
value: DEFAULT_CONFIG.MODAL.value,
validator: DEFAULT_CONFIG.MODAL.validator,
supercedes: DEFAULT_CONFIG.MODAL.supercedes
});
/**
* A KeyListener (or array of KeyListeners) that will be enabled
* when the Panel is shown, and disabled when the Panel is hidden.
* @config keylisteners
* @type YAHOO.util.KeyListener[]
* @default null
*/
this.cfg.addProperty(DEFAULT_CONFIG.KEY_LISTENERS.key, {
handler: this.configKeyListeners,
suppressEvent: DEFAULT_CONFIG.KEY_LISTENERS.suppressEvent,
supercedes: DEFAULT_CONFIG.KEY_LISTENERS.supercedes
});
/**
* UI Strings used by the Panel. The strings are inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source.
*
* @config strings
* @type Object
* @default An object literal with the properties shown below:
* <dl>
* <dt>close</dt><dd><em>HTML</em> : The markup to use as the label for the close icon. Defaults to "Close".</dd>
* </dl>
*/
this.cfg.addProperty(DEFAULT_CONFIG.STRINGS.key, {
value:DEFAULT_CONFIG.STRINGS.value,
handler:this.configStrings,
validator:DEFAULT_CONFIG.STRINGS.validator,
supercedes:DEFAULT_CONFIG.STRINGS.supercedes
});
},
// BEGIN BUILT-IN PROPERTY EVENT HANDLERS //
/**
* The default event handler fired when the "close" property is changed.
* The method controls the appending or hiding of the close icon at the
* top right of the Panel.
* @method configClose
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configClose: function (type, args, obj) {
var val = args[0],
oClose = this.close,
strings = this.cfg.getProperty("strings"),
fc;
if (val) {
if (!oClose) {
if (!m_oCloseIconTemplate) {
m_oCloseIconTemplate = document.createElement("a");
m_oCloseIconTemplate.className = "container-close";
m_oCloseIconTemplate.href = "#";
}
oClose = m_oCloseIconTemplate.cloneNode(true);
fc = this.innerElement.firstChild;
if (fc) {
this.innerElement.insertBefore(oClose, fc);
} else {
this.innerElement.appendChild(oClose);
}
oClose.innerHTML = (strings && strings.close) ? strings.close : " ";
Event.on(oClose, "click", this._doClose, this, true);
this.close = oClose;
} else {
oClose.style.display = "block";
}
} else {
if (oClose) {
oClose.style.display = "none";
}
}
},
/**
* Event handler for the close icon
*
* @method _doClose
* @protected
*
* @param {DOMEvent} e
*/
_doClose : function (e) {
Event.preventDefault(e);
this.hide();
},
/**
* The default event handler fired when the "draggable" property
* is changed.
* @method configDraggable
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configDraggable: function (type, args, obj) {
var val = args[0];
if (val) {
if (!Util.DD) {
this.cfg.setProperty("draggable", false);
return;
}
if (this.header) {
Dom.setStyle(this.header, "cursor", "move");
this.registerDragDrop();
}
this.subscribe("beforeShow", setWidthToOffsetWidth);
} else {
if (this.dd) {
this.dd.unreg();
}
if (this.header) {
Dom.setStyle(this.header,"cursor","auto");
}
this.unsubscribe("beforeShow", setWidthToOffsetWidth);
}
},
/**
* The default event handler fired when the "underlay" property
* is changed.
* @method configUnderlay
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configUnderlay: function (type, args, obj) {
var bMacGecko = (this.platform == "mac" && UA.gecko),
sUnderlay = args[0].toLowerCase(),
oUnderlay = this.underlay,
oElement = this.element;
function createUnderlay() {
var bNew = false;
if (!oUnderlay) { // create if not already in DOM
if (!m_oUnderlayTemplate) {
m_oUnderlayTemplate = document.createElement("div");
m_oUnderlayTemplate.className = "underlay";
}
oUnderlay = m_oUnderlayTemplate.cloneNode(false);
this.element.appendChild(oUnderlay);
this.underlay = oUnderlay;
if (bIEQuirks) {
this.sizeUnderlay();
this.cfg.subscribeToConfigEvent("width", this.sizeUnderlay);
this.cfg.subscribeToConfigEvent("height", this.sizeUnderlay);
this.changeContentEvent.subscribe(this.sizeUnderlay);
YAHOO.widget.Module.textResizeEvent.subscribe(this.sizeUnderlay, this, true);
}
if (UA.webkit && UA.webkit < 420) {
this.changeContentEvent.subscribe(this.forceUnderlayRedraw);
}
bNew = true;
}
}
function onBeforeShow() {
var bNew = createUnderlay.call(this);
if (!bNew && bIEQuirks) {
this.sizeUnderlay();
}
this._underlayDeferred = false;
this.beforeShowEvent.unsubscribe(onBeforeShow);
}
function destroyUnderlay() {
if (this._underlayDeferred) {
this.beforeShowEvent.unsubscribe(onBeforeShow);
this._underlayDeferred = false;
}
if (oUnderlay) {
this.cfg.unsubscribeFromConfigEvent("width", this.sizeUnderlay);
this.cfg.unsubscribeFromConfigEvent("height",this.sizeUnderlay);
this.changeContentEvent.unsubscribe(this.sizeUnderlay);
this.changeContentEvent.unsubscribe(this.forceUnderlayRedraw);
YAHOO.widget.Module.textResizeEvent.unsubscribe(this.sizeUnderlay, this, true);
this.element.removeChild(oUnderlay);
this.underlay = null;
}
}
switch (sUnderlay) {
case "shadow":
Dom.removeClass(oElement, "matte");
Dom.addClass(oElement, "shadow");
break;
case "matte":
if (!bMacGecko) {
destroyUnderlay.call(this);
}
Dom.removeClass(oElement, "shadow");
Dom.addClass(oElement, "matte");
break;
default:
if (!bMacGecko) {
destroyUnderlay.call(this);
}
Dom.removeClass(oElement, "shadow");
Dom.removeClass(oElement, "matte");
break;
}
if ((sUnderlay == "shadow") || (bMacGecko && !oUnderlay)) {
if (this.cfg.getProperty("visible")) {
var bNew = createUnderlay.call(this);
if (!bNew && bIEQuirks) {
this.sizeUnderlay();
}
} else {
if (!this._underlayDeferred) {
this.beforeShowEvent.subscribe(onBeforeShow);
this._underlayDeferred = true;
}
}
}
},
/**
* The default event handler fired when the "modal" property is
* changed. This handler subscribes or unsubscribes to the show and hide
* events to handle the display or hide of the modality mask.
* @method configModal
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configModal: function (type, args, obj) {
var modal = args[0];
if (modal) {
if (!this._hasModalityEventListeners) {
this.subscribe("beforeShow", this.buildMask);
this.subscribe("beforeShow", this.bringToTop);
this.subscribe("beforeShow", this.showMask);
this.subscribe("hide", this.hideMask);
Overlay.windowResizeEvent.subscribe(this.sizeMask,
this, true);
this._hasModalityEventListeners = true;
}
} else {
if (this._hasModalityEventListeners) {
if (this.cfg.getProperty("visible")) {
this.hideMask();
this.removeMask();
}
this.unsubscribe("beforeShow", this.buildMask);
this.unsubscribe("beforeShow", this.bringToTop);
this.unsubscribe("beforeShow", this.showMask);
this.unsubscribe("hide", this.hideMask);
Overlay.windowResizeEvent.unsubscribe(this.sizeMask, this);
this._hasModalityEventListeners = false;
}
}
},
/**
* Removes the modality mask.
* @method removeMask
*/
removeMask: function () {
var oMask = this.mask,
oParentNode;
if (oMask) {
/*
Hide the mask before destroying it to ensure that DOM
event handlers on focusable elements get removed.
*/
this.hideMask();
oParentNode = oMask.parentNode;
if (oParentNode) {
oParentNode.removeChild(oMask);
}
this.mask = null;
}
},
/**
* The default event handler fired when the "keylisteners" property
* is changed.
* @method configKeyListeners
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configKeyListeners: function (type, args, obj) {
var listeners = args[0],
listener,
nListeners,
i;
if (listeners) {
if (listeners instanceof Array) {
nListeners = listeners.length;
for (i = 0; i < nListeners; i++) {
listener = listeners[i];
if (!Config.alreadySubscribed(this.showEvent,
listener.enable, listener)) {
this.showEvent.subscribe(listener.enable,
listener, true);
}
if (!Config.alreadySubscribed(this.hideEvent,
listener.disable, listener)) {
this.hideEvent.subscribe(listener.disable,
listener, true);
this.destroyEvent.subscribe(listener.disable,
listener, true);
}
}
} else {
if (!Config.alreadySubscribed(this.showEvent,
listeners.enable, listeners)) {
this.showEvent.subscribe(listeners.enable,
listeners, true);
}
if (!Config.alreadySubscribed(this.hideEvent,
listeners.disable, listeners)) {
this.hideEvent.subscribe(listeners.disable,
listeners, true);
this.destroyEvent.subscribe(listeners.disable,
listeners, true);
}
}
}
},
/**
* The default handler for the "strings" property
* @method configStrings
*/
configStrings : function(type, args, obj) {
var val = Lang.merge(DEFAULT_CONFIG.STRINGS.value, args[0]);
this.cfg.setProperty(DEFAULT_CONFIG.STRINGS.key, val, true);
},
/**
* The default event handler fired when the "height" property is changed.
* @method configHeight
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configHeight: function (type, args, obj) {
var height = args[0],
el = this.innerElement;
Dom.setStyle(el, "height", height);
this.cfg.refireEvent("iframe");
},
/**
* The default custom event handler executed when the Panel's height is changed,
* if the autofillheight property has been set.
*
* @method _autoFillOnHeightChange
* @protected
* @param {String} type The event type
* @param {Array} args The array of arguments passed to event subscribers
* @param {HTMLElement} el The header, body or footer element which is to be resized to fill
* out the containers height
*/
_autoFillOnHeightChange : function(type, args, el) {
Panel.superclass._autoFillOnHeightChange.apply(this, arguments);
if (bIEQuirks) {
var panel = this;
setTimeout(function() {
panel.sizeUnderlay();
},0);
}
},
/**
* The default event handler fired when the "width" property is changed.
* @method configWidth
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configWidth: function (type, args, obj) {
var width = args[0],
el = this.innerElement;
Dom.setStyle(el, "width", width);
this.cfg.refireEvent("iframe");
},
/**
* The default event handler fired when the "zIndex" property is changed.
* @method configzIndex
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configzIndex: function (type, args, obj) {
Panel.superclass.configzIndex.call(this, type, args, obj);
if (this.mask || this.cfg.getProperty("modal") === true) {
var panelZ = Dom.getStyle(this.element, "zIndex");
if (!panelZ || isNaN(panelZ)) {
panelZ = 0;
}
if (panelZ === 0) {
// Recursive call to configzindex (which should be stopped
// from going further because panelZ should no longer === 0)
this.cfg.setProperty("zIndex", 1);
} else {
this.stackMask();
}
}
},
// END BUILT-IN PROPERTY EVENT HANDLERS //
/**
* Builds the wrapping container around the Panel that is used for
* positioning the shadow and matte underlays. The container element is
* assigned to a local instance variable called container, and the
* element is reinserted inside of it.
* @method buildWrapper
*/
buildWrapper: function () {
var elementParent = this.element.parentNode,
originalElement = this.element,
wrapper = document.createElement("div");
wrapper.className = Panel.CSS_PANEL_CONTAINER;
wrapper.id = originalElement.id + "_c";
if (elementParent) {
elementParent.insertBefore(wrapper, originalElement);
}
wrapper.appendChild(originalElement);
this.element = wrapper;
this.innerElement = originalElement;
Dom.setStyle(this.innerElement, "visibility", "inherit");
},
/**
* Adjusts the size of the shadow based on the size of the element.
* @method sizeUnderlay
*/
sizeUnderlay: function () {
var oUnderlay = this.underlay,
oElement;
if (oUnderlay) {
oElement = this.element;
oUnderlay.style.width = oElement.offsetWidth + "px";
oUnderlay.style.height = oElement.offsetHeight + "px";
}
},
/**
* Registers the Panel's header for drag & drop capability.
* @method registerDragDrop
*/
registerDragDrop: function () {
var me = this;
if (this.header) {
if (!Util.DD) {
return;
}
var bDragOnly = (this.cfg.getProperty("dragonly") === true);
/**
* The YAHOO.util.DD instance, used to implement the draggable header for the panel if draggable is enabled
*
* @property dd
* @type YAHOO.util.DD
*/
this.dd = new Util.DD(this.element.id, this.id, {dragOnly: bDragOnly});
if (!this.header.id) {
this.header.id = this.id + "_h";
}
this.dd.startDrag = function () {
var offsetHeight,
offsetWidth,
viewPortWidth,
viewPortHeight,
scrollX,
scrollY;
if (YAHOO.env.ua.ie == 6) {
Dom.addClass(me.element,"drag");
}
if (me.cfg.getProperty("constraintoviewport")) {
var nViewportOffset = Overlay.VIEWPORT_OFFSET;
offsetHeight = me.element.offsetHeight;
offsetWidth = me.element.offsetWidth;
viewPortWidth = Dom.getViewportWidth();
viewPortHeight = Dom.getViewportHeight();
scrollX = Dom.getDocumentScrollLeft();
scrollY = Dom.getDocumentScrollTop();
if (offsetHeight + nViewportOffset < viewPortHeight) {
this.minY = scrollY + nViewportOffset;
this.maxY = scrollY + viewPortHeight - offsetHeight - nViewportOffset;
} else {
this.minY = scrollY + nViewportOffset;
this.maxY = scrollY + nViewportOffset;
}
if (offsetWidth + nViewportOffset < viewPortWidth) {
this.minX = scrollX + nViewportOffset;
this.maxX = scrollX + viewPortWidth - offsetWidth - nViewportOffset;
} else {
this.minX = scrollX + nViewportOffset;
this.maxX = scrollX + nViewportOffset;
}
this.constrainX = true;
this.constrainY = true;
} else {
this.constrainX = false;
this.constrainY = false;
}
me.dragEvent.fire("startDrag", arguments);
};
this.dd.onDrag = function () {
me.syncPosition();
me.cfg.refireEvent("iframe");
if (this.platform == "mac" && YAHOO.env.ua.gecko) {
this.showMacGeckoScrollbars();
}
me.dragEvent.fire("onDrag", arguments);
};
this.dd.endDrag = function () {
if (YAHOO.env.ua.ie == 6) {
Dom.removeClass(me.element,"drag");
}
me.dragEvent.fire("endDrag", arguments);
me.moveEvent.fire(me.cfg.getProperty("xy"));
};
this.dd.setHandleElId(this.header.id);
this.dd.addInvalidHandleType("INPUT");
this.dd.addInvalidHandleType("SELECT");
this.dd.addInvalidHandleType("TEXTAREA");
}
},
/**
* Builds the mask that is laid over the document when the Panel is
* configured to be modal.
* @method buildMask
*/
buildMask: function () {
var oMask = this.mask;
if (!oMask) {
if (!m_oMaskTemplate) {
m_oMaskTemplate = document.createElement("div");
m_oMaskTemplate.className = "mask";
m_oMaskTemplate.innerHTML = " ";
}
oMask = m_oMaskTemplate.cloneNode(true);
oMask.id = this.id + "_mask";
document.body.insertBefore(oMask, document.body.firstChild);
this.mask = oMask;
if (YAHOO.env.ua.gecko && this.platform == "mac") {
Dom.addClass(this.mask, "block-scrollbars");
}
// Stack mask based on the element zindex
this.stackMask();
}
},
/**
* Hides the modality mask.
* @method hideMask
*/
hideMask: function () {
if (this.cfg.getProperty("modal") && this.mask && this.beforeHideMaskEvent.fire()) {
this.mask.style.display = "none";
Dom.removeClass(document.body, "masked");
this.hideMaskEvent.fire();
}
},
/**
* Shows the modality mask.
* @method showMask
*/
showMask: function () {
if (this.cfg.getProperty("modal") && this.mask && this.beforeShowMaskEvent.fire()) {
Dom.addClass(document.body, "masked");
this.sizeMask();
this.mask.style.display = "block";
this.showMaskEvent.fire();
}
},
/**
* Sets the size of the modality mask to cover the entire scrollable
* area of the document
* @method sizeMask
*/
sizeMask: function () {
if (this.mask) {
// Shrink mask first, so it doesn't affect the document size.
var mask = this.mask,
viewWidth = Dom.getViewportWidth(),
viewHeight = Dom.getViewportHeight();
if (mask.offsetHeight > viewHeight) {
mask.style.height = viewHeight + "px";
}
if (mask.offsetWidth > viewWidth) {
mask.style.width = viewWidth + "px";
}
// Then size it to the document
mask.style.height = Dom.getDocumentHeight() + "px";
mask.style.width = Dom.getDocumentWidth() + "px";
}
},
/**
* Sets the zindex of the mask, if it exists, based on the zindex of
* the Panel element. The zindex of the mask is set to be one less
* than the Panel element's zindex.
*
* <p>NOTE: This method will not bump up the zindex of the Panel
* to ensure that the mask has a non-negative zindex. If you require the
* mask zindex to be 0 or higher, the zindex of the Panel
* should be set to a value higher than 0, before this method is called.
* </p>
* @method stackMask
*/
stackMask: function() {
if (this.mask) {
var panelZ = Dom.getStyle(this.element, "zIndex");
if (!YAHOO.lang.isUndefined(panelZ) && !isNaN(panelZ)) {
Dom.setStyle(this.mask, "zIndex", panelZ - 1);
}
}
},
/**
* Renders the Panel by inserting the elements that are not already in
* the main Panel into their correct places. Optionally appends the
* Panel to the specified node prior to the render's execution. NOTE:
* For Panels without existing markup, the appendToNode argument is
* REQUIRED. If this argument is ommitted and the current element is
* not present in the document, the function will return false,
* indicating that the render was a failure.
* @method render
* @param {String} appendToNode The element id to which the Module
* should be appended to prior to rendering <em>OR</em>
* @param {HTMLElement} appendToNode The element to which the Module
* should be appended to prior to rendering
* @return {boolean} Success or failure of the render
*/
render: function (appendToNode) {
return Panel.superclass.render.call(this, appendToNode, this.innerElement);
},
/**
* Renders the currently set header into it's proper position under the
* module element. If the module element is not provided, "this.innerElement"
* is used.
*
* @method _renderHeader
* @protected
* @param {HTMLElement} moduleElement Optional. A reference to the module element
*/
_renderHeader: function(moduleElement){
moduleElement = moduleElement || this.innerElement;
Panel.superclass._renderHeader.call(this, moduleElement);
},
/**
* Renders the currently set body into it's proper position under the
* module element. If the module element is not provided, "this.innerElement"
* is used.
*
* @method _renderBody
* @protected
* @param {HTMLElement} moduleElement Optional. A reference to the module element.
*/
_renderBody: function(moduleElement){
moduleElement = moduleElement || this.innerElement;
Panel.superclass._renderBody.call(this, moduleElement);
},
/**
* Renders the currently set footer into it's proper position under the
* module element. If the module element is not provided, "this.innerElement"
* is used.
*
* @method _renderFooter
* @protected
* @param {HTMLElement} moduleElement Optional. A reference to the module element
*/
_renderFooter: function(moduleElement){
moduleElement = moduleElement || this.innerElement;
Panel.superclass._renderFooter.call(this, moduleElement);
},
/**
* Removes the Panel element from the DOM and sets all child elements
* to null.
* @method destroy
* @param {boolean} shallowPurge If true, only the parent element's DOM event listeners are purged. If false, or not provided, all children are also purged of DOM event listeners.
* NOTE: The flag is a "shallowPurge" flag, as opposed to what may be a more intuitive "purgeChildren" flag to maintain backwards compatibility with behavior prior to 2.9.0.
*/
destroy: function (shallowPurge) {
Overlay.windowResizeEvent.unsubscribe(this.sizeMask, this);
this.removeMask();
if (this.close) {
Event.purgeElement(this.close);
}
Panel.superclass.destroy.call(this, shallowPurge);
},
/**
* Forces the underlay element to be repainted through the application/removal
* of a yui-force-redraw class to the underlay element.
*
* @method forceUnderlayRedraw
*/
forceUnderlayRedraw : function () {
var u = this.underlay;
Dom.addClass(u, "yui-force-redraw");
setTimeout(function(){Dom.removeClass(u, "yui-force-redraw");}, 0);
},
/**
* Returns a String representation of the object.
* @method toString
* @return {String} The string representation of the Panel.
*/
toString: function () {
return "Panel " + this.id;
}
});
}());
(function () {
/**
* <p>
* Dialog is an implementation of Panel that can be used to submit form
* data.
* </p>
* <p>
* Built-in functionality for buttons with event handlers is included.
* If the optional YUI Button dependancy is included on the page, the buttons
* created will be instances of YAHOO.widget.Button, otherwise regular HTML buttons
* will be created.
* </p>
* <p>
* Forms can be processed in 3 ways -- via an asynchronous Connection utility call,
* a simple form POST or GET, or manually. The YUI Connection utility should be
* included if you're using the default "async" postmethod, but is not required if
* you're using any of the other postmethod values.
* </p>
* @namespace YAHOO.widget
* @class Dialog
* @extends YAHOO.widget.Panel
* @constructor
* @param {String} el The element ID representing the Dialog <em>OR</em>
* @param {HTMLElement} el The element representing the Dialog
* @param {Object} userConfig The configuration object literal containing
* the configuration that should be set for this Dialog. See configuration
* documentation for more details.
*/
YAHOO.widget.Dialog = function (el, userConfig) {
YAHOO.widget.Dialog.superclass.constructor.call(this, el, userConfig);
};
var Event = YAHOO.util.Event,
CustomEvent = YAHOO.util.CustomEvent,
Dom = YAHOO.util.Dom,
Dialog = YAHOO.widget.Dialog,
Lang = YAHOO.lang,
/**
* Constant representing the name of the Dialog's events
* @property EVENT_TYPES
* @private
* @final
* @type Object
*/
EVENT_TYPES = {
"BEFORE_SUBMIT": "beforeSubmit",
"SUBMIT": "submit",
"MANUAL_SUBMIT": "manualSubmit",
"ASYNC_SUBMIT": "asyncSubmit",
"FORM_SUBMIT": "formSubmit",
"CANCEL": "cancel"
},
/**
* Constant representing the Dialog's configuration properties
* @property DEFAULT_CONFIG
* @private
* @final
* @type Object
*/
DEFAULT_CONFIG = {
"POST_METHOD": {
key: "postmethod",
value: "async"
},
"POST_DATA" : {
key: "postdata",
value: null
},
"BUTTONS": {
key: "buttons",
value: "none",
supercedes: ["visible"]
},
"HIDEAFTERSUBMIT" : {
key: "hideaftersubmit",
value: true
}
};
/**
* Constant representing the default CSS class used for a Dialog
* @property YAHOO.widget.Dialog.CSS_DIALOG
* @static
* @final
* @type String
*/
Dialog.CSS_DIALOG = "yui-dialog";
function removeButtonEventHandlers() {
var aButtons = this._aButtons,
nButtons,
oButton,
i;
if (Lang.isArray(aButtons)) {
nButtons = aButtons.length;
if (nButtons > 0) {
i = nButtons - 1;
do {
oButton = aButtons[i];
if (YAHOO.widget.Button && oButton instanceof YAHOO.widget.Button) {
oButton.destroy();
}
else if (oButton.tagName.toUpperCase() == "BUTTON") {
Event.purgeElement(oButton);
Event.purgeElement(oButton, false);
}
}
while (i--);
}
}
}
YAHOO.extend(Dialog, YAHOO.widget.Panel, {
/**
* @property form
* @description Object reference to the Dialog's
* <code><form></code> element.
* @default null
* @type <a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/
* level-one-html.html#ID-40002357">HTMLFormElement</a>
*/
form: null,
/**
* Initializes the class's configurable properties which can be changed
* using the Dialog's Config object (cfg).
* @method initDefaultConfig
*/
initDefaultConfig: function () {
Dialog.superclass.initDefaultConfig.call(this);
/**
* The internally maintained callback object for use with the
* Connection utility. The format of the callback object is
* similar to Connection Manager's callback object and is
* simply passed through to Connection Manager when the async
* request is made.
* @property callback
* @type Object
*/
this.callback = {
/**
* The function to execute upon success of the
* Connection submission (when the form does not
* contain a file input element).
*
* @property callback.success
* @type Function
*/
success: null,
/**
* The function to execute upon failure of the
* Connection submission
* @property callback.failure
* @type Function
*/
failure: null,
/**
*<p>
* The function to execute upon success of the
* Connection submission, when the form contains
* a file input element.
* </p>
* <p>
* <em>NOTE:</em> Connection manager will not
* invoke the success or failure handlers for the file
* upload use case. This will be the only callback
* handler invoked.
* </p>
* <p>
* For more information, see the <a href="http://developer.yahoo.com/yui/connection/#file">
* Connection Manager documenation on file uploads</a>.
* </p>
* @property callback.upload
* @type Function
*/
/**
* The arbitrary argument or arguments to pass to the Connection
* callback functions
* @property callback.argument
* @type Object
*/
argument: null
};
// Add form dialog config properties //
/**
* The method to use for posting the Dialog's form. Possible values
* are "async", "form", and "manual".
* @config postmethod
* @type String
* @default async
*/
this.cfg.addProperty(DEFAULT_CONFIG.POST_METHOD.key, {
handler: this.configPostMethod,
value: DEFAULT_CONFIG.POST_METHOD.value,
validator: function (val) {
if (val != "form" && val != "async" && val != "none" &&
val != "manual") {
return false;
} else {
return true;
}
}
});
/**
* Any additional post data which needs to be sent when using the
* <a href="#config_postmethod">async</a> postmethod for dialog POST submissions.
* The format for the post data string is defined by Connection Manager's
* <a href="YAHOO.util.Connect.html#method_asyncRequest">asyncRequest</a>
* method.
* @config postdata
* @type String
* @default null
*/
this.cfg.addProperty(DEFAULT_CONFIG.POST_DATA.key, {
value: DEFAULT_CONFIG.POST_DATA.value
});
/**
* This property is used to configure whether or not the
* dialog should be automatically hidden after submit.
*
* @config hideaftersubmit
* @type Boolean
* @default true
*/
this.cfg.addProperty(DEFAULT_CONFIG.HIDEAFTERSUBMIT.key, {
value: DEFAULT_CONFIG.HIDEAFTERSUBMIT.value
});
/**
* Array of object literals, each containing a set of properties
* defining a button to be appended into the Dialog's footer.
*
* <p>Each button object in the buttons array can have three properties:</p>
* <dl>
* <dt>text:</dt>
* <dd>
* The text that will display on the face of the button. The text can
* include HTML, as long as it is compliant with HTML Button specifications. The text is added to the DOM as HTML,
* and should be escaped by the implementor if coming from an external source.
* </dd>
* <dt>handler:</dt>
* <dd>Can be either:
* <ol>
* <li>A reference to a function that should fire when the
* button is clicked. (In this case scope of this function is
* always its Dialog instance.)</li>
*
* <li>An object literal representing the code to be
* executed when the button is clicked.
*
* <p>Format:</p>
*
* <p>
* <code>{
* <br>
* <strong>fn:</strong> Function, //
* The handler to call when the event fires.
* <br>
* <strong>obj:</strong> Object, //
* An object to pass back to the handler.
* <br>
* <strong>scope:</strong> Object //
* The object to use for the scope of the handler.
* <br>
* }</code>
* </p>
* </li>
* </ol>
* </dd>
* <dt>isDefault:</dt>
* <dd>
* An optional boolean value that specifies that a button
* should be highlighted and focused by default.
* </dd>
* </dl>
*
* <em>NOTE:</em>If the YUI Button Widget is included on the page,
* the buttons created will be instances of YAHOO.widget.Button.
* Otherwise, HTML Buttons (<code><BUTTON></code>) will be
* created.
*
* @config buttons
* @type {Array|String}
* @default "none"
*/
this.cfg.addProperty(DEFAULT_CONFIG.BUTTONS.key, {
handler: this.configButtons,
value: DEFAULT_CONFIG.BUTTONS.value,
supercedes : DEFAULT_CONFIG.BUTTONS.supercedes
});
},
/**
* Initializes the custom events for Dialog which are fired
* automatically at appropriate times by the Dialog class.
* @method initEvents
*/
initEvents: function () {
Dialog.superclass.initEvents.call(this);
var SIGNATURE = CustomEvent.LIST;
/**
* CustomEvent fired prior to submission
* @event beforeSubmitEvent
*/
this.beforeSubmitEvent =
this.createEvent(EVENT_TYPES.BEFORE_SUBMIT);
this.beforeSubmitEvent.signature = SIGNATURE;
/**
* CustomEvent fired after submission
* @event submitEvent
*/
this.submitEvent = this.createEvent(EVENT_TYPES.SUBMIT);
this.submitEvent.signature = SIGNATURE;
/**
* CustomEvent fired for manual submission, before the generic submit event is fired
* @event manualSubmitEvent
*/
this.manualSubmitEvent =
this.createEvent(EVENT_TYPES.MANUAL_SUBMIT);
this.manualSubmitEvent.signature = SIGNATURE;
/**
* CustomEvent fired after asynchronous submission, before the generic submit event is fired
*
* @event asyncSubmitEvent
* @param {Object} conn The connection object, returned by YAHOO.util.Connect.asyncRequest
*/
this.asyncSubmitEvent = this.createEvent(EVENT_TYPES.ASYNC_SUBMIT);
this.asyncSubmitEvent.signature = SIGNATURE;
/**
* CustomEvent fired after form-based submission, before the generic submit event is fired
* @event formSubmitEvent
*/
this.formSubmitEvent = this.createEvent(EVENT_TYPES.FORM_SUBMIT);
this.formSubmitEvent.signature = SIGNATURE;
/**
* CustomEvent fired after cancel
* @event cancelEvent
*/
this.cancelEvent = this.createEvent(EVENT_TYPES.CANCEL);
this.cancelEvent.signature = SIGNATURE;
},
/**
* The Dialog initialization method, which is executed for Dialog and
* all of its subclasses. This method is automatically called by the
* constructor, and sets up all DOM references for pre-existing markup,
* and creates required markup if it is not already present.
*
* @method init
* @param {String} el The element ID representing the Dialog <em>OR</em>
* @param {HTMLElement} el The element representing the Dialog
* @param {Object} userConfig The configuration object literal
* containing the configuration that should be set for this Dialog.
* See configuration documentation for more details.
*/
init: function (el, userConfig) {
/*
Note that we don't pass the user config in here yet because
we only want it executed once, at the lowest subclass level
*/
Dialog.superclass.init.call(this, el/*, userConfig*/);
this.beforeInitEvent.fire(Dialog);
Dom.addClass(this.element, Dialog.CSS_DIALOG);
this.cfg.setProperty("visible", false);
if (userConfig) {
this.cfg.applyConfig(userConfig, true);
}
//this.showEvent.subscribe(this.focusFirst, this, true);
this.beforeHideEvent.subscribe(this.blurButtons, this, true);
this.subscribe("changeBody", this.registerForm);
this.initEvent.fire(Dialog);
},
/**
* Submits the Dialog's form depending on the value of the
* "postmethod" configuration property. <strong>Please note:
* </strong> As of version 2.3 this method will automatically handle
* asyncronous file uploads should the Dialog instance's form contain
* <code><input type="file"></code> elements. If a Dialog
* instance will be handling asyncronous file uploads, its
* <code>callback</code> property will need to be setup with a
* <code>upload</code> handler rather than the standard
* <code>success</code> and, or <code>failure</code> handlers. For more
* information, see the <a href="http://developer.yahoo.com/yui/
* connection/#file">Connection Manager documenation on file uploads</a>.
* @method doSubmit
*/
doSubmit: function () {
var Connect = YAHOO.util.Connect,
oForm = this.form,
bUseFileUpload = false,
bUseSecureFileUpload = false,
aElements,
nElements,
i,
formAttrs;
switch (this.cfg.getProperty("postmethod")) {
case "async":
aElements = oForm.elements;
nElements = aElements.length;
if (nElements > 0) {
i = nElements - 1;
do {
if (aElements[i].type == "file") {
bUseFileUpload = true;
break;
}
}
while(i--);
}
if (bUseFileUpload && YAHOO.env.ua.ie && this.isSecure) {
bUseSecureFileUpload = true;
}
formAttrs = this._getFormAttributes(oForm);
Connect.setForm(oForm, bUseFileUpload, bUseSecureFileUpload);
var postData = this.cfg.getProperty("postdata");
var c = Connect.asyncRequest(formAttrs.method, formAttrs.action, this.callback, postData);
this.asyncSubmitEvent.fire(c);
break;
case "form":
oForm.submit();
this.formSubmitEvent.fire();
break;
case "none":
case "manual":
this.manualSubmitEvent.fire();
break;
}
},
/**
* Retrieves important attributes (currently method and action) from
* the form element, accounting for any elements which may have the same name
* as the attributes. Defaults to "POST" and "" for method and action respectively
* if the attribute cannot be retrieved.
*
* @method _getFormAttributes
* @protected
* @param {HTMLFormElement} oForm The HTML Form element from which to retrieve the attributes
* @return {Object} Object literal, with method and action String properties.
*/
_getFormAttributes : function(oForm){
var attrs = {
method : null,
action : null
};
if (oForm) {
if (oForm.getAttributeNode) {
var action = oForm.getAttributeNode("action");
var method = oForm.getAttributeNode("method");
if (action) {
attrs.action = action.value;
}
if (method) {
attrs.method = method.value;
}
} else {
attrs.action = oForm.getAttribute("action");
attrs.method = oForm.getAttribute("method");
}
}
attrs.method = (Lang.isString(attrs.method) ? attrs.method : "POST").toUpperCase();
attrs.action = Lang.isString(attrs.action) ? attrs.action : "";
return attrs;
},
/**
* Prepares the Dialog's internal FORM object, creating one if one is
* not currently present.
* @method registerForm
*/
registerForm: function() {
var form = this.element.getElementsByTagName("form")[0];
if (this.form) {
if (this.form == form && Dom.isAncestor(this.element, this.form)) {
return;
} else {
Event.purgeElement(this.form);
this.form = null;
}
}
if (!form) {
form = document.createElement("form");
form.name = "frm_" + this.id;
this.body.appendChild(form);
}
if (form) {
this.form = form;
Event.on(form, "submit", this._submitHandler, this, true);
}
},
/**
* Internal handler for the form submit event
*
* @method _submitHandler
* @protected
* @param {DOMEvent} e The DOM Event object
*/
_submitHandler : function(e) {
Event.stopEvent(e);
this.submit();
this.form.blur();
},
/**
* Sets up a tab, shift-tab loop between the first and last elements
* provided. NOTE: Sets up the preventBackTab and preventTabOut KeyListener
* instance properties, which are reset everytime this method is invoked.
*
* @method setTabLoop
* @param {HTMLElement} firstElement
* @param {HTMLElement} lastElement
*
*/
setTabLoop : function(firstElement, lastElement) {
firstElement = firstElement || this.firstButton;
lastElement = lastElement || this.lastButton;
Dialog.superclass.setTabLoop.call(this, firstElement, lastElement);
},
/**
* Protected internal method for setTabLoop, which can be used by
* subclasses to jump in and modify the arguments passed in if required.
*
* @method _setTabLoop
* @param {HTMLElement} firstElement
* @param {HTMLElement} lastElement
* @protected
*/
_setTabLoop : function(firstElement, lastElement) {
firstElement = firstElement || this.firstButton;
lastElement = this.lastButton || lastElement;
this.setTabLoop(firstElement, lastElement);
},
/**
* Configures instance properties, pointing to the
* first and last focusable elements in the Dialog's form.
*
* @method setFirstLastFocusable
*/
setFirstLastFocusable : function() {
Dialog.superclass.setFirstLastFocusable.call(this);
var i, l, el, elements = this.focusableElements;
this.firstFormElement = null;
this.lastFormElement = null;
if (this.form && elements && elements.length > 0) {
l = elements.length;
for (i = 0; i < l; ++i) {
el = elements[i];
if (this.form === el.form) {
this.firstFormElement = el;
break;
}
}
for (i = l-1; i >= 0; --i) {
el = elements[i];
if (this.form === el.form) {
this.lastFormElement = el;
break;
}
}
}
},
// BEGIN BUILT-IN PROPERTY EVENT HANDLERS //
/**
* The default event handler fired when the "close" property is
* changed. The method controls the appending or hiding of the close
* icon at the top right of the Dialog.
* @method configClose
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For
* configuration handlers, args[0] will equal the newly applied value
* for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configClose: function (type, args, obj) {
Dialog.superclass.configClose.apply(this, arguments);
},
/**
* Event handler for the close icon
*
* @method _doClose
* @protected
*
* @param {DOMEvent} e
*/
_doClose : function(e) {
Event.preventDefault(e);
this.cancel();
},
/**
* The default event handler for the "buttons" configuration property
* @method configButtons
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configButtons: function (type, args, obj) {
var Button = YAHOO.widget.Button,
aButtons = args[0],
oInnerElement = this.innerElement,
oButton,
oButtonEl,
oYUIButton,
nButtons,
oSpan,
oFooter,
i;
removeButtonEventHandlers.call(this);
this._aButtons = null;
if (Lang.isArray(aButtons)) {
oSpan = document.createElement("span");
oSpan.className = "button-group";
nButtons = aButtons.length;
this._aButtons = [];
this.defaultHtmlButton = null;
for (i = 0; i < nButtons; i++) {
oButton = aButtons[i];
if (Button) {
oYUIButton = new Button({ label: oButton.text, type:oButton.type });
oYUIButton.appendTo(oSpan);
oButtonEl = oYUIButton.get("element");
if (oButton.isDefault) {
oYUIButton.addClass("default");
this.defaultHtmlButton = oButtonEl;
}
if (Lang.isFunction(oButton.handler)) {
oYUIButton.set("onclick", {
fn: oButton.handler,
obj: this,
scope: this
});
} else if (Lang.isObject(oButton.handler) && Lang.isFunction(oButton.handler.fn)) {
oYUIButton.set("onclick", {
fn: oButton.handler.fn,
obj: ((!Lang.isUndefined(oButton.handler.obj)) ? oButton.handler.obj : this),
scope: (oButton.handler.scope || this)
});
}
this._aButtons[this._aButtons.length] = oYUIButton;
} else {
oButtonEl = document.createElement("button");
oButtonEl.setAttribute("type", "button");
if (oButton.isDefault) {
oButtonEl.className = "default";
this.defaultHtmlButton = oButtonEl;
}
oButtonEl.innerHTML = oButton.text;
if (Lang.isFunction(oButton.handler)) {
Event.on(oButtonEl, "click", oButton.handler, this, true);
} else if (Lang.isObject(oButton.handler) &&
Lang.isFunction(oButton.handler.fn)) {
Event.on(oButtonEl, "click",
oButton.handler.fn,
((!Lang.isUndefined(oButton.handler.obj)) ? oButton.handler.obj : this),
(oButton.handler.scope || this));
}
oSpan.appendChild(oButtonEl);
this._aButtons[this._aButtons.length] = oButtonEl;
}
oButton.htmlButton = oButtonEl;
if (i === 0) {
this.firstButton = oButtonEl;
}
if (i == (nButtons - 1)) {
this.lastButton = oButtonEl;
}
}
this.setFooter(oSpan);
oFooter = this.footer;
if (Dom.inDocument(this.element) && !Dom.isAncestor(oInnerElement, oFooter)) {
oInnerElement.appendChild(oFooter);
}
this.buttonSpan = oSpan;
} else { // Do cleanup
oSpan = this.buttonSpan;
oFooter = this.footer;
if (oSpan && oFooter) {
oFooter.removeChild(oSpan);
this.buttonSpan = null;
this.firstButton = null;
this.lastButton = null;
this.defaultHtmlButton = null;
}
}
this.changeContentEvent.fire();
},
/**
* @method getButtons
* @description Returns an array containing each of the Dialog's
* buttons, by default an array of HTML <code><BUTTON></code>
* elements. If the Dialog's buttons were created using the
* YAHOO.widget.Button class (via the inclusion of the optional Button
* dependency on the page), an array of YAHOO.widget.Button instances
* is returned.
* @return {Array}
*/
getButtons: function () {
return this._aButtons || null;
},
/**
* <p>
* Sets focus to the first focusable element in the Dialog's form if found,
* else, the default button if found, else the first button defined via the
* "buttons" configuration property.
* </p>
* <p>
* This method is invoked when the Dialog is made visible.
* </p>
* @method focusFirst
* @return {Boolean} true, if focused. false if not
*/
focusFirst: function (type, args, obj) {
var el = this.firstFormElement,
focused = false;
if (args && args[1]) {
Event.stopEvent(args[1]);
// When tabbing here, use firstElement instead of firstFormElement
if (args[0] === 9 && this.firstElement) {
el = this.firstElement;
}
}
if (el) {
try {
el.focus();
focused = true;
} catch(oException) {
// Ignore
}
} else {
if (this.defaultHtmlButton) {
focused = this.focusDefaultButton();
} else {
focused = this.focusFirstButton();
}
}
return focused;
},
/**
* Sets focus to the last element in the Dialog's form or the last
* button defined via the "buttons" configuration property.
* @method focusLast
* @return {Boolean} true, if focused. false if not
*/
focusLast: function (type, args, obj) {
var aButtons = this.cfg.getProperty("buttons"),
el = this.lastFormElement,
focused = false;
if (args && args[1]) {
Event.stopEvent(args[1]);
// When tabbing here, use lastElement instead of lastFormElement
if (args[0] === 9 && this.lastElement) {
el = this.lastElement;
}
}
if (aButtons && Lang.isArray(aButtons)) {
focused = this.focusLastButton();
} else {
if (el) {
try {
el.focus();
focused = true;
} catch(oException) {
// Ignore
}
}
}
return focused;
},
/**
* Helper method to normalize button references. It either returns the
* YUI Button instance for the given element if found,
* or the passes back the HTMLElement reference if a corresponding YUI Button
* reference is not found or YAHOO.widget.Button does not exist on the page.
*
* @method _getButton
* @private
* @param {HTMLElement} button
* @return {YAHOO.widget.Button|HTMLElement}
*/
_getButton : function(button) {
var Button = YAHOO.widget.Button;
// If we have an HTML button and YUI Button is on the page,
// get the YUI Button reference if available.
if (Button && button && button.nodeName && button.id) {
button = Button.getButton(button.id) || button;
}
return button;
},
/**
* Sets the focus to the button that is designated as the default via
* the "buttons" configuration property. By default, this method is
* called when the Dialog is made visible.
* @method focusDefaultButton
* @return {Boolean} true if focused, false if not
*/
focusDefaultButton: function () {
var button = this._getButton(this.defaultHtmlButton),
focused = false;
if (button) {
/*
Place the call to the "focus" method inside a try/catch
block to prevent IE from throwing JavaScript errors if
the element is disabled or hidden.
*/
try {
button.focus();
focused = true;
} catch(oException) {
}
}
return focused;
},
/**
* Blurs all the buttons defined via the "buttons"
* configuration property.
* @method blurButtons
*/
blurButtons: function () {
var aButtons = this.cfg.getProperty("buttons"),
nButtons,
oButton,
oElement,
i;
if (aButtons && Lang.isArray(aButtons)) {
nButtons = aButtons.length;
if (nButtons > 0) {
i = (nButtons - 1);
do {
oButton = aButtons[i];
if (oButton) {
oElement = this._getButton(oButton.htmlButton);
if (oElement) {
/*
Place the call to the "blur" method inside
a try/catch block to prevent IE from
throwing JavaScript errors if the element
is disabled or hidden.
*/
try {
oElement.blur();
} catch(oException) {
// ignore
}
}
}
} while(i--);
}
}
},
/**
* Sets the focus to the first button created via the "buttons"
* configuration property.
* @method focusFirstButton
* @return {Boolean} true, if focused. false if not
*/
focusFirstButton: function () {
var aButtons = this.cfg.getProperty("buttons"),
oButton,
oElement,
focused = false;
if (aButtons && Lang.isArray(aButtons)) {
oButton = aButtons[0];
if (oButton) {
oElement = this._getButton(oButton.htmlButton);
if (oElement) {
/*
Place the call to the "focus" method inside a
try/catch block to prevent IE from throwing
JavaScript errors if the element is disabled
or hidden.
*/
try {
oElement.focus();
focused = true;
} catch(oException) {
// ignore
}
}
}
}
return focused;
},
/**
* Sets the focus to the last button created via the "buttons"
* configuration property.
* @method focusLastButton
* @return {Boolean} true, if focused. false if not
*/
focusLastButton: function () {
var aButtons = this.cfg.getProperty("buttons"),
nButtons,
oButton,
oElement,
focused = false;
if (aButtons && Lang.isArray(aButtons)) {
nButtons = aButtons.length;
if (nButtons > 0) {
oButton = aButtons[(nButtons - 1)];
if (oButton) {
oElement = this._getButton(oButton.htmlButton);
if (oElement) {
/*
Place the call to the "focus" method inside a
try/catch block to prevent IE from throwing
JavaScript errors if the element is disabled
or hidden.
*/
try {
oElement.focus();
focused = true;
} catch(oException) {
// Ignore
}
}
}
}
}
return focused;
},
/**
* The default event handler for the "postmethod" configuration property
* @method configPostMethod
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For
* configuration handlers, args[0] will equal the newly applied value
* for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configPostMethod: function (type, args, obj) {
this.registerForm();
},
// END BUILT-IN PROPERTY EVENT HANDLERS //
/**
* Built-in function hook for writing a validation function that will
* be checked for a "true" value prior to a submit. This function, as
* implemented by default, always returns true, so it should be
* overridden if validation is necessary.
* @method validate
*/
validate: function () {
return true;
},
/**
* Executes a submit of the Dialog if validation
* is successful. By default the Dialog is hidden
* after submission, but you can set the "hideaftersubmit"
* configuration property to false, to prevent the Dialog
* from being hidden.
*
* @method submit
*/
submit: function () {
if (this.validate()) {
if (this.beforeSubmitEvent.fire()) {
this.doSubmit();
this.submitEvent.fire();
if (this.cfg.getProperty("hideaftersubmit")) {
this.hide();
}
return true;
} else {
return false;
}
} else {
return false;
}
},
/**
* Executes the cancel of the Dialog followed by a hide.
* @method cancel
*/
cancel: function () {
this.cancelEvent.fire();
this.hide();
},
/**
* Returns a JSON-compatible data structure representing the data
* currently contained in the form.
* @method getData
* @return {Object} A JSON object reprsenting the data of the
* current form.
*/
getData: function () {
var oForm = this.form,
aElements,
nTotalElements,
oData,
sName,
oElement,
nElements,
sType,
sTagName,
aOptions,
nOptions,
aValues,
oOption,
oRadio,
oCheckbox,
valueAttr,
i,
n;
function isFormElement(p_oElement) {
var sTag = p_oElement.tagName.toUpperCase();
return ((sTag == "INPUT" || sTag == "TEXTAREA" ||
sTag == "SELECT") && p_oElement.name == sName);
}
if (oForm) {
aElements = oForm.elements;
nTotalElements = aElements.length;
oData = {};
for (i = 0; i < nTotalElements; i++) {
sName = aElements[i].name;
/*
Using "Dom.getElementsBy" to safeguard user from JS
errors that result from giving a form field (or set of
fields) the same name as a native method of a form
(like "submit") or a DOM collection (such as the "item"
method). Originally tried accessing fields via the
"namedItem" method of the "element" collection, but
discovered that it won't return a collection of fields
in Gecko.
*/
oElement = Dom.getElementsBy(isFormElement, "*", oForm);
nElements = oElement.length;
if (nElements > 0) {
if (nElements == 1) {
oElement = oElement[0];
sType = oElement.type;
sTagName = oElement.tagName.toUpperCase();
switch (sTagName) {
case "INPUT":
if (sType == "checkbox") {
oData[sName] = oElement.checked;
} else if (sType != "radio") {
oData[sName] = oElement.value;
}
break;
case "TEXTAREA":
oData[sName] = oElement.value;
break;
case "SELECT":
aOptions = oElement.options;
nOptions = aOptions.length;
aValues = [];
for (n = 0; n < nOptions; n++) {
oOption = aOptions[n];
if (oOption.selected) {
valueAttr = oOption.attributes.value;
aValues[aValues.length] = (valueAttr && valueAttr.specified) ? oOption.value : oOption.text;
}
}
oData[sName] = aValues;
break;
}
} else {
sType = oElement[0].type;
switch (sType) {
case "radio":
for (n = 0; n < nElements; n++) {
oRadio = oElement[n];
if (oRadio.checked) {
oData[sName] = oRadio.value;
break;
}
}
break;
case "checkbox":
aValues = [];
for (n = 0; n < nElements; n++) {
oCheckbox = oElement[n];
if (oCheckbox.checked) {
aValues[aValues.length] = oCheckbox.value;
}
}
oData[sName] = aValues;
break;
}
}
}
}
}
return oData;
},
/**
* Removes the Panel element from the DOM and sets all child elements
* to null.
* @method destroy
* @param {boolean} shallowPurge If true, only the parent element's DOM event listeners are purged. If false, or not provided, all children are also purged of DOM event listeners.
* NOTE: The flag is a "shallowPurge" flag, as opposed to what may be a more intuitive "purgeChildren" flag to maintain backwards compatibility with behavior prior to 2.9.0.
*/
destroy: function (shallowPurge) {
removeButtonEventHandlers.call(this);
this._aButtons = null;
var aForms = this.element.getElementsByTagName("form"),
oForm;
if (aForms.length > 0) {
oForm = aForms[0];
if (oForm) {
Event.purgeElement(oForm);
if (oForm.parentNode) {
oForm.parentNode.removeChild(oForm);
}
this.form = null;
}
}
Dialog.superclass.destroy.call(this, shallowPurge);
},
/**
* Returns a string representation of the object.
* @method toString
* @return {String} The string representation of the Dialog
*/
toString: function () {
return "Dialog " + this.id;
}
});
}());
(function () {
/**
* SimpleDialog is a simple implementation of Dialog that can be used to
* submit a single value. Forms can be processed in 3 ways -- via an
* asynchronous Connection utility call, a simple form POST or GET,
* or manually.
* @namespace YAHOO.widget
* @class SimpleDialog
* @extends YAHOO.widget.Dialog
* @constructor
* @param {String} el The element ID representing the SimpleDialog
* <em>OR</em>
* @param {HTMLElement} el The element representing the SimpleDialog
* @param {Object} userConfig The configuration object literal containing
* the configuration that should be set for this SimpleDialog. See
* configuration documentation for more details.
*/
YAHOO.widget.SimpleDialog = function (el, userConfig) {
YAHOO.widget.SimpleDialog.superclass.constructor.call(this,
el, userConfig);
};
var Dom = YAHOO.util.Dom,
SimpleDialog = YAHOO.widget.SimpleDialog,
/**
* Constant representing the SimpleDialog's configuration properties
* @property DEFAULT_CONFIG
* @private
* @final
* @type Object
*/
DEFAULT_CONFIG = {
"ICON": {
key: "icon",
value: "none",
suppressEvent: true
},
"TEXT": {
key: "text",
value: "",
suppressEvent: true,
supercedes: ["icon"]
}
};
/**
* Constant for the standard network icon for a blocking action
* @property YAHOO.widget.SimpleDialog.ICON_BLOCK
* @static
* @final
* @type String
*/
SimpleDialog.ICON_BLOCK = "blckicon";
/**
* Constant for the standard network icon for alarm
* @property YAHOO.widget.SimpleDialog.ICON_ALARM
* @static
* @final
* @type String
*/
SimpleDialog.ICON_ALARM = "alrticon";
/**
* Constant for the standard network icon for help
* @property YAHOO.widget.SimpleDialog.ICON_HELP
* @static
* @final
* @type String
*/
SimpleDialog.ICON_HELP = "hlpicon";
/**
* Constant for the standard network icon for info
* @property YAHOO.widget.SimpleDialog.ICON_INFO
* @static
* @final
* @type String
*/
SimpleDialog.ICON_INFO = "infoicon";
/**
* Constant for the standard network icon for warn
* @property YAHOO.widget.SimpleDialog.ICON_WARN
* @static
* @final
* @type String
*/
SimpleDialog.ICON_WARN = "warnicon";
/**
* Constant for the standard network icon for a tip
* @property YAHOO.widget.SimpleDialog.ICON_TIP
* @static
* @final
* @type String
*/
SimpleDialog.ICON_TIP = "tipicon";
/**
* Constant representing the name of the CSS class applied to the element
* created by the "icon" configuration property.
* @property YAHOO.widget.SimpleDialog.ICON_CSS_CLASSNAME
* @static
* @final
* @type String
*/
SimpleDialog.ICON_CSS_CLASSNAME = "yui-icon";
/**
* Constant representing the default CSS class used for a SimpleDialog
* @property YAHOO.widget.SimpleDialog.CSS_SIMPLEDIALOG
* @static
* @final
* @type String
*/
SimpleDialog.CSS_SIMPLEDIALOG = "yui-simple-dialog";
YAHOO.extend(SimpleDialog, YAHOO.widget.Dialog, {
/**
* Initializes the class's configurable properties which can be changed
* using the SimpleDialog's Config object (cfg).
* @method initDefaultConfig
*/
initDefaultConfig: function () {
SimpleDialog.superclass.initDefaultConfig.call(this);
// Add dialog config properties //
/**
* Sets the informational icon for the SimpleDialog
* @config icon
* @type String
* @default "none"
*/
this.cfg.addProperty(DEFAULT_CONFIG.ICON.key, {
handler: this.configIcon,
value: DEFAULT_CONFIG.ICON.value,
suppressEvent: DEFAULT_CONFIG.ICON.suppressEvent
});
/**
* Sets the text for the SimpleDialog. The text is inserted into the DOM as HTML, and should be escaped by the implementor if coming from an external source.
* @config text
* @type HTML
* @default ""
*/
this.cfg.addProperty(DEFAULT_CONFIG.TEXT.key, {
handler: this.configText,
value: DEFAULT_CONFIG.TEXT.value,
suppressEvent: DEFAULT_CONFIG.TEXT.suppressEvent,
supercedes: DEFAULT_CONFIG.TEXT.supercedes
});
},
/**
* The SimpleDialog initialization method, which is executed for
* SimpleDialog and all of its subclasses. This method is automatically
* called by the constructor, and sets up all DOM references for
* pre-existing markup, and creates required markup if it is not
* already present.
* @method init
* @param {String} el The element ID representing the SimpleDialog
* <em>OR</em>
* @param {HTMLElement} el The element representing the SimpleDialog
* @param {Object} userConfig The configuration object literal
* containing the configuration that should be set for this
* SimpleDialog. See configuration documentation for more details.
*/
init: function (el, userConfig) {
/*
Note that we don't pass the user config in here yet because we
only want it executed once, at the lowest subclass level
*/
SimpleDialog.superclass.init.call(this, el/*, userConfig*/);
this.beforeInitEvent.fire(SimpleDialog);
Dom.addClass(this.element, SimpleDialog.CSS_SIMPLEDIALOG);
this.cfg.queueProperty("postmethod", "manual");
if (userConfig) {
this.cfg.applyConfig(userConfig, true);
}
this.beforeRenderEvent.subscribe(function () {
if (! this.body) {
this.setBody("");
}
}, this, true);
this.initEvent.fire(SimpleDialog);
},
/**
* Prepares the SimpleDialog's internal FORM object, creating one if one
* is not currently present, and adding the value hidden field.
* @method registerForm
*/
registerForm: function () {
SimpleDialog.superclass.registerForm.call(this);
var doc = this.form.ownerDocument,
input = doc.createElement("input");
input.type = "hidden";
input.name = this.id;
input.value = "";
this.form.appendChild(input);
},
// BEGIN BUILT-IN PROPERTY EVENT HANDLERS //
/**
* Fired when the "icon" property is set.
* @method configIcon
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configIcon: function (type,args,obj) {
var sIcon = args[0],
oBody = this.body,
sCSSClass = SimpleDialog.ICON_CSS_CLASSNAME,
aElements,
oIcon,
oIconParent;
if (sIcon && sIcon != "none") {
aElements = Dom.getElementsByClassName(sCSSClass, "*" , oBody);
if (aElements.length === 1) {
oIcon = aElements[0];
oIconParent = oIcon.parentNode;
if (oIconParent) {
oIconParent.removeChild(oIcon);
oIcon = null;
}
}
if (sIcon.indexOf(".") == -1) {
oIcon = document.createElement("span");
oIcon.className = (sCSSClass + " " + sIcon);
oIcon.innerHTML = " ";
} else {
oIcon = document.createElement("img");
oIcon.src = (this.imageRoot + sIcon);
oIcon.className = sCSSClass;
}
if (oIcon) {
oBody.insertBefore(oIcon, oBody.firstChild);
}
}
},
/**
* Fired when the "text" property is set.
* @method configText
* @param {String} type The CustomEvent type (usually the property name)
* @param {Object[]} args The CustomEvent arguments. For configuration
* handlers, args[0] will equal the newly applied value for the property.
* @param {Object} obj The scope object. For configuration handlers,
* this will usually equal the owner.
*/
configText: function (type,args,obj) {
var text = args[0];
if (text) {
this.setBody(text);
this.cfg.refireEvent("icon");
}
},
// END BUILT-IN PROPERTY EVENT HANDLERS //
/**
* Returns a string representation of the object.
* @method toString
* @return {String} The string representation of the SimpleDialog
*/
toString: function () {
return "SimpleDialog " + this.id;
}
/**
* <p>
* Sets the SimpleDialog's body content to the HTML specified.
* If no body is present, one will be automatically created.
* An empty string can be passed to the method to clear the contents of the body.
* </p>
* <p><strong>NOTE:</strong> SimpleDialog provides the <a href="#config_text">text</a>
* and <a href="#config_icon">icon</a> configuration properties to set the contents
* of it's body element in accordance with the UI design for a SimpleDialog (an
* icon and message text). Calling setBody on the SimpleDialog will not enforce this
* UI design constraint and will replace the entire contents of the SimpleDialog body.
* It should only be used if you wish the replace the default icon/text body structure
* of a SimpleDialog with your own custom markup.</p>
*
* @method setBody
* @param {HTML} bodyContent The HTML used to set the body.
* As a convenience, non HTMLElement objects can also be passed into
* the method, and will be treated as strings, with the body innerHTML
* set to their default toString implementations.
*
* <p>NOTE: Markup passed into this method is added to the DOM as HTML, and should be escaped by the implementor if coming from an external source.</p>
*
* <em>OR</em>
* @param {HTMLElement} bodyContent The HTMLElement to add as the first and only child of the body element.
* <em>OR</em>
* @param {DocumentFragment} bodyContent The document fragment
* containing elements which are to be added to the body
*/
});
}());
(function () {
/**
* ContainerEffect encapsulates animation transitions that are executed when
* an Overlay is shown or hidden.
* @namespace YAHOO.widget
* @class ContainerEffect
* @constructor
* @param {YAHOO.widget.Overlay} overlay The Overlay that the animation
* should be associated with
* @param {Object} attrIn The object literal representing the animation
* arguments to be used for the animate-in transition. The arguments for
* this literal are: attributes(object, see YAHOO.util.Anim for description),
* duration(Number), and method(i.e. Easing.easeIn).
* @param {Object} attrOut The object literal representing the animation
* arguments to be used for the animate-out transition. The arguments for
* this literal are: attributes(object, see YAHOO.util.Anim for description),
* duration(Number), and method(i.e. Easing.easeIn).
* @param {HTMLElement} targetElement Optional. The target element that
* should be animated during the transition. Defaults to overlay.element.
* @param {class} Optional. The animation class to instantiate. Defaults to
* YAHOO.util.Anim. Other options include YAHOO.util.Motion.
*/
YAHOO.widget.ContainerEffect = function (overlay, attrIn, attrOut, targetElement, animClass) {
if (!animClass) {
animClass = YAHOO.util.Anim;
}
/**
* The overlay to animate
* @property overlay
* @type YAHOO.widget.Overlay
*/
this.overlay = overlay;
/**
* The animation attributes to use when transitioning into view
* @property attrIn
* @type Object
*/
this.attrIn = attrIn;
/**
* The animation attributes to use when transitioning out of view
* @property attrOut
* @type Object
*/
this.attrOut = attrOut;
/**
* The target element to be animated
* @property targetElement
* @type HTMLElement
*/
this.targetElement = targetElement || overlay.element;
/**
* The animation class to use for animating the overlay
* @property animClass
* @type class
*/
this.animClass = animClass;
};
var Dom = YAHOO.util.Dom,
CustomEvent = YAHOO.util.CustomEvent,
ContainerEffect = YAHOO.widget.ContainerEffect;
/**
* A pre-configured ContainerEffect instance that can be used for fading
* an overlay in and out.
* @method FADE
* @static
* @param {YAHOO.widget.Overlay} overlay The Overlay object to animate
* @param {Number} dur The duration of the animation
* @return {YAHOO.widget.ContainerEffect} The configured ContainerEffect object
*/
ContainerEffect.FADE = function (overlay, dur) {
var Easing = YAHOO.util.Easing,
fin = {
attributes: {opacity:{from:0, to:1}},
duration: dur,
method: Easing.easeIn
},
fout = {
attributes: {opacity:{to:0}},
duration: dur,
method: Easing.easeOut
},
fade = new ContainerEffect(overlay, fin, fout, overlay.element);
fade.handleUnderlayStart = function() {
var underlay = this.overlay.underlay;
if (underlay && YAHOO.env.ua.ie) {
var hasFilters = (underlay.filters && underlay.filters.length > 0);
if(hasFilters) {
Dom.addClass(overlay.element, "yui-effect-fade");
}
}
};
fade.handleUnderlayComplete = function() {
var underlay = this.overlay.underlay;
if (underlay && YAHOO.env.ua.ie) {
Dom.removeClass(overlay.element, "yui-effect-fade");
}
};
fade.handleStartAnimateIn = function (type, args, obj) {
obj.overlay._fadingIn = true;
Dom.addClass(obj.overlay.element, "hide-select");
if (!obj.overlay.underlay) {
obj.overlay.cfg.refireEvent("underlay");
}
obj.handleUnderlayStart();
obj.overlay._setDomVisibility(true);
Dom.setStyle(obj.overlay.element, "opacity", 0);
};
fade.handleCompleteAnimateIn = function (type,args,obj) {
obj.overlay._fadingIn = false;
Dom.removeClass(obj.overlay.element, "hide-select");
if (obj.overlay.element.style.filter) {
obj.overlay.element.style.filter = null;
}
obj.handleUnderlayComplete();
obj.overlay.cfg.refireEvent("iframe");
obj.animateInCompleteEvent.fire();
};
fade.handleStartAnimateOut = function (type, args, obj) {
obj.overlay._fadingOut = true;
Dom.addClass(obj.overlay.element, "hide-select");
obj.handleUnderlayStart();
};
fade.handleCompleteAnimateOut = function (type, args, obj) {
obj.overlay._fadingOut = false;
Dom.removeClass(obj.overlay.element, "hide-select");
if (obj.overlay.element.style.filter) {
obj.overlay.element.style.filter = null;
}
obj.overlay._setDomVisibility(false);
Dom.setStyle(obj.overlay.element, "opacity", 1);
obj.handleUnderlayComplete();
obj.overlay.cfg.refireEvent("iframe");
obj.animateOutCompleteEvent.fire();
};
fade.init();
return fade;
};
/**
* A pre-configured ContainerEffect instance that can be used for sliding an
* overlay in and out.
* @method SLIDE
* @static
* @param {YAHOO.widget.Overlay} overlay The Overlay object to animate
* @param {Number} dur The duration of the animation
* @return {YAHOO.widget.ContainerEffect} The configured ContainerEffect object
*/
ContainerEffect.SLIDE = function (overlay, dur) {
var Easing = YAHOO.util.Easing,
x = overlay.cfg.getProperty("x") || Dom.getX(overlay.element),
y = overlay.cfg.getProperty("y") || Dom.getY(overlay.element),
clientWidth = Dom.getClientWidth(),
offsetWidth = overlay.element.offsetWidth,
sin = {
attributes: { points: { to: [x, y] } },
duration: dur,
method: Easing.easeIn
},
sout = {
attributes: { points: { to: [(clientWidth + 25), y] } },
duration: dur,
method: Easing.easeOut
},
slide = new ContainerEffect(overlay, sin, sout, overlay.element, YAHOO.util.Motion);
slide.handleStartAnimateIn = function (type,args,obj) {
obj.overlay.element.style.left = ((-25) - offsetWidth) + "px";
obj.overlay.element.style.top = y + "px";
};
slide.handleTweenAnimateIn = function (type, args, obj) {
var pos = Dom.getXY(obj.overlay.element),
currentX = pos[0],
currentY = pos[1];
if (Dom.getStyle(obj.overlay.element, "visibility") ==
"hidden" && currentX < x) {
obj.overlay._setDomVisibility(true);
}
obj.overlay.cfg.setProperty("xy", [currentX, currentY], true);
obj.overlay.cfg.refireEvent("iframe");
};
slide.handleCompleteAnimateIn = function (type, args, obj) {
obj.overlay.cfg.setProperty("xy", [x, y], true);
obj.startX = x;
obj.startY = y;
obj.overlay.cfg.refireEvent("iframe");
obj.animateInCompleteEvent.fire();
};
slide.handleStartAnimateOut = function (type, args, obj) {
var vw = Dom.getViewportWidth(),
pos = Dom.getXY(obj.overlay.element),
yso = pos[1];
obj.animOut.attributes.points.to = [(vw + 25), yso];
};
slide.handleTweenAnimateOut = function (type, args, obj) {
var pos = Dom.getXY(obj.overlay.element),
xto = pos[0],
yto = pos[1];
obj.overlay.cfg.setProperty("xy", [xto, yto], true);
obj.overlay.cfg.refireEvent("iframe");
};
slide.handleCompleteAnimateOut = function (type, args, obj) {
obj.overlay._setDomVisibility(false);
obj.overlay.cfg.setProperty("xy", [x, y]);
obj.animateOutCompleteEvent.fire();
};
slide.init();
return slide;
};
ContainerEffect.prototype = {
/**
* Initializes the animation classes and events.
* @method init
*/
init: function () {
this.beforeAnimateInEvent = this.createEvent("beforeAnimateIn");
this.beforeAnimateInEvent.signature = CustomEvent.LIST;
this.beforeAnimateOutEvent = this.createEvent("beforeAnimateOut");
this.beforeAnimateOutEvent.signature = CustomEvent.LIST;
this.animateInCompleteEvent = this.createEvent("animateInComplete");
this.animateInCompleteEvent.signature = CustomEvent.LIST;
this.animateOutCompleteEvent = this.createEvent("animateOutComplete");
this.animateOutCompleteEvent.signature = CustomEvent.LIST;
this.animIn = new this.animClass(
this.targetElement,
this.attrIn.attributes,
this.attrIn.duration,
this.attrIn.method);
this.animIn.onStart.subscribe(this.handleStartAnimateIn, this);
this.animIn.onTween.subscribe(this.handleTweenAnimateIn, this);
this.animIn.onComplete.subscribe(this.handleCompleteAnimateIn,this);
this.animOut = new this.animClass(
this.targetElement,
this.attrOut.attributes,
this.attrOut.duration,
this.attrOut.method);
this.animOut.onStart.subscribe(this.handleStartAnimateOut, this);
this.animOut.onTween.subscribe(this.handleTweenAnimateOut, this);
this.animOut.onComplete.subscribe(this.handleCompleteAnimateOut, this);
},
/**
* Triggers the in-animation.
* @method animateIn
*/
animateIn: function () {
this._stopAnims(this.lastFrameOnStop);
this.beforeAnimateInEvent.fire();
this.animIn.animate();
},
/**
* Triggers the out-animation.
* @method animateOut
*/
animateOut: function () {
this._stopAnims(this.lastFrameOnStop);
this.beforeAnimateOutEvent.fire();
this.animOut.animate();
},
/**
* Flag to define whether Anim should jump to the last frame,
* when animateIn or animateOut is stopped.
*
* @property lastFrameOnStop
* @default true
* @type boolean
*/
lastFrameOnStop : true,
/**
* Stops both animIn and animOut instances, if in progress.
*
* @method _stopAnims
* @param {boolean} finish If true, animation will jump to final frame.
* @protected
*/
_stopAnims : function(finish) {
if (this.animOut && this.animOut.isAnimated()) {
this.animOut.stop(finish);
}
if (this.animIn && this.animIn.isAnimated()) {
this.animIn.stop(finish);
}
},
/**
* The default onStart handler for the in-animation.
* @method handleStartAnimateIn
* @param {String} type The CustomEvent type
* @param {Object[]} args The CustomEvent arguments
* @param {Object} obj The scope object
*/
handleStartAnimateIn: function (type, args, obj) { },
/**
* The default onTween handler for the in-animation.
* @method handleTweenAnimateIn
* @param {String} type The CustomEvent type
* @param {Object[]} args The CustomEvent arguments
* @param {Object} obj The scope object
*/
handleTweenAnimateIn: function (type, args, obj) { },
/**
* The default onComplete handler for the in-animation.
* @method handleCompleteAnimateIn
* @param {String} type The CustomEvent type
* @param {Object[]} args The CustomEvent arguments
* @param {Object} obj The scope object
*/
handleCompleteAnimateIn: function (type, args, obj) { },
/**
* The default onStart handler for the out-animation.
* @method handleStartAnimateOut
* @param {String} type The CustomEvent type
* @param {Object[]} args The CustomEvent arguments
* @param {Object} obj The scope object
*/
handleStartAnimateOut: function (type, args, obj) { },
/**
* The default onTween handler for the out-animation.
* @method handleTweenAnimateOut
* @param {String} type The CustomEvent type
* @param {Object[]} args The CustomEvent arguments
* @param {Object} obj The scope object
*/
handleTweenAnimateOut: function (type, args, obj) { },
/**
* The default onComplete handler for the out-animation.
* @method handleCompleteAnimateOut
* @param {String} type The CustomEvent type
* @param {Object[]} args The CustomEvent arguments
* @param {Object} obj The scope object
*/
handleCompleteAnimateOut: function (type, args, obj) { },
/**
* Returns a string representation of the object.
* @method toString
* @return {String} The string representation of the ContainerEffect
*/
toString: function () {
var output = "ContainerEffect";
if (this.overlay) {
output += " [" + this.overlay.toString() + "]";
}
return output;
}
};
YAHOO.lang.augmentProto(ContainerEffect, YAHOO.util.EventProvider);
})();
YAHOO.register("container", YAHOO.widget.Module, {version: "2.9.0", build: "2800"});
|
src/components/App.js
|
JoshuaTang/OnlineGobang
|
import React, {Component} from 'react';
import Nav from './Nav';
import ControlPanel from '../containers/ControlPanel';
import BoardPanel from '../containers/BoardPanel';
import ModeSelector from '../containers/ModeSelector';
export default class App extends Component {
render() {
return (
<div>
<ModeSelector/>
<Nav/>
<div className="container">
<ControlPanel/>
<BoardPanel/>
</div>
</div>
);
}
}
|
docs/src/components/ComponentDoc/ComponentSidebar/ComponentSidebar.js
|
Semantic-Org/Semantic-UI-React
|
import _ from 'lodash'
import PropTypes from 'prop-types'
import React from 'react'
import { Accordion, Menu, Sticky } from 'semantic-ui-react'
import { docTypes } from 'docs/src/utils'
import ComponentSidebarSection from './ComponentSidebarSection'
const sidebarStyle = {
background: '#fff',
boxShadow: '0 2px 2px rgba(0, 0, 0, 0.1)',
paddingLeft: '1em',
paddingBottom: '0.1em',
paddingTop: '0.1em',
}
const ComponentSidebar = ({ activePath, examplesRef, onItemClick, sections }) => (
<Sticky context={examplesRef} offset={14}>
<Menu as={Accordion} fluid style={sidebarStyle} text vertical>
{_.map(sections, ({ examples, sectionName }) => (
<ComponentSidebarSection
activePath={activePath}
examples={examples}
key={sectionName}
sectionName={sectionName}
onItemClick={onItemClick}
/>
))}
</Menu>
</Sticky>
)
ComponentSidebar.propTypes = {
activePath: PropTypes.string,
examplesRef: PropTypes.object,
onItemClick: PropTypes.func.isRequired,
sections: docTypes.sidebarSections.isRequired,
}
const areEqual = (prevProps, nextProps) => prevProps.activePath === nextProps.activePath
export default React.memo(ComponentSidebar, areEqual)
|
src/d3Charts/scatter.js
|
livingston/react-chart-spikes
|
import React, { Component } from 'react';
import { maxBy, minBy } from 'lodash';
import { scaleLinear } from 'd3-scale';
import { zoom } from 'd3-zoom';
import { select, event as d3Event } from 'd3-selection';
import FlexibleWrapper from '../ui/flexibleWrapper.js';
// Test data
require('chance');
const scatterDatum = () => ({
x: chance.integer({min: 0, max: 1000}),
y: chance.integer({min: 0, max: 1000}),
name: chance.word()
});
const data = Array.apply(null, Array(1000)).map(scatterDatum);
const Dot = ({ point, xScale, yScale, onMouseOver, onMouseOut }) => (<circle onMouseOver={onMouseOver} onMouseOut={onMouseOut}
cx={xScale(point.x)} cy={yScale(point.y)} r={5}
fill="#33adff"
/>);
const XAxis = ({ scale, top, width, left }) => (<g className="axis x-axis" transform={`translate(0, ${top})`}>
<line x1={left} x2={width} y1={0} y2={0} />
{scale.ticks().map(tick => (<g transform={`translate(${scale(tick)}, 0)`} key={tick}>
<line x1={0} x2={0} y1={0} y2={5} />
<text x={0} y={20} dy=".3em" key={tick}>{tick}</text>
</g>))}
</g>)
const YAxis = ({ scale, padding, height, left, top }) => (<g className="axis y-axis" transform={`translate(${padding}, ${top})`}>
<line x1={left} x2={left} y1={padding} y2={height} />
{scale.ticks().map(tick => (<g transform={`translate(0, ${scale(tick)})`} key={tick}>
<line x1={left - 5} x2={left} y1={0} y2={0} />
<text x={left - 10} y={0} dy=".3em" key={tick}>{tick}</text>
</g>))}
</g>)
const axisHeight = 50;
const axisWidth = 50;
const padding = 50;
const yPadding = padding + axisHeight;
class Scatter extends Component {
constructor(props) {
super(props);
const minX = minBy(data, (d) => d.x).x;
const maxX = maxBy(data, (d) => d.x).x;
const minY = minBy(data, (d) => d.y).y;
const maxY = maxBy(data, (d) => d.y).y;
this.xScale = scaleLinear().domain([minX, maxX]);
this.yScale = scaleLinear().domain([minY, maxY]);
this.state = {
width: 500,
height: 500,
currentPoint: null,
xScale: this.xScale,
yScale: this.yScale,
zoomLevel: 1,
zoomFactor: 0.2,
maxZoomLevel: 4,
minZoomLevel: 1
};
}
get filteredData() {
const { xScale, yScale } = this.state;
const [minX, maxX] = xScale.domain();
const [minY, maxY] = yScale.domain();
return data.filter(({ x, y }) => (x >= minX && x <= maxX && y >= minY && y <= maxY));
}
componentDidMount() {
this.updateDimensions();
this.zoom = zoom()
.scaleExtent([this.state.minZoomLevel, this.state.maxZoomLevel])
.on("zoom", this.onZoom);
select(this.chart)
.call(this.zoom)
.on("dblclick.zoom", null);
}
updateDimensions = () => {
const { clientWidth: width, clientHeight: height } = this.node;
this.setState({
width,
height
}, () => {
this.zoom.translateExtent([[0, 0], [width, height]]);
});
}
showPoint = (currentPoint) => {
this.setState({ currentPoint });
}
clearPoint = () => (this.setState({ currentPoint: null }))
onZoom = () => {
const { xScale, yScale } = this;
const updatedXScale = d3Event.transform.rescaleX(xScale);
const updatedYScale = d3Event.transform.rescaleY(yScale);
this.setState({
xScale: updatedXScale,
yScale: updatedYScale,
zoomLevel: d3Event.transform.k
});
}
updateZoomLevel = () => {
this.zoom.scaleTo(select(this.chart), this.state.zoomLevel);
}
zoomIn = () => {
this.setState(state => {
const { zoomFactor, zoomLevel, maxZoomLevel } = state;
if (zoomLevel < maxZoomLevel) {
const zoomIn = zoomLevel * (1 + zoomFactor);
return { zoomLevel: zoomIn };
}
return { zoomLevel: maxZoomLevel };
}, this.updateZoomLevel);
}
zoomOut = () => {
this.setState(state => {
const { zoomFactor, zoomLevel, minZoomLevel } = state;
if (zoomLevel > minZoomLevel) {
const zoomOut = zoomLevel * (1 - zoomFactor);
return { zoomLevel: zoomOut };
}
return { zoomLevel: minZoomLevel };
}, this.updateZoomLevel);
}
render() {
const { width, height, currentPoint, xScale, yScale, zoomLevel, maxZoomLevel, minZoomLevel } = this.state;
xScale.range([padding, width - padding]);
yScale.range([height - axisHeight - padding, padding]);
return (<section className="chart-wrapper d3">
<section className="chart-legend">
<h3>Scatter Plot</h3>
{currentPoint ?
<div className="currentPoint" style={{ backgroundColor: '#33adff' }}>
<div>name: {currentPoint.name}</div>
<div>x: {currentPoint.x}</div>
<div>y: {currentPoint.y}</div>
</div>
: null }
<div className="d3-controls">
<button className="d3-zoom-in" onClick={this.zoomIn} disabled={zoomLevel === maxZoomLevel}>+</button>
<button className="d3-zoom-out" onClick={this.zoomOut} disabled={zoomLevel === minZoomLevel}>-</button>
</div>
</section>
<section className="chart" ref={n => (this.node = n)}>
<FlexibleWrapper onResize={this.updateDimensions}>
<svg width={width} height={height} ref={node => (this.chart = node)}>
<defs>
<clipPath id="scatter-clip"><rect x={padding} y={0} width={width - (padding * 2)} height={height} /></clipPath>
</defs>
<g className="dots" clipPath="url(#scatter-clip)">
{this.filteredData.map((datum, i) => <Dot
point={datum} xScale={xScale} yScale={yScale} key={i}
onMouseOver={() => (this.showPoint(datum))}
onMouseOut={this.clearPoint}
/>)}
</g>
<XAxis scale={xScale} top={height - axisHeight} left={padding} width={width - padding} />
<YAxis scale={yScale} top={padding} left={axisWidth} padding={0} height={height - axisHeight - padding} />
</svg>
</FlexibleWrapper>
</section>
</section>);
}
}
export default Scatter;
|
src/modules/search/components/SearchBar.js
|
nordsoftware/outdoors-sports-map
|
import React from 'react';
import {translate} from 'react-i18next';
import SMIcon from '../../home/components/SMIcon';
const SearchBar = translate()(({input, onInput, onSubmit, onClear, searchActive, disabled, t}) =>
<div className="search-bar">
<form className="search-bar__input" onSubmit={(e) => {e.preventDefault(); onSubmit();}}>
<label htmlFor="search"><SMIcon icon="search"/></label>
{disabled &&
<span className="search-bar__input-loading" onClick={onClear}>
<SMIcon icon="loading"/>
</span>
}
<input name="search"
id="search"
type="text"
onChange={(e) => onInput(e.target.value)}
placeholder={disabled ? ` ${t('GENERAL.LOADING')}` : `${t('SEARCH.SEARCH')}...`}
disabled={disabled}
value={input}
/>
{(input || searchActive) &&
<div className="search-bar__input-clear" onClick={onClear}>
<SMIcon icon="close"/>
</div>
}
</form>
</div>
);
export default SearchBar;
|
src/svg-icons/maps/local-shipping.js
|
ngbrown/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLocalShipping = (props) => (
<SvgIcon {...props}>
<path d="M20 8h-3V4H3c-1.1 0-2 .9-2 2v11h2c0 1.66 1.34 3 3 3s3-1.34 3-3h6c0 1.66 1.34 3 3 3s3-1.34 3-3h2v-5l-3-4zM6 18.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.5zm13.5-9l1.96 2.5H17V9.5h2.5zm-1.5 9c-.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>
);
MapsLocalShipping = pure(MapsLocalShipping);
MapsLocalShipping.displayName = 'MapsLocalShipping';
MapsLocalShipping.muiName = 'SvgIcon';
export default MapsLocalShipping;
|
packages/material-ui-icons/lib/esm/LocalPoliceTwoTone.js
|
mbrookes/material-ui
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon([/*#__PURE__*/_jsx("path", {
d: "M12 3.19 5 6.3V11c0 4.52 2.98 8.69 7 9.93 4.02-1.23 7-5.41 7-9.93V6.3l-7-3.11zm2.5 9.4.9 3.88-3.4-2.05-3.4 2.05.9-3.87-3-2.59 3.96-.34L12 6.02l1.54 3.64 3.96.34-3 2.59z",
opacity: ".3"
}, "0"), /*#__PURE__*/_jsx("path", {
d: "m14.5 12.59.9 3.88-3.4-2.05-3.4 2.05.9-3.87-3-2.59 3.96-.34L12 6.02l1.54 3.64 3.96.34-3 2.59zM12 3.19l7 3.11V11c0 4.52-2.98 8.69-7 9.93-4.02-1.24-7-5.41-7-9.93V6.3l7-3.11M12 1 3 5v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V5l-9-4z"
}, "1")], 'LocalPoliceTwoTone');
|
app/javascript/mastodon/components/area.js
|
pinfort/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
class Area extends React.PureComponent {
static propTypes = {
account: ImmutablePropTypes.map.isRequired
};
constructor (props, context) {
super(props, context);
this.props = props;
var area_data = require("../../area_settings.json");
var areas = area_data['areas'];
this.instances = area_data['instances'];
this.config = [];
areas.forEach(function(data, index, arr) {
this.config[data['area-id']] = data;
}, this);
this.get_area_eng_name = this.get_area_eng_name.bind(this);
this.get_area_short_name = this.get_area_short_name.bind(this);
this.get_local_area_eng_name = this.get_local_area_eng_name.bind(this);
this.get_remote_area_eng_name = this.get_remote_area_eng_name.bind(this);
this.get_local_area_short_name = this.get_local_area_short_name.bind(this);
this.get_remote_area_short_name = this.get_remote_area_short_name.bind(this);
this.is_local = this.is_local.bind(this);
}
get_area_eng_name(account){
if (this.is_local(account)){
return (this.get_local_area_eng_name(account.get('area')));
}else{
return (this.get_remote_area_eng_name(account));
}
}
get_local_area_eng_name(area_id){
if (isNaN(area_id)) {
var area_id = 0;
};
try{
var area_eng_name = this.config[area_id]["area-eng-name"];
} catch (e) {
var area_eng_name = this.config[0]["area-eng-name"];
}
return (area_eng_name);
}
get_remote_area_eng_name(account){
var splittedName = account.get('acct').split('@');
var domain = splittedName[splittedName.length - 1];
try{
var instanceSetting = this.instances[domain];
var area_eng_name = instanceSetting["instance-eng-name"];
}catch (e) {
return this.get_local_area_eng_name(0);
}
return (area_eng_name);
}
get_area_short_name(account){
if (this.is_local(account)){
return (this.get_local_area_short_name(account.get('area')));
}else{
return (this.get_remote_area_short_name(account));
}
}
get_local_area_short_name(area_id){
if (isNaN(area_id)) {
var area_id = 0;
};
try{
var area_short_name = this.config[area_id]["area-short-name"];
} catch (e) {
var area_short_name = this.config[0]["area-short-name"];
}
return (area_short_name);
}
get_remote_area_short_name(account){
var splittedName = account.get('acct').split('@');
var domain = splittedName[splittedName.length - 1];
try{
var instanceSetting = this.instances[domain];
var area_short_name = instanceSetting["instance-short-name"];
}catch (e) {
return this.get_local_area_short_name(0);
}
return (area_short_name);
}
is_local(account){
return (account.get('username') === account.get('acct'));
}
}
export default Area;
|
src/components/Header/Header.js
|
divsbhalala/accelEventsWebApp
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import 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';
import logoUrl2x from './logo-small@2x.png';
class Header extends React.Component {
render() {
return (
<div className={s.root}>
<div className={s.container}>
<Navigation />
<Link className={s.brand} to="/">
<img src={logoUrl} srcSet={`${logoUrl2x} 2x`} 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);
|
frontend/jqwidgets/jqwidgets-react/react_jqxfileupload.js
|
yevgeny-sergeyev/nexl-js
|
/*
jQWidgets v5.7.2 (2018-Apr)
Copyright (c) 2011-2018 jQWidgets.
License: https://jqwidgets.com/license/
*/
import React from 'react';
const JQXLite = window.JQXLite;
export const jqx = window.jqx;
export default class JqxFileUpload extends React.Component {
componentDidMount() {
let options = this.manageAttributes();
this.createComponent(options);
};
manageAttributes() {
let properties = ['autoUpload','accept','browseTemplate','cancelTemplate','disabled','fileInputName','height','localization','multipleFilesUpload','renderFiles','rtl','theme','uploadUrl','uploadTemplate','width'];
let options = {};
for(let item in this.props) {
if(item === 'settings') {
for(let itemTwo in this.props[item]) {
options[itemTwo] = this.props[item][itemTwo];
}
} else {
if(properties.indexOf(item) !== -1) {
options[item] = this.props[item];
}
}
}
return options;
};
createComponent(options) {
if(!this.style) {
for (let style in this.props.style) {
JQXLite(this.componentSelector).css(style, this.props.style[style]);
}
}
if(this.props.className !== undefined) {
let classes = this.props.className.split(' ');
for (let i = 0; i < classes.length; i++ ) {
JQXLite(this.componentSelector).addClass(classes[i]);
}
}
if(!this.template) {
JQXLite(this.componentSelector).html(this.props.template);
}
JQXLite(this.componentSelector).jqxFileUpload(options);
};
setOptions(options) {
JQXLite(this.componentSelector).jqxFileUpload('setOptions', options);
};
getOptions() {
if(arguments.length === 0) {
throw Error('At least one argument expected in getOptions()!');
}
let resultToReturn = {};
for(let i = 0; i < arguments.length; i++) {
resultToReturn[arguments[i]] = JQXLite(this.componentSelector).jqxFileUpload(arguments[i]);
}
return resultToReturn;
};
on(name,callbackFn) {
JQXLite(this.componentSelector).on(name,callbackFn);
};
off(name) {
JQXLite(this.componentSelector).off(name);
};
autoUpload(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('autoUpload', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('autoUpload');
}
};
accept(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('accept', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('accept');
}
};
browseTemplate(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('browseTemplate', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('browseTemplate');
}
};
cancelTemplate(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('cancelTemplate', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('cancelTemplate');
}
};
disabled(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('disabled', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('disabled');
}
};
fileInputName(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('fileInputName', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('fileInputName');
}
};
height(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('height', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('height');
}
};
localization(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('localization', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('localization');
}
};
multipleFilesUpload(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('multipleFilesUpload', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('multipleFilesUpload');
}
};
renderFiles(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('renderFiles', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('renderFiles');
}
};
rtl(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('rtl', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('rtl');
}
};
theme(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('theme', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('theme');
}
};
uploadUrl(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('uploadUrl', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('uploadUrl');
}
};
uploadTemplate(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('uploadTemplate', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('uploadTemplate');
}
};
width(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('width', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('width');
}
};
browse() {
JQXLite(this.componentSelector).jqxFileUpload('browse');
};
cancelFile(fileIndex) {
JQXLite(this.componentSelector).jqxFileUpload('cancelFile', fileIndex);
};
cancelAll() {
JQXLite(this.componentSelector).jqxFileUpload('cancelAll');
};
destroy() {
JQXLite(this.componentSelector).jqxFileUpload('destroy');
};
performRender() {
JQXLite(this.componentSelector).jqxFileUpload('render');
};
refresh() {
JQXLite(this.componentSelector).jqxFileUpload('refresh');
};
uploadFile(fileIndex) {
JQXLite(this.componentSelector).jqxFileUpload('uploadFile', fileIndex);
};
uploadAll() {
JQXLite(this.componentSelector).jqxFileUpload('uploadAll');
};
render() {
let id = 'jqxFileUpload' + JQXLite.generateID();
this.componentSelector = '#' + id;
return (
<div id={id}>{this.props.value}{this.props.children}</div>
)
};
};
|
test/ModalSpec.js
|
roadmanfong/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Modal from '../src/Modal';
import { render, shouldWarn } from './helpers';
describe('Modal', function () {
let mountPoint;
beforeEach(()=>{
mountPoint = document.createElement('div');
document.body.appendChild(mountPoint);
});
afterEach(function () {
React.unmountComponentAtNode(mountPoint);
document.body.removeChild(mountPoint);
});
it('Should render the modal content', function() {
let noOp = function () {};
let instance = render(
<Modal show onHide={noOp} animation={false}>
<strong>Message</strong>
</Modal>
, mountPoint);
assert.ok(
ReactTestUtils.findRenderedDOMComponentWithTag(instance.refs.modal, 'strong'));
});
it('Should add modal-open class to the modal container while open', function(done) {
let Container = React.createClass({
getInitialState() {
return { modalOpen: true };
},
handleCloseModal() {
this.setState({ modalOpen: false });
},
render() {
return (
<div>
<Modal
animation={false}
show={this.state.modalOpen}
onHide={this.handleCloseModal}
container={this}
>
<strong>Message</strong>
</Modal>
</div>
);
}
});
let instance = render(
<Container />
, mountPoint);
let modal = ReactTestUtils.findRenderedComponentWithType(instance, Modal);
assert.ok(React.findDOMNode(instance).className.match(/\bmodal-open\b/));
let backdrop = React.findDOMNode(modal.refs.backdrop);
ReactTestUtils.Simulate.click(backdrop);
setTimeout(function(){
assert.equal(React.findDOMNode(instance).className.length, 0);
done();
}, 0);
});
it('Should close the modal when the backdrop is clicked', function (done) {
let doneOp = function () { done(); };
let instance = render(
<Modal show onHide={doneOp} animation={false}>
<strong>Message</strong>
</Modal>
, mountPoint);
let backdrop = React.findDOMNode(instance.refs.backdrop);
ReactTestUtils.Simulate.click(backdrop);
});
it('Should close the modal when the modal dialog is clicked', function (done) {
let doneOp = function () { done(); };
let instance = render(
<Modal show onHide={doneOp}>
<strong>Message</strong>
</Modal>
, mountPoint);
let dialog = React.findDOMNode(instance.refs.dialog);
ReactTestUtils.Simulate.click(dialog);
});
it('Should not close the modal when the "static" backdrop is clicked', function () {
let onHideSpy = sinon.spy();
let instance = render(
<Modal show onHide={onHideSpy} backdrop='static'>
<strong>Message</strong>
</Modal>
, mountPoint);
let backdrop = React.findDOMNode(instance.refs.backdrop);
ReactTestUtils.Simulate.click(backdrop);
expect(onHideSpy).to.not.have.been.called;
});
it('Should close the modal when the modal close button is clicked', function (done) {
let doneOp = function () { done(); };
let instance = render(
<Modal show onHide={doneOp}>
<Modal.Header closeButton />
<strong>Message</strong>
</Modal>
, mountPoint);
let button = React.findDOMNode(instance.refs.modal)
.getElementsByClassName('close')[0];
ReactTestUtils.Simulate.click(button);
});
it('Should use bsClass on the dialog', function () {
let noOp = function () {};
let instance = render(
<Modal show bsClass='mymodal' onHide={noOp}>
<strong>Message</strong>
</Modal>
, mountPoint);
let dialog = React.findDOMNode(instance.refs.dialog);
let backdrop = React.findDOMNode(instance.refs.backdrop);
assert.ok(dialog.className.match(/\bmymodal\b/));
assert.ok(dialog.children[0].className.match(/\bmymodal-dialog\b/));
assert.ok(dialog.children[0].children[0].className.match(/\bmymodal-content\b/));
assert.ok(backdrop.className.match(/\bmymodal-backdrop\b/));
shouldWarn("Invalid prop 'bsClass' of value 'mymodal'");
});
it('Should pass bsSize to the dialog', function () {
let noOp = function () {};
let instance = render(
<Modal show bsSize='small' onHide={noOp}>
<strong>Message</strong>
</Modal>
, mountPoint);
let dialog = React.findDOMNode(instance.refs.modal).getElementsByClassName('modal-dialog')[0];
assert.ok(dialog.className.match(/\bmodal-sm\b/));
});
it('Should pass dialogClassName to the dialog', function () {
let noOp = function () {};
let instance = render(
<Modal show dialogClassName="testCss" onHide={noOp}>
<strong>Message</strong>
</Modal>
, mountPoint);
let dialog = ReactTestUtils.findRenderedDOMComponentWithClass(instance.refs.modal, 'modal-dialog');
assert.match(dialog.props.className, /\btestCss\b/);
});
it('Should assign refs correctly when no backdrop', function () {
let test = () => render(
<Modal show backdrop={false} onHide={function () {}}>
<strong>Message</strong>
</Modal>
, mountPoint);
expect(test).not.to.throw();
});
it('Should use dialogComponent', function () {
let noOp = function () {};
class CustomDialog {
render(){ return <div {...this.props}/>; }
}
let instance = render(
<Modal show dialogComponent={CustomDialog} onHide={noOp}>
<strong>Message</strong>
</Modal>
, mountPoint);
assert.ok(instance.refs.dialog instanceof CustomDialog);
});
it('Should pass transition callbacks to Transition', function (done) {
let count = 0;
let increment = ()=> count++;
let instance = render(
<Modal show
onHide={()=>{}}
onExit={increment}
onExiting={increment}
onExited={()=> {
increment();
expect(count).to.equal(6);
done();
}}
onEnter={increment}
onEntering={increment}
onEntered={()=> {
increment();
instance.setProps({ show: false });
}}
>
<strong>Message</strong>
</Modal>
, mountPoint);
});
it('Should unbind listeners when unmounted', function() {
render(
<div>
<Modal show onHide={() => null} animation={false}>
<strong>Foo bar</strong>
</Modal>
</div>
, mountPoint);
assert.include(document.body.className, 'modal-open');
render(<div />, mountPoint);
assert.notInclude(document.body.className, 'modal-open');
});
describe('Focused state', function () {
let focusableContainer = null;
beforeEach(()=>{
focusableContainer = document.createElement('div');
focusableContainer.tabIndex = 0;
document.body.appendChild(focusableContainer);
focusableContainer.focus();
});
afterEach(function () {
React.unmountComponentAtNode(focusableContainer);
document.body.removeChild(focusableContainer);
});
it('Should focus on the Modal when it is opened', function () {
document.activeElement.should.equal(focusableContainer);
let instance = render(
<Modal show onHide={()=>{}} animation={false}>
<strong>Message</strong>
</Modal>
, focusableContainer);
document.activeElement.className.should.contain('modal');
instance.renderWithProps({ show: false });
document.activeElement.should.equal(focusableContainer);
});
it('Should not focus on the Modal when autoFocus is false', function () {
render(
<Modal show autoFocus={false} onHide={()=>{}} animation={false}>
<strong>Message</strong>
</Modal>
, focusableContainer);
document.activeElement.should.equal(focusableContainer);
});
it('Should not focus Modal when child has focus', function () {
document.activeElement.should.equal(focusableContainer);
render(
<Modal show onHide={()=>{}} animation={false}>
<input autoFocus />
</Modal>
, focusableContainer);
let input = document.getElementsByTagName('input')[0];
document.activeElement.should.equal(input);
});
});
});
|
ajax/libs/yui/3.8.0/event-focus/event-focus-debug.js
|
Pranay92/cdnjs
|
YUI.add('event-focus', function (Y, NAME) {
/**
* Adds bubbling and delegation support to DOM events focus and blur.
*
* @module event
* @submodule event-focus
*/
var Event = Y.Event,
YLang = Y.Lang,
isString = YLang.isString,
arrayIndex = Y.Array.indexOf,
useActivate = (function() {
// Changing the structure of this test, so that it doesn't use inline JS in HTML,
// which throws an exception in Win8 packaged apps, due to additional security restrictions:
// http://msdn.microsoft.com/en-us/library/windows/apps/hh465380.aspx#differences
var supported = false,
doc = Y.config.doc,
p;
if (doc) {
p = doc.createElement("p");
p.setAttribute("onbeforeactivate", ";");
// onbeforeactivate is a function in IE8+.
// onbeforeactivate is a string in IE6,7 (unfortunate, otherwise we could have just checked for function below).
// onbeforeactivate is a function in IE10, in a Win8 App environment (no exception running the test).
// onbeforeactivate is undefined in Webkit/Gecko.
// onbeforeactivate is a function in Webkit/Gecko if it's a supported event (e.g. onclick).
supported = (p.onbeforeactivate !== undefined);
}
return supported;
}());
function define(type, proxy, directEvent) {
var nodeDataKey = '_' + type + 'Notifiers';
Y.Event.define(type, {
_useActivate : useActivate,
_attach: function (el, notifier, delegate) {
if (Y.DOM.isWindow(el)) {
return Event._attach([type, function (e) {
notifier.fire(e);
}, el]);
} else {
return Event._attach(
[proxy, this._proxy, el, this, notifier, delegate],
{ capture: true });
}
},
_proxy: function (e, notifier, delegate) {
var target = e.target,
currentTarget = e.currentTarget,
notifiers = target.getData(nodeDataKey),
yuid = Y.stamp(currentTarget._node),
defer = (useActivate || target !== currentTarget),
directSub;
notifier.currentTarget = (delegate) ? target : currentTarget;
notifier.container = (delegate) ? currentTarget : null;
// Maintain a list to handle subscriptions from nested
// containers div#a>div#b>input #a.on(focus..) #b.on(focus..),
// use one focus or blur subscription that fires notifiers from
// #b then #a to emulate bubble sequence.
if (!notifiers) {
notifiers = {};
target.setData(nodeDataKey, notifiers);
// only subscribe to the element's focus if the target is
// not the current target (
if (defer) {
directSub = Event._attach(
[directEvent, this._notify, target._node]).sub;
directSub.once = true;
}
} else {
// In old IE, defer is always true. In capture-phase browsers,
// The delegate subscriptions will be encountered first, which
// will establish the notifiers data and direct subscription
// on the node. If there is also a direct subscription to the
// node's focus/blur, it should not call _notify because the
// direct subscription from the delegate sub(s) exists, which
// will call _notify. So this avoids _notify being called
// twice, unnecessarily.
defer = true;
}
if (!notifiers[yuid]) {
notifiers[yuid] = [];
}
notifiers[yuid].push(notifier);
if (!defer) {
this._notify(e);
}
},
_notify: function (e, container) {
var currentTarget = e.currentTarget,
notifierData = currentTarget.getData(nodeDataKey),
axisNodes = currentTarget.ancestors(),
doc = currentTarget.get('ownerDocument'),
delegates = [],
// Used to escape loops when there are no more
// notifiers to consider
count = notifierData ?
Y.Object.keys(notifierData).length :
0,
target, notifiers, notifier, yuid, match, tmp, i, len, sub, ret;
// clear the notifications list (mainly for delegation)
currentTarget.clearData(nodeDataKey);
// Order the delegate subs by their placement in the parent axis
axisNodes.push(currentTarget);
// document.get('ownerDocument') returns null
// which we'll use to prevent having duplicate Nodes in the list
if (doc) {
axisNodes.unshift(doc);
}
// ancestors() returns the Nodes from top to bottom
axisNodes._nodes.reverse();
if (count) {
// Store the count for step 2
tmp = count;
axisNodes.some(function (node) {
var yuid = Y.stamp(node),
notifiers = notifierData[yuid],
i, len;
if (notifiers) {
count--;
for (i = 0, len = notifiers.length; i < len; ++i) {
if (notifiers[i].handle.sub.filter) {
delegates.push(notifiers[i]);
}
}
}
return !count;
});
count = tmp;
}
// Walk up the parent axis, notifying direct subscriptions and
// testing delegate filters.
while (count && (target = axisNodes.shift())) {
yuid = Y.stamp(target);
notifiers = notifierData[yuid];
if (notifiers) {
for (i = 0, len = notifiers.length; i < len; ++i) {
notifier = notifiers[i];
sub = notifier.handle.sub;
match = true;
e.currentTarget = target;
if (sub.filter) {
match = sub.filter.apply(target,
[target, e].concat(sub.args || []));
// No longer necessary to test against this
// delegate subscription for the nodes along
// the parent axis.
delegates.splice(
arrayIndex(delegates, notifier), 1);
}
if (match) {
// undefined for direct subs
e.container = notifier.container;
ret = notifier.fire(e);
}
if (ret === false || e.stopped === 2) {
break;
}
}
delete notifiers[yuid];
count--;
}
if (e.stopped !== 2) {
// delegates come after subs targeting this specific node
// because they would not normally report until they'd
// bubbled to the container node.
for (i = 0, len = delegates.length; i < len; ++i) {
notifier = delegates[i];
sub = notifier.handle.sub;
if (sub.filter.apply(target,
[target, e].concat(sub.args || []))) {
e.container = notifier.container;
e.currentTarget = target;
ret = notifier.fire(e);
}
if (ret === false || e.stopped === 2) {
break;
}
}
}
if (e.stopped) {
break;
}
}
},
on: function (node, sub, notifier) {
sub.handle = this._attach(node._node, notifier);
},
detach: function (node, sub) {
sub.handle.detach();
},
delegate: function (node, sub, notifier, filter) {
if (isString(filter)) {
sub.filter = function (target) {
return Y.Selector.test(target._node, filter,
node === target ? null : node._node);
};
}
sub.handle = this._attach(node._node, notifier, true);
},
detachDelegate: function (node, sub) {
sub.handle.detach();
}
}, true);
}
// For IE, we need to defer to focusin rather than focus because
// `el.focus(); doSomething();` executes el.onbeforeactivate, el.onactivate,
// el.onfocusin, doSomething, then el.onfocus. All others support capture
// phase focus, which executes before doSomething. To guarantee consistent
// behavior for this use case, IE's direct subscriptions are made against
// focusin so subscribers will be notified before js following el.focus() is
// executed.
if (useActivate) {
// name capture phase direct subscription
define("focus", "beforeactivate", "focusin");
define("blur", "beforedeactivate", "focusout");
} else {
define("focus", "focus", "focus");
define("blur", "blur", "blur");
}
}, '@VERSION@', {"requires": ["event-synthetic"]});
|
packages/vx-glyph/src/glyphs/Diamond.js
|
Flaque/vx
|
import React from 'react';
import cx from 'classnames';
import { symbol, symbolDiamond } from 'd3-shape';
import Glyph from './Glyph';
import additionalProps from '../util/additionalProps';
export default function GlyphDiamond({
children,
className,
top,
left,
size,
...restProps
}) {
const path = symbol();
path.type(symbolDiamond);
if (size) path.size(size);
return (
<Glyph top={top} left={left}>
<path
className={cx('vx-glyph-diamond', className)}
d={path()}
{...additionalProps(restProps)}
/>
{children}
</Glyph>
);
}
|
src/components/PlayLogo/index.js
|
PalmasLab/palmasplay
|
import React from 'react'
import styles from './styles.css'
const Logo = () => (
<div className={styles.playLogo}></div>
)
|
ajax/libs/react/0.11.2/react.min.js
|
jakubfiala/cdnjs
|
/**
* React v0.11.2
*
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
!function(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.React=e()}}(function(){return function e(t,n,r){function o(a,s){if(!n[a]){if(!t[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(i)return i(a,!0);throw new Error("Cannot find module '"+a+"'")}var c=n[a]={exports:{}};t[a][0].call(c.exports,function(e){var n=t[a][1][e];return o(n?n:e)},c,c.exports,e,t,n,r)}return n[a].exports}for(var i="function"==typeof require&&require,a=0;a<r.length;a++)o(r[a]);return o}({1:[function(e,t){"use strict";var n=e("./focusNode"),r={componentDidMount:function(){this.props.autoFocus&&n(this.getDOMNode())}};t.exports=r},{"./focusNode":104}],2:[function(e,t){"use strict";function n(){var e=window.opera;return"object"==typeof e&&"function"==typeof e.version&&parseInt(e.version(),10)<=12}function r(e){return(e.ctrlKey||e.altKey||e.metaKey)&&!(e.ctrlKey&&e.altKey)}var o=e("./EventConstants"),i=e("./EventPropagators"),a=e("./ExecutionEnvironment"),s=e("./SyntheticInputEvent"),u=e("./keyOf"),c=a.canUseDOM&&"TextEvent"in window&&!("documentMode"in document||n()),l=32,p=String.fromCharCode(l),d=o.topLevelTypes,f={beforeInput:{phasedRegistrationNames:{bubbled:u({onBeforeInput:null}),captured:u({onBeforeInputCapture:null})},dependencies:[d.topCompositionEnd,d.topKeyPress,d.topTextInput,d.topPaste]}},h=null,v={eventTypes:f,extractEvents:function(e,t,n,o){var a;if(c)switch(e){case d.topKeyPress:var u=o.which;if(u!==l)return;a=String.fromCharCode(u);break;case d.topTextInput:if(a=o.data,a===p)return;break;default:return}else{switch(e){case d.topPaste:h=null;break;case d.topKeyPress:o.which&&!r(o)&&(h=String.fromCharCode(o.which));break;case d.topCompositionEnd:h=o.data}if(null===h)return;a=h}if(a){var v=s.getPooled(f.beforeInput,n,o);return v.data=a,h=null,i.accumulateTwoPhaseDispatches(v),v}}};t.exports=v},{"./EventConstants":15,"./EventPropagators":20,"./ExecutionEnvironment":21,"./SyntheticInputEvent":84,"./keyOf":125}],3:[function(e,t){"use strict";function n(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var r={columnCount:!0,fillOpacity:!0,flex:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},o=["Webkit","ms","Moz","O"];Object.keys(r).forEach(function(e){o.forEach(function(t){r[n(t,e)]=r[e]})});var i={background:{backgroundImage:!0,backgroundPosition:!0,backgroundRepeat:!0,backgroundColor:!0},border:{borderWidth:!0,borderStyle:!0,borderColor:!0},borderBottom:{borderBottomWidth:!0,borderBottomStyle:!0,borderBottomColor:!0},borderLeft:{borderLeftWidth:!0,borderLeftStyle:!0,borderLeftColor:!0},borderRight:{borderRightWidth:!0,borderRightStyle:!0,borderRightColor:!0},borderTop:{borderTopWidth:!0,borderTopStyle:!0,borderTopColor:!0},font:{fontStyle:!0,fontVariant:!0,fontWeight:!0,fontSize:!0,lineHeight:!0,fontFamily:!0}},a={isUnitlessNumber:r,shorthandPropertyExpansions:i};t.exports=a},{}],4:[function(e,t){"use strict";var n=e("./CSSProperty"),r=e("./dangerousStyleValue"),o=e("./hyphenateStyleName"),i=e("./memoizeStringOnly"),a=i(function(e){return o(e)}),s={createMarkupForStyles:function(e){var t="";for(var n in e)if(e.hasOwnProperty(n)){var o=e[n];null!=o&&(t+=a(n)+":",t+=r(n,o)+";")}return t||null},setValueForStyles:function(e,t){var o=e.style;for(var i in t)if(t.hasOwnProperty(i)){var a=r(i,t[i]);if(a)o[i]=a;else{var s=n.shorthandPropertyExpansions[i];if(s)for(var u in s)o[u]="";else o[i]=""}}}};t.exports=s},{"./CSSProperty":3,"./dangerousStyleValue":99,"./hyphenateStyleName":116,"./memoizeStringOnly":127}],5:[function(e,t){"use strict";function n(){this._callbacks=null,this._contexts=null}var r=e("./PooledClass"),o=e("./invariant"),i=e("./mixInto");i(n,{enqueue:function(e,t){this._callbacks=this._callbacks||[],this._contexts=this._contexts||[],this._callbacks.push(e),this._contexts.push(t)},notifyAll:function(){var e=this._callbacks,t=this._contexts;if(e){o(e.length===t.length),this._callbacks=null,this._contexts=null;for(var n=0,r=e.length;r>n;n++)e[n].call(t[n]);e.length=0,t.length=0}},reset:function(){this._callbacks=null,this._contexts=null},destructor:function(){this.reset()}}),r.addPoolingTo(n),t.exports=n},{"./PooledClass":26,"./invariant":118,"./mixInto":131}],6:[function(e,t){"use strict";function n(e){return"SELECT"===e.nodeName||"INPUT"===e.nodeName&&"file"===e.type}function r(e){var t=M.getPooled(P.change,_,e);C.accumulateTwoPhaseDispatches(t),R.batchedUpdates(o,t)}function o(e){y.enqueueEvents(e),y.processEventQueue()}function i(e,t){I=e,_=t,I.attachEvent("onchange",r)}function a(){I&&(I.detachEvent("onchange",r),I=null,_=null)}function s(e,t,n){return e===O.topChange?n:void 0}function u(e,t,n){e===O.topFocus?(a(),i(t,n)):e===O.topBlur&&a()}function c(e,t){I=e,_=t,T=e.value,N=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(I,"value",A),I.attachEvent("onpropertychange",p)}function l(){I&&(delete I.value,I.detachEvent("onpropertychange",p),I=null,_=null,T=null,N=null)}function p(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==T&&(T=t,r(e))}}function d(e,t,n){return e===O.topInput?n:void 0}function f(e,t,n){e===O.topFocus?(l(),c(t,n)):e===O.topBlur&&l()}function h(e){return e!==O.topSelectionChange&&e!==O.topKeyUp&&e!==O.topKeyDown||!I||I.value===T?void 0:(T=I.value,_)}function v(e){return"INPUT"===e.nodeName&&("checkbox"===e.type||"radio"===e.type)}function m(e,t,n){return e===O.topClick?n:void 0}var g=e("./EventConstants"),y=e("./EventPluginHub"),C=e("./EventPropagators"),E=e("./ExecutionEnvironment"),R=e("./ReactUpdates"),M=e("./SyntheticEvent"),D=e("./isEventSupported"),x=e("./isTextInputElement"),b=e("./keyOf"),O=g.topLevelTypes,P={change:{phasedRegistrationNames:{bubbled:b({onChange:null}),captured:b({onChangeCapture:null})},dependencies:[O.topBlur,O.topChange,O.topClick,O.topFocus,O.topInput,O.topKeyDown,O.topKeyUp,O.topSelectionChange]}},I=null,_=null,T=null,N=null,w=!1;E.canUseDOM&&(w=D("change")&&(!("documentMode"in document)||document.documentMode>8));var S=!1;E.canUseDOM&&(S=D("input")&&(!("documentMode"in document)||document.documentMode>9));var A={get:function(){return N.get.call(this)},set:function(e){T=""+e,N.set.call(this,e)}},k={eventTypes:P,extractEvents:function(e,t,r,o){var i,a;if(n(t)?w?i=s:a=u:x(t)?S?i=d:(i=h,a=f):v(t)&&(i=m),i){var c=i(e,t,r);if(c){var l=M.getPooled(P.change,c,o);return C.accumulateTwoPhaseDispatches(l),l}}a&&a(e,t,r)}};t.exports=k},{"./EventConstants":15,"./EventPluginHub":17,"./EventPropagators":20,"./ExecutionEnvironment":21,"./ReactUpdates":74,"./SyntheticEvent":82,"./isEventSupported":119,"./isTextInputElement":121,"./keyOf":125}],7:[function(e,t){"use strict";var n=0,r={createReactRootIndex:function(){return n++}};t.exports=r},{}],8:[function(e,t){"use strict";function n(e){switch(e){case g.topCompositionStart:return C.compositionStart;case g.topCompositionEnd:return C.compositionEnd;case g.topCompositionUpdate:return C.compositionUpdate}}function r(e,t){return e===g.topKeyDown&&t.keyCode===h}function o(e,t){switch(e){case g.topKeyUp:return-1!==f.indexOf(t.keyCode);case g.topKeyDown:return t.keyCode!==h;case g.topKeyPress:case g.topMouseDown:case g.topBlur:return!0;default:return!1}}function i(e){this.root=e,this.startSelection=c.getSelection(e),this.startValue=this.getText()}var a=e("./EventConstants"),s=e("./EventPropagators"),u=e("./ExecutionEnvironment"),c=e("./ReactInputSelection"),l=e("./SyntheticCompositionEvent"),p=e("./getTextContentAccessor"),d=e("./keyOf"),f=[9,13,27,32],h=229,v=u.canUseDOM&&"CompositionEvent"in window,m=!v||"documentMode"in document&&document.documentMode>8&&document.documentMode<=11,g=a.topLevelTypes,y=null,C={compositionEnd:{phasedRegistrationNames:{bubbled:d({onCompositionEnd:null}),captured:d({onCompositionEndCapture:null})},dependencies:[g.topBlur,g.topCompositionEnd,g.topKeyDown,g.topKeyPress,g.topKeyUp,g.topMouseDown]},compositionStart:{phasedRegistrationNames:{bubbled:d({onCompositionStart:null}),captured:d({onCompositionStartCapture:null})},dependencies:[g.topBlur,g.topCompositionStart,g.topKeyDown,g.topKeyPress,g.topKeyUp,g.topMouseDown]},compositionUpdate:{phasedRegistrationNames:{bubbled:d({onCompositionUpdate:null}),captured:d({onCompositionUpdateCapture:null})},dependencies:[g.topBlur,g.topCompositionUpdate,g.topKeyDown,g.topKeyPress,g.topKeyUp,g.topMouseDown]}};i.prototype.getText=function(){return this.root.value||this.root[p()]},i.prototype.getData=function(){var e=this.getText(),t=this.startSelection.start,n=this.startValue.length-this.startSelection.end;return e.substr(t,e.length-n-t)};var E={eventTypes:C,extractEvents:function(e,t,a,u){var c,p;if(v?c=n(e):y?o(e,u)&&(c=C.compositionEnd):r(e,u)&&(c=C.compositionStart),m&&(y||c!==C.compositionStart?c===C.compositionEnd&&y&&(p=y.getData(),y=null):y=new i(t)),c){var d=l.getPooled(c,a,u);return p&&(d.data=p),s.accumulateTwoPhaseDispatches(d),d}}};t.exports=E},{"./EventConstants":15,"./EventPropagators":20,"./ExecutionEnvironment":21,"./ReactInputSelection":56,"./SyntheticCompositionEvent":80,"./getTextContentAccessor":113,"./keyOf":125}],9:[function(e,t){"use strict";function n(e,t,n){e.insertBefore(t,e.childNodes[n]||null)}var r,o=e("./Danger"),i=e("./ReactMultiChildUpdateTypes"),a=e("./getTextContentAccessor"),s=e("./invariant"),u=a();r="textContent"===u?function(e,t){e.textContent=t}:function(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);if(t){var n=e.ownerDocument||document;e.appendChild(n.createTextNode(t))}};var c={dangerouslyReplaceNodeWithMarkup:o.dangerouslyReplaceNodeWithMarkup,updateTextContent:r,processUpdates:function(e,t){for(var a,u=null,c=null,l=0;a=e[l];l++)if(a.type===i.MOVE_EXISTING||a.type===i.REMOVE_NODE){var p=a.fromIndex,d=a.parentNode.childNodes[p],f=a.parentID;s(d),u=u||{},u[f]=u[f]||[],u[f][p]=d,c=c||[],c.push(d)}var h=o.dangerouslyRenderMarkup(t);if(c)for(var v=0;v<c.length;v++)c[v].parentNode.removeChild(c[v]);for(var m=0;a=e[m];m++)switch(a.type){case i.INSERT_MARKUP:n(a.parentNode,h[a.markupIndex],a.toIndex);break;case i.MOVE_EXISTING:n(a.parentNode,u[a.parentID][a.fromIndex],a.toIndex);break;case i.TEXT_CONTENT:r(a.parentNode,a.textContent);break;case i.REMOVE_NODE:}}};t.exports=c},{"./Danger":12,"./ReactMultiChildUpdateTypes":61,"./getTextContentAccessor":113,"./invariant":118}],10:[function(e,t){"use strict";var n=e("./invariant"),r={MUST_USE_ATTRIBUTE:1,MUST_USE_PROPERTY:2,HAS_SIDE_EFFECTS:4,HAS_BOOLEAN_VALUE:8,HAS_NUMERIC_VALUE:16,HAS_POSITIVE_NUMERIC_VALUE:48,HAS_OVERLOADED_BOOLEAN_VALUE:64,injectDOMPropertyConfig:function(e){var t=e.Properties||{},o=e.DOMAttributeNames||{},a=e.DOMPropertyNames||{},s=e.DOMMutationMethods||{};e.isCustomAttribute&&i._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var u in t){n(!i.isStandardName.hasOwnProperty(u)),i.isStandardName[u]=!0;var c=u.toLowerCase();if(i.getPossibleStandardName[c]=u,o.hasOwnProperty(u)){var l=o[u];i.getPossibleStandardName[l]=u,i.getAttributeName[u]=l}else i.getAttributeName[u]=c;i.getPropertyName[u]=a.hasOwnProperty(u)?a[u]:u,i.getMutationMethod[u]=s.hasOwnProperty(u)?s[u]:null;var p=t[u];i.mustUseAttribute[u]=p&r.MUST_USE_ATTRIBUTE,i.mustUseProperty[u]=p&r.MUST_USE_PROPERTY,i.hasSideEffects[u]=p&r.HAS_SIDE_EFFECTS,i.hasBooleanValue[u]=p&r.HAS_BOOLEAN_VALUE,i.hasNumericValue[u]=p&r.HAS_NUMERIC_VALUE,i.hasPositiveNumericValue[u]=p&r.HAS_POSITIVE_NUMERIC_VALUE,i.hasOverloadedBooleanValue[u]=p&r.HAS_OVERLOADED_BOOLEAN_VALUE,n(!i.mustUseAttribute[u]||!i.mustUseProperty[u]),n(i.mustUseProperty[u]||!i.hasSideEffects[u]),n(!!i.hasBooleanValue[u]+!!i.hasNumericValue[u]+!!i.hasOverloadedBooleanValue[u]<=1)}}},o={},i={ID_ATTRIBUTE_NAME:"data-reactid",isStandardName:{},getPossibleStandardName:{},getAttributeName:{},getPropertyName:{},getMutationMethod:{},mustUseAttribute:{},mustUseProperty:{},hasSideEffects:{},hasBooleanValue:{},hasNumericValue:{},hasPositiveNumericValue:{},hasOverloadedBooleanValue:{},_isCustomAttributeFunctions:[],isCustomAttribute:function(e){for(var t=0;t<i._isCustomAttributeFunctions.length;t++){var n=i._isCustomAttributeFunctions[t];if(n(e))return!0}return!1},getDefaultValueForProperty:function(e,t){var n,r=o[e];return r||(o[e]=r={}),t in r||(n=document.createElement(e),r[t]=n[t]),r[t]},injection:r};t.exports=i},{"./invariant":118}],11:[function(e,t){"use strict";function n(e,t){return null==t||r.hasBooleanValue[e]&&!t||r.hasNumericValue[e]&&isNaN(t)||r.hasPositiveNumericValue[e]&&1>t||r.hasOverloadedBooleanValue[e]&&t===!1}var r=e("./DOMProperty"),o=e("./escapeTextForBrowser"),i=e("./memoizeStringOnly"),a=(e("./warning"),i(function(e){return o(e)+'="'})),s={createMarkupForID:function(e){return a(r.ID_ATTRIBUTE_NAME)+o(e)+'"'},createMarkupForProperty:function(e,t){if(r.isStandardName.hasOwnProperty(e)&&r.isStandardName[e]){if(n(e,t))return"";var i=r.getAttributeName[e];return r.hasBooleanValue[e]||r.hasOverloadedBooleanValue[e]&&t===!0?o(i):a(i)+o(t)+'"'}return r.isCustomAttribute(e)?null==t?"":a(e)+o(t)+'"':null},setValueForProperty:function(e,t,o){if(r.isStandardName.hasOwnProperty(t)&&r.isStandardName[t]){var i=r.getMutationMethod[t];if(i)i(e,o);else if(n(t,o))this.deleteValueForProperty(e,t);else if(r.mustUseAttribute[t])e.setAttribute(r.getAttributeName[t],""+o);else{var a=r.getPropertyName[t];r.hasSideEffects[t]&&e[a]===o||(e[a]=o)}}else r.isCustomAttribute(t)&&(null==o?e.removeAttribute(t):e.setAttribute(t,""+o))},deleteValueForProperty:function(e,t){if(r.isStandardName.hasOwnProperty(t)&&r.isStandardName[t]){var n=r.getMutationMethod[t];if(n)n(e,void 0);else if(r.mustUseAttribute[t])e.removeAttribute(r.getAttributeName[t]);else{var o=r.getPropertyName[t],i=r.getDefaultValueForProperty(e.nodeName,o);r.hasSideEffects[t]&&e[o]===i||(e[o]=i)}}else r.isCustomAttribute(t)&&e.removeAttribute(t)}};t.exports=s},{"./DOMProperty":10,"./escapeTextForBrowser":102,"./memoizeStringOnly":127,"./warning":139}],12:[function(e,t){"use strict";function n(e){return e.substring(1,e.indexOf(" "))}var r=e("./ExecutionEnvironment"),o=e("./createNodesFromMarkup"),i=e("./emptyFunction"),a=e("./getMarkupWrap"),s=e("./invariant"),u=/^(<[^ \/>]+)/,c="data-danger-index",l={dangerouslyRenderMarkup:function(e){s(r.canUseDOM);for(var t,l={},p=0;p<e.length;p++)s(e[p]),t=n(e[p]),t=a(t)?t:"*",l[t]=l[t]||[],l[t][p]=e[p];var d=[],f=0;for(t in l)if(l.hasOwnProperty(t)){var h=l[t];for(var v in h)if(h.hasOwnProperty(v)){var m=h[v];h[v]=m.replace(u,"$1 "+c+'="'+v+'" ')}var g=o(h.join(""),i);for(p=0;p<g.length;++p){var y=g[p];y.hasAttribute&&y.hasAttribute(c)&&(v=+y.getAttribute(c),y.removeAttribute(c),s(!d.hasOwnProperty(v)),d[v]=y,f+=1)}}return s(f===d.length),s(d.length===e.length),d},dangerouslyReplaceNodeWithMarkup:function(e,t){s(r.canUseDOM),s(t),s("html"!==e.tagName.toLowerCase());var n=o(t,i)[0];e.parentNode.replaceChild(n,e)}};t.exports=l},{"./ExecutionEnvironment":21,"./createNodesFromMarkup":98,"./emptyFunction":100,"./getMarkupWrap":110,"./invariant":118}],13:[function(e,t){"use strict";var n=e("./keyOf"),r=[n({ResponderEventPlugin:null}),n({SimpleEventPlugin:null}),n({TapEventPlugin:null}),n({EnterLeaveEventPlugin:null}),n({ChangeEventPlugin:null}),n({SelectEventPlugin:null}),n({CompositionEventPlugin:null}),n({BeforeInputEventPlugin:null}),n({AnalyticsEventPlugin:null}),n({MobileSafariClickEventPlugin:null})];t.exports=r},{"./keyOf":125}],14:[function(e,t){"use strict";var n=e("./EventConstants"),r=e("./EventPropagators"),o=e("./SyntheticMouseEvent"),i=e("./ReactMount"),a=e("./keyOf"),s=n.topLevelTypes,u=i.getFirstReactDOM,c={mouseEnter:{registrationName:a({onMouseEnter:null}),dependencies:[s.topMouseOut,s.topMouseOver]},mouseLeave:{registrationName:a({onMouseLeave:null}),dependencies:[s.topMouseOut,s.topMouseOver]}},l=[null,null],p={eventTypes:c,extractEvents:function(e,t,n,a){if(e===s.topMouseOver&&(a.relatedTarget||a.fromElement))return null;if(e!==s.topMouseOut&&e!==s.topMouseOver)return null;var p;if(t.window===t)p=t;else{var d=t.ownerDocument;p=d?d.defaultView||d.parentWindow:window}var f,h;if(e===s.topMouseOut?(f=t,h=u(a.relatedTarget||a.toElement)||p):(f=p,h=t),f===h)return null;var v=f?i.getID(f):"",m=h?i.getID(h):"",g=o.getPooled(c.mouseLeave,v,a);g.type="mouseleave",g.target=f,g.relatedTarget=h;var y=o.getPooled(c.mouseEnter,m,a);return y.type="mouseenter",y.target=h,y.relatedTarget=f,r.accumulateEnterLeaveDispatches(g,y,v,m),l[0]=g,l[1]=y,l}};t.exports=p},{"./EventConstants":15,"./EventPropagators":20,"./ReactMount":59,"./SyntheticMouseEvent":86,"./keyOf":125}],15:[function(e,t){"use strict";var n=e("./keyMirror"),r=n({bubbled:null,captured:null}),o=n({topBlur:null,topChange:null,topClick:null,topCompositionEnd:null,topCompositionStart:null,topCompositionUpdate:null,topContextMenu:null,topCopy:null,topCut:null,topDoubleClick:null,topDrag:null,topDragEnd:null,topDragEnter:null,topDragExit:null,topDragLeave:null,topDragOver:null,topDragStart:null,topDrop:null,topError:null,topFocus:null,topInput:null,topKeyDown:null,topKeyPress:null,topKeyUp:null,topLoad:null,topMouseDown:null,topMouseMove:null,topMouseOut:null,topMouseOver:null,topMouseUp:null,topPaste:null,topReset:null,topScroll:null,topSelectionChange:null,topSubmit:null,topTextInput:null,topTouchCancel:null,topTouchEnd:null,topTouchMove:null,topTouchStart:null,topWheel:null}),i={topLevelTypes:o,PropagationPhases:r};t.exports=i},{"./keyMirror":124}],16:[function(e,t){var n=e("./emptyFunction"),r={listen:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!1),{remove:function(){e.removeEventListener(t,n,!1)}}):e.attachEvent?(e.attachEvent("on"+t,n),{remove:function(){e.detachEvent("on"+t,n)}}):void 0},capture:function(e,t,r){return e.addEventListener?(e.addEventListener(t,r,!0),{remove:function(){e.removeEventListener(t,r,!0)}}):{remove:n}},registerDefault:function(){}};t.exports=r},{"./emptyFunction":100}],17:[function(e,t){"use strict";var n=e("./EventPluginRegistry"),r=e("./EventPluginUtils"),o=e("./accumulate"),i=e("./forEachAccumulated"),a=e("./invariant"),s=(e("./isEventSupported"),e("./monitorCodeUse"),{}),u=null,c=function(e){if(e){var t=r.executeDispatch,o=n.getPluginModuleForEvent(e);o&&o.executeDispatch&&(t=o.executeDispatch),r.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e)}},l=null,p={injection:{injectMount:r.injection.injectMount,injectInstanceHandle:function(e){l=e},getInstanceHandle:function(){return l},injectEventPluginOrder:n.injectEventPluginOrder,injectEventPluginsByName:n.injectEventPluginsByName},eventNameDispatchConfigs:n.eventNameDispatchConfigs,registrationNameModules:n.registrationNameModules,putListener:function(e,t,n){a(!n||"function"==typeof n);var r=s[t]||(s[t]={});r[e]=n},getListener:function(e,t){var n=s[t];return n&&n[e]},deleteListener:function(e,t){var n=s[t];n&&delete n[e]},deleteAllListeners:function(e){for(var t in s)delete s[t][e]},extractEvents:function(e,t,r,i){for(var a,s=n.plugins,u=0,c=s.length;c>u;u++){var l=s[u];if(l){var p=l.extractEvents(e,t,r,i);p&&(a=o(a,p))}}return a},enqueueEvents:function(e){e&&(u=o(u,e))},processEventQueue:function(){var e=u;u=null,i(e,c),a(!u)},__purge:function(){s={}},__getListenerBank:function(){return s}};t.exports=p},{"./EventPluginRegistry":18,"./EventPluginUtils":19,"./accumulate":92,"./forEachAccumulated":105,"./invariant":118,"./isEventSupported":119,"./monitorCodeUse":132}],18:[function(e,t){"use strict";function n(){if(a)for(var e in s){var t=s[e],n=a.indexOf(e);if(i(n>-1),!u.plugins[n]){i(t.extractEvents),u.plugins[n]=t;var o=t.eventTypes;for(var c in o)i(r(o[c],t,c))}}}function r(e,t,n){i(!u.eventNameDispatchConfigs.hasOwnProperty(n)),u.eventNameDispatchConfigs[n]=e;var r=e.phasedRegistrationNames;if(r){for(var a in r)if(r.hasOwnProperty(a)){var s=r[a];o(s,t,n)}return!0}return e.registrationName?(o(e.registrationName,t,n),!0):!1}function o(e,t,n){i(!u.registrationNameModules[e]),u.registrationNameModules[e]=t,u.registrationNameDependencies[e]=t.eventTypes[n].dependencies}var i=e("./invariant"),a=null,s={},u={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},injectEventPluginOrder:function(e){i(!a),a=Array.prototype.slice.call(e),n()},injectEventPluginsByName:function(e){var t=!1;for(var r in e)if(e.hasOwnProperty(r)){var o=e[r];s.hasOwnProperty(r)&&s[r]===o||(i(!s[r]),s[r]=o,t=!0)}t&&n()},getPluginModuleForEvent:function(e){var t=e.dispatchConfig;if(t.registrationName)return u.registrationNameModules[t.registrationName]||null;for(var n in t.phasedRegistrationNames)if(t.phasedRegistrationNames.hasOwnProperty(n)){var r=u.registrationNameModules[t.phasedRegistrationNames[n]];if(r)return r}return null},_resetEventPlugins:function(){a=null;for(var e in s)s.hasOwnProperty(e)&&delete s[e];u.plugins.length=0;var t=u.eventNameDispatchConfigs;for(var n in t)t.hasOwnProperty(n)&&delete t[n];var r=u.registrationNameModules;for(var o in r)r.hasOwnProperty(o)&&delete r[o]}};t.exports=u},{"./invariant":118}],19:[function(e,t){"use strict";function n(e){return e===v.topMouseUp||e===v.topTouchEnd||e===v.topTouchCancel}function r(e){return e===v.topMouseMove||e===v.topTouchMove}function o(e){return e===v.topMouseDown||e===v.topTouchStart}function i(e,t){var n=e._dispatchListeners,r=e._dispatchIDs;if(Array.isArray(n))for(var o=0;o<n.length&&!e.isPropagationStopped();o++)t(e,n[o],r[o]);else n&&t(e,n,r)}function a(e,t,n){e.currentTarget=h.Mount.getNode(n);var r=t(e,n);return e.currentTarget=null,r}function s(e,t){i(e,t),e._dispatchListeners=null,e._dispatchIDs=null}function u(e){var t=e._dispatchListeners,n=e._dispatchIDs;if(Array.isArray(t)){for(var r=0;r<t.length&&!e.isPropagationStopped();r++)if(t[r](e,n[r]))return n[r]}else if(t&&t(e,n))return n;return null}function c(e){var t=u(e);return e._dispatchIDs=null,e._dispatchListeners=null,t}function l(e){var t=e._dispatchListeners,n=e._dispatchIDs;f(!Array.isArray(t));var r=t?t(e,n):null;return e._dispatchListeners=null,e._dispatchIDs=null,r}function p(e){return!!e._dispatchListeners}var d=e("./EventConstants"),f=e("./invariant"),h={Mount:null,injectMount:function(e){h.Mount=e}},v=d.topLevelTypes,m={isEndish:n,isMoveish:r,isStartish:o,executeDirectDispatch:l,executeDispatch:a,executeDispatchesInOrder:s,executeDispatchesInOrderStopAtTrue:c,hasDispatches:p,injection:h,useTouchEvents:!1};t.exports=m},{"./EventConstants":15,"./invariant":118}],20:[function(e,t){"use strict";function n(e,t,n){var r=t.dispatchConfig.phasedRegistrationNames[n];return v(e,r)}function r(e,t,r){var o=t?h.bubbled:h.captured,i=n(e,r,o);i&&(r._dispatchListeners=d(r._dispatchListeners,i),r._dispatchIDs=d(r._dispatchIDs,e))}function o(e){e&&e.dispatchConfig.phasedRegistrationNames&&p.injection.getInstanceHandle().traverseTwoPhase(e.dispatchMarker,r,e)}function i(e,t,n){if(n&&n.dispatchConfig.registrationName){var r=n.dispatchConfig.registrationName,o=v(e,r);o&&(n._dispatchListeners=d(n._dispatchListeners,o),n._dispatchIDs=d(n._dispatchIDs,e))}}function a(e){e&&e.dispatchConfig.registrationName&&i(e.dispatchMarker,null,e)}function s(e){f(e,o)}function u(e,t,n,r){p.injection.getInstanceHandle().traverseEnterLeave(n,r,i,e,t)}function c(e){f(e,a)}var l=e("./EventConstants"),p=e("./EventPluginHub"),d=e("./accumulate"),f=e("./forEachAccumulated"),h=l.PropagationPhases,v=p.getListener,m={accumulateTwoPhaseDispatches:s,accumulateDirectDispatches:c,accumulateEnterLeaveDispatches:u};t.exports=m},{"./EventConstants":15,"./EventPluginHub":17,"./accumulate":92,"./forEachAccumulated":105}],21:[function(e,t){"use strict";var n=!("undefined"==typeof window||!window.document||!window.document.createElement),r={canUseDOM:n,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:n&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:n&&!!window.screen,isInWorker:!n};t.exports=r},{}],22:[function(e,t){"use strict";var n,r=e("./DOMProperty"),o=e("./ExecutionEnvironment"),i=r.injection.MUST_USE_ATTRIBUTE,a=r.injection.MUST_USE_PROPERTY,s=r.injection.HAS_BOOLEAN_VALUE,u=r.injection.HAS_SIDE_EFFECTS,c=r.injection.HAS_NUMERIC_VALUE,l=r.injection.HAS_POSITIVE_NUMERIC_VALUE,p=r.injection.HAS_OVERLOADED_BOOLEAN_VALUE;if(o.canUseDOM){var d=document.implementation;n=d&&d.hasFeature&&d.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")}var f={isCustomAttribute:RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/),Properties:{accept:null,accessKey:null,action:null,allowFullScreen:i|s,allowTransparency:i,alt:null,async:s,autoComplete:null,autoPlay:s,cellPadding:null,cellSpacing:null,charSet:i,checked:a|s,className:n?i:a,cols:i|l,colSpan:null,content:null,contentEditable:null,contextMenu:i,controls:a|s,coords:null,crossOrigin:null,data:null,dateTime:i,defer:s,dir:null,disabled:i|s,download:p,draggable:null,encType:null,form:i,formNoValidate:s,frameBorder:i,height:i,hidden:i|s,href:null,hrefLang:null,htmlFor:null,httpEquiv:null,icon:null,id:a,label:null,lang:null,list:null,loop:a|s,max:null,maxLength:i,media:i,mediaGroup:null,method:null,min:null,multiple:a|s,muted:a|s,name:null,noValidate:s,open:null,pattern:null,placeholder:null,poster:null,preload:null,radioGroup:null,readOnly:a|s,rel:null,required:s,role:i,rows:i|l,rowSpan:null,sandbox:null,scope:null,scrollLeft:a,scrolling:null,scrollTop:a,seamless:i|s,selected:a|s,shape:null,size:i|l,sizes:i,span:l,spellCheck:null,src:null,srcDoc:a,srcSet:i,start:c,step:null,style:null,tabIndex:null,target:null,title:null,type:null,useMap:null,value:a|u,width:i,wmode:i,autoCapitalize:null,autoCorrect:null,itemProp:i,itemScope:i|s,itemType:i,property:null},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"}};t.exports=f},{"./DOMProperty":10,"./ExecutionEnvironment":21}],23:[function(e,t){"use strict";function n(e){u(null==e.props.checkedLink||null==e.props.valueLink)}function r(e){n(e),u(null==e.props.value&&null==e.props.onChange)}function o(e){n(e),u(null==e.props.checked&&null==e.props.onChange)}function i(e){this.props.valueLink.requestChange(e.target.value)}function a(e){this.props.checkedLink.requestChange(e.target.checked)}var s=e("./ReactPropTypes"),u=e("./invariant"),c={button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0},l={Mixin:{propTypes:{value:function(e,t){return!e[t]||c[e.type]||e.onChange||e.readOnly||e.disabled?void 0: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(e,t){return!e[t]||e.onChange||e.readOnly||e.disabled?void 0: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:s.func}},getValue:function(e){return e.props.valueLink?(r(e),e.props.valueLink.value):e.props.value},getChecked:function(e){return e.props.checkedLink?(o(e),e.props.checkedLink.value):e.props.checked},getOnChange:function(e){return e.props.valueLink?(r(e),i):e.props.checkedLink?(o(e),a):e.props.onChange}};t.exports=l},{"./ReactPropTypes":67,"./invariant":118}],24:[function(e,t){"use strict";function n(e){e.remove()}var r=e("./ReactBrowserEventEmitter"),o=e("./accumulate"),i=e("./forEachAccumulated"),a=e("./invariant"),s={trapBubbledEvent:function(e,t){a(this.isMounted());var n=r.trapBubbledEvent(e,t,this.getDOMNode());this._localEventListeners=o(this._localEventListeners,n)},componentWillUnmount:function(){this._localEventListeners&&i(this._localEventListeners,n)}};t.exports=s},{"./ReactBrowserEventEmitter":29,"./accumulate":92,"./forEachAccumulated":105,"./invariant":118}],25:[function(e,t){"use strict";var n=e("./EventConstants"),r=e("./emptyFunction"),o=n.topLevelTypes,i={eventTypes:null,extractEvents:function(e,t,n,i){if(e===o.topTouchStart){var a=i.target;a&&!a.onclick&&(a.onclick=r)}}};t.exports=i},{"./EventConstants":15,"./emptyFunction":100}],26:[function(e,t){"use strict";var n=e("./invariant"),r=function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)},o=function(e,t){var n=this;if(n.instancePool.length){var r=n.instancePool.pop();return n.call(r,e,t),r}return new n(e,t)},i=function(e,t,n){var r=this;if(r.instancePool.length){var o=r.instancePool.pop();return r.call(o,e,t,n),o}return new r(e,t,n)},a=function(e,t,n,r,o){var i=this;if(i.instancePool.length){var a=i.instancePool.pop();return i.call(a,e,t,n,r,o),a}return new i(e,t,n,r,o)},s=function(e){var t=this;n(e instanceof t),e.destructor&&e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},u=10,c=r,l=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||c,n.poolSize||(n.poolSize=u),n.release=s,n},p={addPoolingTo:l,oneArgumentPooler:r,twoArgumentPooler:o,threeArgumentPooler:i,fiveArgumentPooler:a};t.exports=p},{"./invariant":118}],27:[function(e,t){"use strict";function n(e){var t=Array.prototype.slice.call(arguments,1);return e.apply(null,t)}{var r=e("./DOMPropertyOperations"),o=e("./EventPluginUtils"),i=e("./ReactChildren"),a=e("./ReactComponent"),s=e("./ReactCompositeComponent"),u=e("./ReactContext"),c=e("./ReactCurrentOwner"),l=e("./ReactDescriptor"),p=e("./ReactDOM"),d=e("./ReactDOMComponent"),f=e("./ReactDefaultInjection"),h=e("./ReactInstanceHandles"),v=e("./ReactMount"),m=e("./ReactMultiChild"),g=e("./ReactPerf"),y=e("./ReactPropTypes"),C=e("./ReactServerRendering"),E=e("./ReactTextComponent"),R=e("./onlyChild");e("./warning")}f.inject();var M={Children:{map:i.map,forEach:i.forEach,count:i.count,only:R},DOM:p,PropTypes:y,initializeTouchEvents:function(e){o.useTouchEvents=e},createClass:s.createClass,createDescriptor:function(){return n.apply(this,arguments)},createElement:n,constructAndRenderComponent:v.constructAndRenderComponent,constructAndRenderComponentByID:v.constructAndRenderComponentByID,renderComponent:g.measure("React","renderComponent",v.renderComponent),renderComponentToString:C.renderComponentToString,renderComponentToStaticMarkup:C.renderComponentToStaticMarkup,unmountComponentAtNode:v.unmountComponentAtNode,isValidClass:l.isValidFactory,isValidComponent:l.isValidDescriptor,withContext:u.withContext,__internals:{Component:a,CurrentOwner:c,DOMComponent:d,DOMPropertyOperations:r,InstanceHandles:h,Mount:v,MultiChild:m,TextComponent:E}};M.version="0.11.2",t.exports=M},{"./DOMPropertyOperations":11,"./EventPluginUtils":19,"./ReactChildren":30,"./ReactComponent":31,"./ReactCompositeComponent":33,"./ReactContext":34,"./ReactCurrentOwner":35,"./ReactDOM":36,"./ReactDOMComponent":38,"./ReactDefaultInjection":48,"./ReactDescriptor":49,"./ReactInstanceHandles":57,"./ReactMount":59,"./ReactMultiChild":60,"./ReactPerf":63,"./ReactPropTypes":67,"./ReactServerRendering":71,"./ReactTextComponent":73,"./onlyChild":133,"./warning":139}],28:[function(e,t){"use strict";var n=e("./ReactEmptyComponent"),r=e("./ReactMount"),o=e("./invariant"),i={getDOMNode:function(){return o(this.isMounted()),n.isNullComponentID(this._rootNodeID)?null:r.getNode(this._rootNodeID)}};t.exports=i},{"./ReactEmptyComponent":51,"./ReactMount":59,"./invariant":118}],29:[function(e,t){"use strict";function n(e){return Object.prototype.hasOwnProperty.call(e,h)||(e[h]=d++,l[e[h]]={}),l[e[h]]}var r=e("./EventConstants"),o=e("./EventPluginHub"),i=e("./EventPluginRegistry"),a=e("./ReactEventEmitterMixin"),s=e("./ViewportMetrics"),u=e("./isEventSupported"),c=e("./merge"),l={},p=!1,d=0,f={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"},h="_reactListenersID"+String(Math.random()).slice(2),v=c(a,{ReactEventListener:null,injection:{injectReactEventListener:function(e){e.setHandleTopLevel(v.handleTopLevel),v.ReactEventListener=e
}},setEnabled:function(e){v.ReactEventListener&&v.ReactEventListener.setEnabled(e)},isEnabled:function(){return!(!v.ReactEventListener||!v.ReactEventListener.isEnabled())},listenTo:function(e,t){for(var o=t,a=n(o),s=i.registrationNameDependencies[e],c=r.topLevelTypes,l=0,p=s.length;p>l;l++){var d=s[l];a.hasOwnProperty(d)&&a[d]||(d===c.topWheel?u("wheel")?v.ReactEventListener.trapBubbledEvent(c.topWheel,"wheel",o):u("mousewheel")?v.ReactEventListener.trapBubbledEvent(c.topWheel,"mousewheel",o):v.ReactEventListener.trapBubbledEvent(c.topWheel,"DOMMouseScroll",o):d===c.topScroll?u("scroll",!0)?v.ReactEventListener.trapCapturedEvent(c.topScroll,"scroll",o):v.ReactEventListener.trapBubbledEvent(c.topScroll,"scroll",v.ReactEventListener.WINDOW_HANDLE):d===c.topFocus||d===c.topBlur?(u("focus",!0)?(v.ReactEventListener.trapCapturedEvent(c.topFocus,"focus",o),v.ReactEventListener.trapCapturedEvent(c.topBlur,"blur",o)):u("focusin")&&(v.ReactEventListener.trapBubbledEvent(c.topFocus,"focusin",o),v.ReactEventListener.trapBubbledEvent(c.topBlur,"focusout",o)),a[c.topBlur]=!0,a[c.topFocus]=!0):f.hasOwnProperty(d)&&v.ReactEventListener.trapBubbledEvent(d,f[d],o),a[d]=!0)}},trapBubbledEvent:function(e,t,n){return v.ReactEventListener.trapBubbledEvent(e,t,n)},trapCapturedEvent:function(e,t,n){return v.ReactEventListener.trapCapturedEvent(e,t,n)},ensureScrollValueMonitoring:function(){if(!p){var e=s.refreshScrollValues;v.ReactEventListener.monitorScrollValue(e),p=!0}},eventNameDispatchConfigs:o.eventNameDispatchConfigs,registrationNameModules:o.registrationNameModules,putListener:o.putListener,getListener:o.getListener,deleteListener:o.deleteListener,deleteAllListeners:o.deleteAllListeners});t.exports=v},{"./EventConstants":15,"./EventPluginHub":17,"./EventPluginRegistry":18,"./ReactEventEmitterMixin":53,"./ViewportMetrics":91,"./isEventSupported":119,"./merge":128}],30:[function(e,t){"use strict";function n(e,t){this.forEachFunction=e,this.forEachContext=t}function r(e,t,n,r){var o=e;o.forEachFunction.call(o.forEachContext,t,r)}function o(e,t,o){if(null==e)return e;var i=n.getPooled(t,o);p(e,r,i),n.release(i)}function i(e,t,n){this.mapResult=e,this.mapFunction=t,this.mapContext=n}function a(e,t,n,r){var o=e,i=o.mapResult,a=!i.hasOwnProperty(n);if(a){var s=o.mapFunction.call(o.mapContext,t,r);i[n]=s}}function s(e,t,n){if(null==e)return e;var r={},o=i.getPooled(r,t,n);return p(e,a,o),i.release(o),r}function u(){return null}function c(e){return p(e,u,null)}var l=e("./PooledClass"),p=e("./traverseAllChildren"),d=(e("./warning"),l.twoArgumentPooler),f=l.threeArgumentPooler;l.addPoolingTo(n,d),l.addPoolingTo(i,f);var h={forEach:o,map:s,count:c};t.exports=h},{"./PooledClass":26,"./traverseAllChildren":138,"./warning":139}],31:[function(e,t){"use strict";var n=e("./ReactDescriptor"),r=e("./ReactOwner"),o=e("./ReactUpdates"),i=e("./invariant"),a=e("./keyMirror"),s=e("./merge"),u=a({MOUNTED:null,UNMOUNTED:null}),c=!1,l=null,p=null,d={injection:{injectEnvironment:function(e){i(!c),p=e.mountImageIntoNode,l=e.unmountIDFromEnvironment,d.BackendIDOperations=e.BackendIDOperations,c=!0}},LifeCycle:u,BackendIDOperations:null,Mixin:{isMounted:function(){return this._lifeCycleState===u.MOUNTED},setProps:function(e,t){var n=this._pendingDescriptor||this._descriptor;this.replaceProps(s(n.props,e),t)},replaceProps:function(e,t){i(this.isMounted()),i(0===this._mountDepth),this._pendingDescriptor=n.cloneAndReplaceProps(this._pendingDescriptor||this._descriptor,e),o.enqueueUpdate(this,t)},_setPropsInternal:function(e,t){var r=this._pendingDescriptor||this._descriptor;this._pendingDescriptor=n.cloneAndReplaceProps(r,s(r.props,e)),o.enqueueUpdate(this,t)},construct:function(e){this.props=e.props,this._owner=e._owner,this._lifeCycleState=u.UNMOUNTED,this._pendingCallbacks=null,this._descriptor=e,this._pendingDescriptor=null},mountComponent:function(e,t,n){i(!this.isMounted());var o=this._descriptor.props;if(null!=o.ref){var a=this._descriptor._owner;r.addComponentAsRefTo(this,o.ref,a)}this._rootNodeID=e,this._lifeCycleState=u.MOUNTED,this._mountDepth=n},unmountComponent:function(){i(this.isMounted());var e=this.props;null!=e.ref&&r.removeComponentAsRefFrom(this,e.ref,this._owner),l(this._rootNodeID),this._rootNodeID=null,this._lifeCycleState=u.UNMOUNTED},receiveComponent:function(e,t){i(this.isMounted()),this._pendingDescriptor=e,this.performUpdateIfNecessary(t)},performUpdateIfNecessary:function(e){if(null!=this._pendingDescriptor){var t=this._descriptor,n=this._pendingDescriptor;this._descriptor=n,this.props=n.props,this._owner=n._owner,this._pendingDescriptor=null,this.updateComponent(e,t)}},updateComponent:function(e,t){var n=this._descriptor;(n._owner!==t._owner||n.props.ref!==t.props.ref)&&(null!=t.props.ref&&r.removeComponentAsRefFrom(this,t.props.ref,t._owner),null!=n.props.ref&&r.addComponentAsRefTo(this,n.props.ref,n._owner))},mountComponentIntoNode:function(e,t,n){var r=o.ReactReconcileTransaction.getPooled();r.perform(this._mountComponentIntoNode,this,e,t,r,n),o.ReactReconcileTransaction.release(r)},_mountComponentIntoNode:function(e,t,n,r){var o=this.mountComponent(e,n,0);p(o,t,r)},isOwnedBy:function(e){return this._owner===e},getSiblingByRef:function(e){var t=this._owner;return t&&t.refs?t.refs[e]:null}}};t.exports=d},{"./ReactDescriptor":49,"./ReactOwner":62,"./ReactUpdates":74,"./invariant":118,"./keyMirror":124,"./merge":128}],32:[function(e,t){"use strict";var n=e("./ReactDOMIDOperations"),r=e("./ReactMarkupChecksum"),o=e("./ReactMount"),i=e("./ReactPerf"),a=e("./ReactReconcileTransaction"),s=e("./getReactRootElementInContainer"),u=e("./invariant"),c=e("./setInnerHTML"),l=1,p=9,d={ReactReconcileTransaction:a,BackendIDOperations:n,unmountIDFromEnvironment:function(e){o.purgeID(e)},mountImageIntoNode:i.measure("ReactComponentBrowserEnvironment","mountImageIntoNode",function(e,t,n){if(u(t&&(t.nodeType===l||t.nodeType===p)),n){if(r.canReuseMarkup(e,s(t)))return;u(t.nodeType!==p)}u(t.nodeType!==p),c(t,e)})};t.exports=d},{"./ReactDOMIDOperations":40,"./ReactMarkupChecksum":58,"./ReactMount":59,"./ReactPerf":63,"./ReactReconcileTransaction":69,"./getReactRootElementInContainer":112,"./invariant":118,"./setInnerHTML":134}],33:[function(e,t){"use strict";function n(e){var t=e._owner||null;return t&&t.constructor&&t.constructor.displayName?" Check the render method of `"+t.constructor.displayName+"`.":""}function r(e,t){for(var n in t)t.hasOwnProperty(n)&&D("function"==typeof t[n])}function o(e,t){var n=N.hasOwnProperty(t)?N[t]:null;A.hasOwnProperty(t)&&D(n===_.OVERRIDE_BASE),e.hasOwnProperty(t)&&D(n===_.DEFINE_MANY||n===_.DEFINE_MANY_MERGED)}function i(e){var t=e._compositeLifeCycleState;D(e.isMounted()||t===S.MOUNTING),D(t!==S.RECEIVING_STATE),D(t!==S.UNMOUNTING)}function a(e,t){D(!h.isValidFactory(t)),D(!h.isValidDescriptor(t));var n=e.prototype;for(var r in t){var i=t[r];if(t.hasOwnProperty(r))if(o(n,r),w.hasOwnProperty(r))w[r](e,i);else{var a=N.hasOwnProperty(r),s=n.hasOwnProperty(r),u=i&&i.__reactDontBind,p="function"==typeof i,d=p&&!a&&!s&&!u;if(d)n.__reactAutoBindMap||(n.__reactAutoBindMap={}),n.__reactAutoBindMap[r]=i,n[r]=i;else if(s){var f=N[r];D(a&&(f===_.DEFINE_MANY_MERGED||f===_.DEFINE_MANY)),f===_.DEFINE_MANY_MERGED?n[r]=c(n[r],i):f===_.DEFINE_MANY&&(n[r]=l(n[r],i))}else n[r]=i}}}function s(e,t){if(t)for(var n in t){var r=t[n];if(t.hasOwnProperty(n)){var o=n in e,i=r;if(o){var a=e[n],s=typeof a,u=typeof r;D("function"===s&&"function"===u),i=l(a,r)}e[n]=i}}}function u(e,t){return D(e&&t&&"object"==typeof e&&"object"==typeof t),P(t,function(t,n){D(void 0===e[n]),e[n]=t}),e}function c(e,t){return function(){var n=e.apply(this,arguments),r=t.apply(this,arguments);return null==n?r:null==r?n:u(n,r)}}function l(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}var p=e("./ReactComponent"),d=e("./ReactContext"),f=e("./ReactCurrentOwner"),h=e("./ReactDescriptor"),v=(e("./ReactDescriptorValidator"),e("./ReactEmptyComponent")),m=e("./ReactErrorUtils"),g=e("./ReactOwner"),y=e("./ReactPerf"),C=e("./ReactPropTransferer"),E=e("./ReactPropTypeLocations"),R=(e("./ReactPropTypeLocationNames"),e("./ReactUpdates")),M=e("./instantiateReactComponent"),D=e("./invariant"),x=e("./keyMirror"),b=e("./merge"),O=e("./mixInto"),P=(e("./monitorCodeUse"),e("./mapObject")),I=e("./shouldUpdateReactComponent"),_=(e("./warning"),x({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null,DEFINE_MANY_MERGED:null})),T=[],N={mixins:_.DEFINE_MANY,statics:_.DEFINE_MANY,propTypes:_.DEFINE_MANY,contextTypes:_.DEFINE_MANY,childContextTypes:_.DEFINE_MANY,getDefaultProps:_.DEFINE_MANY_MERGED,getInitialState:_.DEFINE_MANY_MERGED,getChildContext:_.DEFINE_MANY_MERGED,render:_.DEFINE_ONCE,componentWillMount:_.DEFINE_MANY,componentDidMount:_.DEFINE_MANY,componentWillReceiveProps:_.DEFINE_MANY,shouldComponentUpdate:_.DEFINE_ONCE,componentWillUpdate:_.DEFINE_MANY,componentDidUpdate:_.DEFINE_MANY,componentWillUnmount:_.DEFINE_MANY,updateComponent:_.OVERRIDE_BASE},w={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var n=0;n<t.length;n++)a(e,t[n])},childContextTypes:function(e,t){r(e,t,E.childContext),e.childContextTypes=b(e.childContextTypes,t)},contextTypes:function(e,t){r(e,t,E.context),e.contextTypes=b(e.contextTypes,t)},getDefaultProps:function(e,t){e.getDefaultProps=e.getDefaultProps?c(e.getDefaultProps,t):t},propTypes:function(e,t){r(e,t,E.prop),e.propTypes=b(e.propTypes,t)},statics:function(e,t){s(e,t)}},S=x({MOUNTING:null,UNMOUNTING:null,RECEIVING_PROPS:null,RECEIVING_STATE:null}),A={construct:function(){p.Mixin.construct.apply(this,arguments),g.Mixin.construct.apply(this,arguments),this.state=null,this._pendingState=null,this.context=null,this._compositeLifeCycleState=null},isMounted:function(){return p.Mixin.isMounted.call(this)&&this._compositeLifeCycleState!==S.MOUNTING},mountComponent:y.measure("ReactCompositeComponent","mountComponent",function(e,t,n){p.Mixin.mountComponent.call(this,e,t,n),this._compositeLifeCycleState=S.MOUNTING,this.__reactAutoBindMap&&this._bindAutoBindMethods(),this.context=this._processContext(this._descriptor._context),this.props=this._processProps(this.props),this.state=this.getInitialState?this.getInitialState():null,D("object"==typeof this.state&&!Array.isArray(this.state)),this._pendingState=null,this._pendingForceUpdate=!1,this.componentWillMount&&(this.componentWillMount(),this._pendingState&&(this.state=this._pendingState,this._pendingState=null)),this._renderedComponent=M(this._renderValidatedComponent()),this._compositeLifeCycleState=null;var r=this._renderedComponent.mountComponent(e,t,n+1);return this.componentDidMount&&t.getReactMountReady().enqueue(this.componentDidMount,this),r}),unmountComponent:function(){this._compositeLifeCycleState=S.UNMOUNTING,this.componentWillUnmount&&this.componentWillUnmount(),this._compositeLifeCycleState=null,this._renderedComponent.unmountComponent(),this._renderedComponent=null,p.Mixin.unmountComponent.call(this)},setState:function(e,t){D("object"==typeof e||null==e),this.replaceState(b(this._pendingState||this.state,e),t)},replaceState:function(e,t){i(this),this._pendingState=e,this._compositeLifeCycleState!==S.MOUNTING&&R.enqueueUpdate(this,t)},_processContext:function(e){var t=null,n=this.constructor.contextTypes;if(n){t={};for(var r in n)t[r]=e[r]}return t},_processChildContext:function(e){var t=this.getChildContext&&this.getChildContext();if(this.constructor.displayName||"ReactCompositeComponent",t){D("object"==typeof this.constructor.childContextTypes);for(var n in t)D(n in this.constructor.childContextTypes);return b(e,t)}return e},_processProps:function(e){var t,n=this.constructor.defaultProps;if(n){t=b(e);for(var r in n)"undefined"==typeof t[r]&&(t[r]=n[r])}else t=e;return t},_checkPropTypes:function(e,t,r){var o=this.constructor.displayName;for(var i in e)if(e.hasOwnProperty(i)){var a=e[i](t,i,o,r);a instanceof Error&&n(this)}},performUpdateIfNecessary:function(e){var t=this._compositeLifeCycleState;if(t!==S.MOUNTING&&t!==S.RECEIVING_PROPS&&(null!=this._pendingDescriptor||null!=this._pendingState||this._pendingForceUpdate)){var n=this.context,r=this.props,o=this._descriptor;null!=this._pendingDescriptor&&(o=this._pendingDescriptor,n=this._processContext(o._context),r=this._processProps(o.props),this._pendingDescriptor=null,this._compositeLifeCycleState=S.RECEIVING_PROPS,this.componentWillReceiveProps&&this.componentWillReceiveProps(r,n)),this._compositeLifeCycleState=S.RECEIVING_STATE;var i=this._pendingState||this.state;this._pendingState=null;try{var a=this._pendingForceUpdate||!this.shouldComponentUpdate||this.shouldComponentUpdate(r,i,n);a?(this._pendingForceUpdate=!1,this._performComponentUpdate(o,r,i,n,e)):(this._descriptor=o,this.props=r,this.state=i,this.context=n,this._owner=o._owner)}finally{this._compositeLifeCycleState=null}}},_performComponentUpdate:function(e,t,n,r,o){var i=this._descriptor,a=this.props,s=this.state,u=this.context;this.componentWillUpdate&&this.componentWillUpdate(t,n,r),this._descriptor=e,this.props=t,this.state=n,this.context=r,this._owner=e._owner,this.updateComponent(o,i),this.componentDidUpdate&&o.getReactMountReady().enqueue(this.componentDidUpdate.bind(this,a,s,u),this)},receiveComponent:function(e,t){(e!==this._descriptor||null==e._owner)&&p.Mixin.receiveComponent.call(this,e,t)},updateComponent:y.measure("ReactCompositeComponent","updateComponent",function(e,t){p.Mixin.updateComponent.call(this,e,t);var n=this._renderedComponent,r=n._descriptor,o=this._renderValidatedComponent();if(I(r,o))n.receiveComponent(o,e);else{var i=this._rootNodeID,a=n._rootNodeID;n.unmountComponent(),this._renderedComponent=M(o);var s=this._renderedComponent.mountComponent(i,e,this._mountDepth+1);p.BackendIDOperations.dangerouslyReplaceNodeWithMarkupByID(a,s)}}),forceUpdate:function(e){var t=this._compositeLifeCycleState;D(this.isMounted()||t===S.MOUNTING),D(t!==S.RECEIVING_STATE&&t!==S.UNMOUNTING),this._pendingForceUpdate=!0,R.enqueueUpdate(this,e)},_renderValidatedComponent:y.measure("ReactCompositeComponent","_renderValidatedComponent",function(){var e,t=d.current;d.current=this._processChildContext(this._descriptor._context),f.current=this;try{e=this.render(),null===e||e===!1?(e=v.getEmptyComponent(),v.registerNullComponentID(this._rootNodeID)):v.deregisterNullComponentID(this._rootNodeID)}finally{d.current=t,f.current=null}return D(h.isValidDescriptor(e)),e}),_bindAutoBindMethods:function(){for(var e in this.__reactAutoBindMap)if(this.__reactAutoBindMap.hasOwnProperty(e)){var t=this.__reactAutoBindMap[e];this[e]=this._bindAutoBindMethod(m.guard(t,this.constructor.displayName+"."+e))}},_bindAutoBindMethod:function(e){var t=this,n=function(){return e.apply(t,arguments)};return n}},k=function(){};O(k,p.Mixin),O(k,g.Mixin),O(k,C.Mixin),O(k,A);var U={LifeCycle:S,Base:k,createClass:function(e){var t=function(e,t){this.construct(e,t)};t.prototype=new k,t.prototype.constructor=t,T.forEach(a.bind(null,t)),a(t,e),t.getDefaultProps&&(t.defaultProps=t.getDefaultProps()),D(t.prototype.render);for(var n in N)t.prototype[n]||(t.prototype[n]=null);var r=h.createFactory(t);return r},injection:{injectMixin:function(e){T.push(e)}}};t.exports=U},{"./ReactComponent":31,"./ReactContext":34,"./ReactCurrentOwner":35,"./ReactDescriptor":49,"./ReactDescriptorValidator":50,"./ReactEmptyComponent":51,"./ReactErrorUtils":52,"./ReactOwner":62,"./ReactPerf":63,"./ReactPropTransferer":64,"./ReactPropTypeLocationNames":65,"./ReactPropTypeLocations":66,"./ReactUpdates":74,"./instantiateReactComponent":117,"./invariant":118,"./keyMirror":124,"./mapObject":126,"./merge":128,"./mixInto":131,"./monitorCodeUse":132,"./shouldUpdateReactComponent":136,"./warning":139}],34:[function(e,t){"use strict";var n=e("./merge"),r={current:{},withContext:function(e,t){var o,i=r.current;r.current=n(i,e);try{o=t()}finally{r.current=i}return o}};t.exports=r},{"./merge":128}],35:[function(e,t){"use strict";var n={current:null};t.exports=n},{}],36:[function(e,t){"use strict";function n(e,t){var n=function(e){this.construct(e)};n.prototype=new o(t,e),n.prototype.constructor=n,n.displayName=t;var i=r.createFactory(n);return i}var r=e("./ReactDescriptor"),o=(e("./ReactDescriptorValidator"),e("./ReactDOMComponent")),i=e("./mergeInto"),a=e("./mapObject"),s=a({a:!1,abbr:!1,address:!1,area:!0,article:!1,aside:!1,audio:!1,b:!1,base:!0,bdi:!1,bdo:!1,big:!1,blockquote:!1,body:!1,br:!0,button:!1,canvas:!1,caption:!1,cite:!1,code:!1,col:!0,colgroup:!1,data:!1,datalist:!1,dd:!1,del:!1,details:!1,dfn:!1,dialog:!1,div:!1,dl:!1,dt:!1,em:!1,embed:!0,fieldset:!1,figcaption:!1,figure:!1,footer:!1,form:!1,h1:!1,h2:!1,h3:!1,h4:!1,h5:!1,h6:!1,head:!1,header:!1,hr:!0,html:!1,i:!1,iframe:!1,img:!0,input:!0,ins:!1,kbd:!1,keygen:!0,label:!1,legend:!1,li:!1,link:!0,main:!1,map:!1,mark:!1,menu:!1,menuitem:!1,meta:!0,meter:!1,nav:!1,noscript:!1,object:!1,ol:!1,optgroup:!1,option:!1,output:!1,p:!1,param:!0,picture:!1,pre:!1,progress:!1,q:!1,rp:!1,rt:!1,ruby:!1,s:!1,samp:!1,script:!1,section:!1,select:!1,small:!1,source:!0,span:!1,strong:!1,style:!1,sub:!1,summary:!1,sup:!1,table:!1,tbody:!1,td:!1,textarea:!1,tfoot:!1,th:!1,thead:!1,time:!1,title:!1,tr:!1,track:!0,u:!1,ul:!1,"var":!1,video:!1,wbr:!0,circle:!1,defs:!1,ellipse:!1,g:!1,line:!1,linearGradient:!1,mask:!1,path:!1,pattern:!1,polygon:!1,polyline:!1,radialGradient:!1,rect:!1,stop:!1,svg:!1,text:!1,tspan:!1},n),u={injectComponentClasses:function(e){i(s,e)}};s.injection=u,t.exports=s},{"./ReactDOMComponent":38,"./ReactDescriptor":49,"./ReactDescriptorValidator":50,"./mapObject":126,"./mergeInto":130}],37:[function(e,t){"use strict";var n=e("./AutoFocusMixin"),r=e("./ReactBrowserComponentMixin"),o=e("./ReactCompositeComponent"),i=e("./ReactDOM"),a=e("./keyMirror"),s=i.button,u=a({onClick:!0,onDoubleClick:!0,onMouseDown:!0,onMouseMove:!0,onMouseUp:!0,onClickCapture:!0,onDoubleClickCapture:!0,onMouseDownCapture:!0,onMouseMoveCapture:!0,onMouseUpCapture:!0}),c=o.createClass({displayName:"ReactDOMButton",mixins:[n,r],render:function(){var e={};for(var t in this.props)!this.props.hasOwnProperty(t)||this.props.disabled&&u[t]||(e[t]=this.props[t]);return s(e,this.props.children)}});t.exports=c},{"./AutoFocusMixin":1,"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36,"./keyMirror":124}],38:[function(e,t){"use strict";function n(e){e&&(v(null==e.children||null==e.dangerouslySetInnerHTML),v(null==e.style||"object"==typeof e.style))}function r(e,t,n,r){var o=p.findReactContainerForID(e);if(o){var i=o.nodeType===x?o.ownerDocument:o;E(t,i)}r.getPutListenerQueue().enqueuePutListener(e,t,n)}function o(e,t){this._tagOpen="<"+e,this._tagClose=t?"":"</"+e+">",this.tagName=e.toUpperCase()}var i=e("./CSSPropertyOperations"),a=e("./DOMProperty"),s=e("./DOMPropertyOperations"),u=e("./ReactBrowserComponentMixin"),c=e("./ReactComponent"),l=e("./ReactBrowserEventEmitter"),p=e("./ReactMount"),d=e("./ReactMultiChild"),f=e("./ReactPerf"),h=e("./escapeTextForBrowser"),v=e("./invariant"),m=e("./keyOf"),g=e("./merge"),y=e("./mixInto"),C=l.deleteListener,E=l.listenTo,R=l.registrationNameModules,M={string:!0,number:!0},D=m({style:null}),x=1;o.Mixin={mountComponent:f.measure("ReactDOMComponent","mountComponent",function(e,t,r){return c.Mixin.mountComponent.call(this,e,t,r),n(this.props),this._createOpenTagMarkupAndPutListeners(t)+this._createContentMarkup(t)+this._tagClose}),_createOpenTagMarkupAndPutListeners:function(e){var t=this.props,n=this._tagOpen;for(var o in t)if(t.hasOwnProperty(o)){var a=t[o];if(null!=a)if(R.hasOwnProperty(o))r(this._rootNodeID,o,a,e);else{o===D&&(a&&(a=t.style=g(t.style)),a=i.createMarkupForStyles(a));var u=s.createMarkupForProperty(o,a);u&&(n+=" "+u)}}if(e.renderToStaticMarkup)return n+">";var c=s.createMarkupForID(this._rootNodeID);return n+" "+c+">"},_createContentMarkup:function(e){var t=this.props.dangerouslySetInnerHTML;if(null!=t){if(null!=t.__html)return t.__html}else{var n=M[typeof this.props.children]?this.props.children:null,r=null!=n?null:this.props.children;if(null!=n)return h(n);if(null!=r){var o=this.mountChildren(r,e);return o.join("")}}return""},receiveComponent:function(e,t){(e!==this._descriptor||null==e._owner)&&c.Mixin.receiveComponent.call(this,e,t)},updateComponent:f.measure("ReactDOMComponent","updateComponent",function(e,t){n(this._descriptor.props),c.Mixin.updateComponent.call(this,e,t),this._updateDOMProperties(t.props,e),this._updateDOMChildren(t.props,e)}),_updateDOMProperties:function(e,t){var n,o,i,s=this.props;for(n in e)if(!s.hasOwnProperty(n)&&e.hasOwnProperty(n))if(n===D){var u=e[n];for(o in u)u.hasOwnProperty(o)&&(i=i||{},i[o]="")}else R.hasOwnProperty(n)?C(this._rootNodeID,n):(a.isStandardName[n]||a.isCustomAttribute(n))&&c.BackendIDOperations.deletePropertyByID(this._rootNodeID,n);for(n in s){var l=s[n],p=e[n];if(s.hasOwnProperty(n)&&l!==p)if(n===D)if(l&&(l=s.style=g(l)),p){for(o in p)!p.hasOwnProperty(o)||l&&l.hasOwnProperty(o)||(i=i||{},i[o]="");for(o in l)l.hasOwnProperty(o)&&p[o]!==l[o]&&(i=i||{},i[o]=l[o])}else i=l;else R.hasOwnProperty(n)?r(this._rootNodeID,n,l,t):(a.isStandardName[n]||a.isCustomAttribute(n))&&c.BackendIDOperations.updatePropertyByID(this._rootNodeID,n,l)}i&&c.BackendIDOperations.updateStylesByID(this._rootNodeID,i)},_updateDOMChildren:function(e,t){var n=this.props,r=M[typeof e.children]?e.children:null,o=M[typeof n.children]?n.children:null,i=e.dangerouslySetInnerHTML&&e.dangerouslySetInnerHTML.__html,a=n.dangerouslySetInnerHTML&&n.dangerouslySetInnerHTML.__html,s=null!=r?null:e.children,u=null!=o?null:n.children,l=null!=r||null!=i,p=null!=o||null!=a;null!=s&&null==u?this.updateChildren(null,t):l&&!p&&this.updateTextContent(""),null!=o?r!==o&&this.updateTextContent(""+o):null!=a?i!==a&&c.BackendIDOperations.updateInnerHTMLByID(this._rootNodeID,a):null!=u&&this.updateChildren(u,t)},unmountComponent:function(){this.unmountChildren(),l.deleteAllListeners(this._rootNodeID),c.Mixin.unmountComponent.call(this)}},y(o,c.Mixin),y(o,o.Mixin),y(o,d.Mixin),y(o,u),t.exports=o},{"./CSSPropertyOperations":4,"./DOMProperty":10,"./DOMPropertyOperations":11,"./ReactBrowserComponentMixin":28,"./ReactBrowserEventEmitter":29,"./ReactComponent":31,"./ReactMount":59,"./ReactMultiChild":60,"./ReactPerf":63,"./escapeTextForBrowser":102,"./invariant":118,"./keyOf":125,"./merge":128,"./mixInto":131}],39:[function(e,t){"use strict";var n=e("./EventConstants"),r=e("./LocalEventTrapMixin"),o=e("./ReactBrowserComponentMixin"),i=e("./ReactCompositeComponent"),a=e("./ReactDOM"),s=a.form,u=i.createClass({displayName:"ReactDOMForm",mixins:[o,r],render:function(){return this.transferPropsTo(s(null,this.props.children))},componentDidMount:function(){this.trapBubbledEvent(n.topLevelTypes.topReset,"reset"),this.trapBubbledEvent(n.topLevelTypes.topSubmit,"submit")}});t.exports=u},{"./EventConstants":15,"./LocalEventTrapMixin":24,"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36}],40:[function(e,t){"use strict";var n=e("./CSSPropertyOperations"),r=e("./DOMChildrenOperations"),o=e("./DOMPropertyOperations"),i=e("./ReactMount"),a=e("./ReactPerf"),s=e("./invariant"),u=e("./setInnerHTML"),c={dangerouslySetInnerHTML:"`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.",style:"`style` must be set using `updateStylesByID()`."},l={updatePropertyByID:a.measure("ReactDOMIDOperations","updatePropertyByID",function(e,t,n){var r=i.getNode(e);s(!c.hasOwnProperty(t)),null!=n?o.setValueForProperty(r,t,n):o.deleteValueForProperty(r,t)}),deletePropertyByID:a.measure("ReactDOMIDOperations","deletePropertyByID",function(e,t,n){var r=i.getNode(e);s(!c.hasOwnProperty(t)),o.deleteValueForProperty(r,t,n)}),updateStylesByID:a.measure("ReactDOMIDOperations","updateStylesByID",function(e,t){var r=i.getNode(e);n.setValueForStyles(r,t)}),updateInnerHTMLByID:a.measure("ReactDOMIDOperations","updateInnerHTMLByID",function(e,t){var n=i.getNode(e);u(n,t)}),updateTextContentByID:a.measure("ReactDOMIDOperations","updateTextContentByID",function(e,t){var n=i.getNode(e);r.updateTextContent(n,t)}),dangerouslyReplaceNodeWithMarkupByID:a.measure("ReactDOMIDOperations","dangerouslyReplaceNodeWithMarkupByID",function(e,t){var n=i.getNode(e);r.dangerouslyReplaceNodeWithMarkup(n,t)}),dangerouslyProcessChildrenUpdates:a.measure("ReactDOMIDOperations","dangerouslyProcessChildrenUpdates",function(e,t){for(var n=0;n<e.length;n++)e[n].parentNode=i.getNode(e[n].parentID);r.processUpdates(e,t)})};t.exports=l},{"./CSSPropertyOperations":4,"./DOMChildrenOperations":9,"./DOMPropertyOperations":11,"./ReactMount":59,"./ReactPerf":63,"./invariant":118,"./setInnerHTML":134}],41:[function(e,t){"use strict";var n=e("./EventConstants"),r=e("./LocalEventTrapMixin"),o=e("./ReactBrowserComponentMixin"),i=e("./ReactCompositeComponent"),a=e("./ReactDOM"),s=a.img,u=i.createClass({displayName:"ReactDOMImg",tagName:"IMG",mixins:[o,r],render:function(){return s(this.props)},componentDidMount:function(){this.trapBubbledEvent(n.topLevelTypes.topLoad,"load"),this.trapBubbledEvent(n.topLevelTypes.topError,"error")}});t.exports=u},{"./EventConstants":15,"./LocalEventTrapMixin":24,"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36}],42:[function(e,t){"use strict";var n=e("./AutoFocusMixin"),r=e("./DOMPropertyOperations"),o=e("./LinkedValueUtils"),i=e("./ReactBrowserComponentMixin"),a=e("./ReactCompositeComponent"),s=e("./ReactDOM"),u=e("./ReactMount"),c=e("./invariant"),l=e("./merge"),p=s.input,d={},f=a.createClass({displayName:"ReactDOMInput",mixins:[n,o.Mixin,i],getInitialState:function(){var e=this.props.defaultValue;return{checked:this.props.defaultChecked||!1,value:null!=e?e:null}},shouldComponentUpdate:function(){return!this._isChanging},render:function(){var e=l(this.props);e.defaultChecked=null,e.defaultValue=null;var t=o.getValue(this);e.value=null!=t?t:this.state.value;var n=o.getChecked(this);return e.checked=null!=n?n:this.state.checked,e.onChange=this._handleChange,p(e,this.props.children)},componentDidMount:function(){var e=u.getID(this.getDOMNode());d[e]=this},componentWillUnmount:function(){var e=this.getDOMNode(),t=u.getID(e);delete d[t]},componentDidUpdate:function(){var e=this.getDOMNode();null!=this.props.checked&&r.setValueForProperty(e,"checked",this.props.checked||!1);var t=o.getValue(this);null!=t&&r.setValueForProperty(e,"value",""+t)},_handleChange:function(e){var t,n=o.getOnChange(this);n&&(this._isChanging=!0,t=n.call(this,e),this._isChanging=!1),this.setState({checked:e.target.checked,value:e.target.value});var r=this.props.name;if("radio"===this.props.type&&null!=r){for(var i=this.getDOMNode(),a=i;a.parentNode;)a=a.parentNode;for(var s=a.querySelectorAll("input[name="+JSON.stringify(""+r)+'][type="radio"]'),l=0,p=s.length;p>l;l++){var f=s[l];if(f!==i&&f.form===i.form){var h=u.getID(f);c(h);var v=d[h];c(v),v.setState({checked:!1})}}}return t}});t.exports=f},{"./AutoFocusMixin":1,"./DOMPropertyOperations":11,"./LinkedValueUtils":23,"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36,"./ReactMount":59,"./invariant":118,"./merge":128}],43:[function(e,t){"use strict";var n=e("./ReactBrowserComponentMixin"),r=e("./ReactCompositeComponent"),o=e("./ReactDOM"),i=(e("./warning"),o.option),a=r.createClass({displayName:"ReactDOMOption",mixins:[n],componentWillMount:function(){},render:function(){return i(this.props,this.props.children)}});t.exports=a},{"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36,"./warning":139}],44:[function(e,t){"use strict";function n(e,t){if(null!=e[t])if(e.multiple){if(!Array.isArray(e[t]))return new Error("The `"+t+"` prop supplied to <select> must be an array if `multiple` is true.")}else if(Array.isArray(e[t]))return new Error("The `"+t+"` prop supplied to <select> must be a scalar value if `multiple` is false.")}function r(e,t){var n,r,o,i=e.props.multiple,a=null!=t?t:e.state.value,s=e.getDOMNode().options;if(i)for(n={},r=0,o=a.length;o>r;++r)n[""+a[r]]=!0;else n=""+a;for(r=0,o=s.length;o>r;r++){var u=i?n.hasOwnProperty(s[r].value):s[r].value===n;u!==s[r].selected&&(s[r].selected=u)}}var o=e("./AutoFocusMixin"),i=e("./LinkedValueUtils"),a=e("./ReactBrowserComponentMixin"),s=e("./ReactCompositeComponent"),u=e("./ReactDOM"),c=e("./merge"),l=u.select,p=s.createClass({displayName:"ReactDOMSelect",mixins:[o,i.Mixin,a],propTypes:{defaultValue:n,value:n},getInitialState:function(){return{value:this.props.defaultValue||(this.props.multiple?[]:"")}},componentWillReceiveProps:function(e){!this.props.multiple&&e.multiple?this.setState({value:[this.state.value]}):this.props.multiple&&!e.multiple&&this.setState({value:this.state.value[0]})},shouldComponentUpdate:function(){return!this._isChanging},render:function(){var e=c(this.props);return e.onChange=this._handleChange,e.value=null,l(e,this.props.children)},componentDidMount:function(){r(this,i.getValue(this))},componentDidUpdate:function(e){var t=i.getValue(this),n=!!e.multiple,o=!!this.props.multiple;(null!=t||n!==o)&&r(this,t)},_handleChange:function(e){var t,n=i.getOnChange(this);n&&(this._isChanging=!0,t=n.call(this,e),this._isChanging=!1);var r;if(this.props.multiple){r=[];for(var o=e.target.options,a=0,s=o.length;s>a;a++)o[a].selected&&r.push(o[a].value)}else r=e.target.value;return this.setState({value:r}),t}});t.exports=p},{"./AutoFocusMixin":1,"./LinkedValueUtils":23,"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36,"./merge":128}],45:[function(e,t){"use strict";function n(e,t,n,r){return e===n&&t===r}function r(e){var t=document.selection,n=t.createRange(),r=n.text.length,o=n.duplicate();o.moveToElementText(e),o.setEndPoint("EndToStart",n);var i=o.text.length,a=i+r;return{start:i,end:a}}function o(e){var t=window.getSelection();if(0===t.rangeCount)return null;var r=t.anchorNode,o=t.anchorOffset,i=t.focusNode,a=t.focusOffset,s=t.getRangeAt(0),u=n(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset),c=u?0:s.toString().length,l=s.cloneRange();l.selectNodeContents(e),l.setEnd(s.startContainer,s.startOffset);var p=n(l.startContainer,l.startOffset,l.endContainer,l.endOffset),d=p?0:l.toString().length,f=d+c,h=document.createRange();h.setStart(r,o),h.setEnd(i,a);var v=h.collapsed;return h.detach(),{start:v?f:d,end:v?d:f}}function i(e,t){var n,r,o=document.selection.createRange().duplicate();"undefined"==typeof t.end?(n=t.start,r=n):t.start>t.end?(n=t.end,r=t.start):(n=t.start,r=t.end),o.moveToElementText(e),o.moveStart("character",n),o.setEndPoint("EndToStart",o),o.moveEnd("character",r-n),o.select()}function a(e,t){var n=window.getSelection(),r=e[c()].length,o=Math.min(t.start,r),i="undefined"==typeof t.end?o:Math.min(t.end,r);if(!n.extend&&o>i){var a=i;i=o,o=a}var s=u(e,o),l=u(e,i);if(s&&l){var p=document.createRange();p.setStart(s.node,s.offset),n.removeAllRanges(),o>i?(n.addRange(p),n.extend(l.node,l.offset)):(p.setEnd(l.node,l.offset),n.addRange(p)),p.detach()}}var s=e("./ExecutionEnvironment"),u=e("./getNodeForCharacterOffset"),c=e("./getTextContentAccessor"),l=s.canUseDOM&&document.selection,p={getOffsets:l?r:o,setOffsets:l?i:a};t.exports=p},{"./ExecutionEnvironment":21,"./getNodeForCharacterOffset":111,"./getTextContentAccessor":113}],46:[function(e,t){"use strict";var n=e("./AutoFocusMixin"),r=e("./DOMPropertyOperations"),o=e("./LinkedValueUtils"),i=e("./ReactBrowserComponentMixin"),a=e("./ReactCompositeComponent"),s=e("./ReactDOM"),u=e("./invariant"),c=e("./merge"),l=(e("./warning"),s.textarea),p=a.createClass({displayName:"ReactDOMTextarea",mixins:[n,o.Mixin,i],getInitialState:function(){var e=this.props.defaultValue,t=this.props.children;null!=t&&(u(null==e),Array.isArray(t)&&(u(t.length<=1),t=t[0]),e=""+t),null==e&&(e="");var n=o.getValue(this);return{initialValue:""+(null!=n?n:e)}},shouldComponentUpdate:function(){return!this._isChanging},render:function(){var e=c(this.props);return u(null==e.dangerouslySetInnerHTML),e.defaultValue=null,e.value=null,e.onChange=this._handleChange,l(e,this.state.initialValue)
},componentDidUpdate:function(){var e=o.getValue(this);if(null!=e){var t=this.getDOMNode();r.setValueForProperty(t,"value",""+e)}},_handleChange:function(e){var t,n=o.getOnChange(this);return n&&(this._isChanging=!0,t=n.call(this,e),this._isChanging=!1),this.setState({value:e.target.value}),t}});t.exports=p},{"./AutoFocusMixin":1,"./DOMPropertyOperations":11,"./LinkedValueUtils":23,"./ReactBrowserComponentMixin":28,"./ReactCompositeComponent":33,"./ReactDOM":36,"./invariant":118,"./merge":128,"./warning":139}],47:[function(e,t){"use strict";function n(){this.reinitializeTransaction()}var r=e("./ReactUpdates"),o=e("./Transaction"),i=e("./emptyFunction"),a=e("./mixInto"),s={initialize:i,close:function(){p.isBatchingUpdates=!1}},u={initialize:i,close:r.flushBatchedUpdates.bind(r)},c=[u,s];a(n,o.Mixin),a(n,{getTransactionWrappers:function(){return c}});var l=new n,p={isBatchingUpdates:!1,batchedUpdates:function(e,t,n){var r=p.isBatchingUpdates;p.isBatchingUpdates=!0,r?e(t,n):l.perform(e,null,t,n)}};t.exports=p},{"./ReactUpdates":74,"./Transaction":90,"./emptyFunction":100,"./mixInto":131}],48:[function(e,t){"use strict";function n(){x.EventEmitter.injectReactEventListener(D),x.EventPluginHub.injectEventPluginOrder(s),x.EventPluginHub.injectInstanceHandle(b),x.EventPluginHub.injectMount(O),x.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:_,EnterLeaveEventPlugin:u,ChangeEventPlugin:o,CompositionEventPlugin:a,MobileSafariClickEventPlugin:p,SelectEventPlugin:P,BeforeInputEventPlugin:r}),x.DOM.injectComponentClasses({button:m,form:g,img:y,input:C,option:E,select:R,textarea:M,html:N(v.html),head:N(v.head),body:N(v.body)}),x.CompositeComponent.injectMixin(d),x.DOMProperty.injectDOMPropertyConfig(l),x.DOMProperty.injectDOMPropertyConfig(T),x.EmptyComponent.injectEmptyComponent(v.noscript),x.Updates.injectReconcileTransaction(f.ReactReconcileTransaction),x.Updates.injectBatchingStrategy(h),x.RootIndex.injectCreateReactRootIndex(c.canUseDOM?i.createReactRootIndex:I.createReactRootIndex),x.Component.injectEnvironment(f)}var r=e("./BeforeInputEventPlugin"),o=e("./ChangeEventPlugin"),i=e("./ClientReactRootIndex"),a=e("./CompositionEventPlugin"),s=e("./DefaultEventPluginOrder"),u=e("./EnterLeaveEventPlugin"),c=e("./ExecutionEnvironment"),l=e("./HTMLDOMPropertyConfig"),p=e("./MobileSafariClickEventPlugin"),d=e("./ReactBrowserComponentMixin"),f=e("./ReactComponentBrowserEnvironment"),h=e("./ReactDefaultBatchingStrategy"),v=e("./ReactDOM"),m=e("./ReactDOMButton"),g=e("./ReactDOMForm"),y=e("./ReactDOMImg"),C=e("./ReactDOMInput"),E=e("./ReactDOMOption"),R=e("./ReactDOMSelect"),M=e("./ReactDOMTextarea"),D=e("./ReactEventListener"),x=e("./ReactInjection"),b=e("./ReactInstanceHandles"),O=e("./ReactMount"),P=e("./SelectEventPlugin"),I=e("./ServerReactRootIndex"),_=e("./SimpleEventPlugin"),T=e("./SVGDOMPropertyConfig"),N=e("./createFullPageComponent");t.exports={inject:n}},{"./BeforeInputEventPlugin":2,"./ChangeEventPlugin":6,"./ClientReactRootIndex":7,"./CompositionEventPlugin":8,"./DefaultEventPluginOrder":13,"./EnterLeaveEventPlugin":14,"./ExecutionEnvironment":21,"./HTMLDOMPropertyConfig":22,"./MobileSafariClickEventPlugin":25,"./ReactBrowserComponentMixin":28,"./ReactComponentBrowserEnvironment":32,"./ReactDOM":36,"./ReactDOMButton":37,"./ReactDOMForm":39,"./ReactDOMImg":41,"./ReactDOMInput":42,"./ReactDOMOption":43,"./ReactDOMSelect":44,"./ReactDOMTextarea":46,"./ReactDefaultBatchingStrategy":47,"./ReactEventListener":54,"./ReactInjection":55,"./ReactInstanceHandles":57,"./ReactMount":59,"./SVGDOMPropertyConfig":75,"./SelectEventPlugin":76,"./ServerReactRootIndex":77,"./SimpleEventPlugin":78,"./createFullPageComponent":97}],49:[function(e,t){"use strict";function n(e,t){if("function"==typeof t)for(var n in t)if(t.hasOwnProperty(n)){var r=t[n];if("function"==typeof r){var o=r.bind(t);for(var i in r)r.hasOwnProperty(i)&&(o[i]=r[i]);e[n]=o}else e[n]=r}}var r=e("./ReactContext"),o=e("./ReactCurrentOwner"),i=e("./merge"),a=(e("./warning"),function(){});a.createFactory=function(e){var t=Object.create(a.prototype),s=function(e,n){null==e?e={}:"object"==typeof e&&(e=i(e));var a=arguments.length-1;if(1===a)e.children=n;else if(a>1){for(var s=Array(a),u=0;a>u;u++)s[u]=arguments[u+1];e.children=s}var c=Object.create(t);return c._owner=o.current,c._context=r.current,c.props=e,c};return s.prototype=t,s.type=e,t.type=e,n(s,e),t.constructor=s,s},a.cloneAndReplaceProps=function(e,t){var n=Object.create(e.constructor.prototype);return n._owner=e._owner,n._context=e._context,n.props=t,n},a.isValidFactory=function(e){return"function"==typeof e&&e.prototype instanceof a},a.isValidDescriptor=function(e){return e instanceof a},t.exports=a},{"./ReactContext":34,"./ReactCurrentOwner":35,"./merge":128,"./warning":139}],50:[function(e,t){"use strict";function n(){var e=p.current;return e&&e.constructor.displayName||void 0}function r(e,t){e._store.validated||null!=e.props.key||(e._store.validated=!0,i("react_key_warning",'Each child in an array should have a unique "key" prop.',e,t))}function o(e,t,n){m.test(e)&&i("react_numeric_key_warning","Child objects should have non-numeric keys so ordering is preserved.",t,n)}function i(e,t,r,o){var i=n(),a=o.displayName,s=i||a,u=f[e];if(!u.hasOwnProperty(s)){u[s]=!0,t+=i?" Check the render method of "+i+".":" Check the renderComponent call using <"+a+">.";var c=null;r._owner&&r._owner!==p.current&&(c=r._owner.constructor.displayName,t+=" It was passed a child from "+c+"."),t+=" See http://fb.me/react-warning-keys for more information.",d(e,{component:s,componentOwner:c}),console.warn(t)}}function a(){var e=n()||"";h.hasOwnProperty(e)||(h[e]=!0,d("react_object_map_children"))}function s(e,t){if(Array.isArray(e))for(var n=0;n<e.length;n++){var i=e[n];c.isValidDescriptor(i)&&r(i,t)}else if(c.isValidDescriptor(e))e._store.validated=!0;else if(e&&"object"==typeof e){a();for(var s in e)o(s,e[s],t)}}function u(e,t,n,r){for(var o in t)if(t.hasOwnProperty(o)){var i;try{i=t[o](n,o,e,r)}catch(a){i=a}i instanceof Error&&!(i.message in v)&&(v[i.message]=!0,d("react_failed_descriptor_type_check",{message:i.message}))}}var c=e("./ReactDescriptor"),l=e("./ReactPropTypeLocations"),p=e("./ReactCurrentOwner"),d=e("./monitorCodeUse"),f={react_key_warning:{},react_numeric_key_warning:{}},h={},v={},m=/^\d+$/,g={createFactory:function(e,t,n){var r=function(){for(var r=e.apply(this,arguments),o=1;o<arguments.length;o++)s(arguments[o],r.type);var i=r.type.displayName;return t&&u(i,t,r.props,l.prop),n&&u(i,n,r._context,l.context),r};r.prototype=e.prototype,r.type=e.type;for(var o in e)e.hasOwnProperty(o)&&(r[o]=e[o]);return r}};t.exports=g},{"./ReactCurrentOwner":35,"./ReactDescriptor":49,"./ReactPropTypeLocations":66,"./monitorCodeUse":132}],51:[function(e,t){"use strict";function n(){return s(a),a()}function r(e){u[e]=!0}function o(e){delete u[e]}function i(e){return u[e]}var a,s=e("./invariant"),u={},c={injectEmptyComponent:function(e){a=e}},l={deregisterNullComponentID:o,getEmptyComponent:n,injection:c,isNullComponentID:i,registerNullComponentID:r};t.exports=l},{"./invariant":118}],52:[function(e,t){"use strict";var n={guard:function(e){return e}};t.exports=n},{}],53:[function(e,t){"use strict";function n(e){r.enqueueEvents(e),r.processEventQueue()}var r=e("./EventPluginHub"),o={handleTopLevel:function(e,t,o,i){var a=r.extractEvents(e,t,o,i);n(a)}};t.exports=o},{"./EventPluginHub":17}],54:[function(e,t){"use strict";function n(e){var t=l.getID(e),n=c.getReactRootIDFromNodeID(t),r=l.findReactContainerForID(n),o=l.getFirstReactDOM(r);return o}function r(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function o(e){for(var t=l.getFirstReactDOM(d(e.nativeEvent))||window,r=t;r;)e.ancestors.push(r),r=n(r);for(var o=0,i=e.ancestors.length;i>o;o++){t=e.ancestors[o];var a=l.getID(t)||"";v._handleTopLevel(e.topLevelType,t,a,e.nativeEvent)}}function i(e){var t=f(window);e(t)}var a=e("./EventListener"),s=e("./ExecutionEnvironment"),u=e("./PooledClass"),c=e("./ReactInstanceHandles"),l=e("./ReactMount"),p=e("./ReactUpdates"),d=e("./getEventTarget"),f=e("./getUnboundedScrollPosition"),h=e("./mixInto");h(r,{destructor:function(){this.topLevelType=null,this.nativeEvent=null,this.ancestors.length=0}}),u.addPoolingTo(r,u.twoArgumentPooler);var v={_enabled:!0,_handleTopLevel:null,WINDOW_HANDLE:s.canUseDOM?window:null,setHandleTopLevel:function(e){v._handleTopLevel=e},setEnabled:function(e){v._enabled=!!e},isEnabled:function(){return v._enabled},trapBubbledEvent:function(e,t,n){var r=n;return r?a.listen(r,t,v.dispatchEvent.bind(null,e)):void 0},trapCapturedEvent:function(e,t,n){var r=n;return r?a.capture(r,t,v.dispatchEvent.bind(null,e)):void 0},monitorScrollValue:function(e){var t=i.bind(null,e);a.listen(window,"scroll",t),a.listen(window,"resize",t)},dispatchEvent:function(e,t){if(v._enabled){var n=r.getPooled(e,t);try{p.batchedUpdates(o,n)}finally{r.release(n)}}}};t.exports=v},{"./EventListener":16,"./ExecutionEnvironment":21,"./PooledClass":26,"./ReactInstanceHandles":57,"./ReactMount":59,"./ReactUpdates":74,"./getEventTarget":109,"./getUnboundedScrollPosition":114,"./mixInto":131}],55:[function(e,t){"use strict";var n=e("./DOMProperty"),r=e("./EventPluginHub"),o=e("./ReactComponent"),i=e("./ReactCompositeComponent"),a=e("./ReactDOM"),s=e("./ReactEmptyComponent"),u=e("./ReactBrowserEventEmitter"),c=e("./ReactPerf"),l=e("./ReactRootIndex"),p=e("./ReactUpdates"),d={Component:o.injection,CompositeComponent:i.injection,DOMProperty:n.injection,EmptyComponent:s.injection,EventPluginHub:r.injection,DOM:a.injection,EventEmitter:u.injection,Perf:c.injection,RootIndex:l.injection,Updates:p.injection};t.exports=d},{"./DOMProperty":10,"./EventPluginHub":17,"./ReactBrowserEventEmitter":29,"./ReactComponent":31,"./ReactCompositeComponent":33,"./ReactDOM":36,"./ReactEmptyComponent":51,"./ReactPerf":63,"./ReactRootIndex":70,"./ReactUpdates":74}],56:[function(e,t){"use strict";function n(e){return o(document.documentElement,e)}var r=e("./ReactDOMSelection"),o=e("./containsNode"),i=e("./focusNode"),a=e("./getActiveElement"),s={hasSelectionCapabilities:function(e){return e&&("INPUT"===e.nodeName&&"text"===e.type||"TEXTAREA"===e.nodeName||"true"===e.contentEditable)},getSelectionInformation:function(){var e=a();return{focusedElem:e,selectionRange:s.hasSelectionCapabilities(e)?s.getSelection(e):null}},restoreSelection:function(e){var t=a(),r=e.focusedElem,o=e.selectionRange;t!==r&&n(r)&&(s.hasSelectionCapabilities(r)&&s.setSelection(r,o),i(r))},getSelection:function(e){var t;if("selectionStart"in e)t={start:e.selectionStart,end:e.selectionEnd};else if(document.selection&&"INPUT"===e.nodeName){var n=document.selection.createRange();n.parentElement()===e&&(t={start:-n.moveStart("character",-e.value.length),end:-n.moveEnd("character",-e.value.length)})}else t=r.getOffsets(e);return t||{start:0,end:0}},setSelection:function(e,t){var n=t.start,o=t.end;if("undefined"==typeof o&&(o=n),"selectionStart"in e)e.selectionStart=n,e.selectionEnd=Math.min(o,e.value.length);else if(document.selection&&"INPUT"===e.nodeName){var i=e.createTextRange();i.collapse(!0),i.moveStart("character",n),i.moveEnd("character",o-n),i.select()}else r.setOffsets(e,t)}};t.exports=s},{"./ReactDOMSelection":45,"./containsNode":94,"./focusNode":104,"./getActiveElement":106}],57:[function(e,t){"use strict";function n(e){return d+e.toString(36)}function r(e,t){return e.charAt(t)===d||t===e.length}function o(e){return""===e||e.charAt(0)===d&&e.charAt(e.length-1)!==d}function i(e,t){return 0===t.indexOf(e)&&r(t,e.length)}function a(e){return e?e.substr(0,e.lastIndexOf(d)):""}function s(e,t){if(p(o(e)&&o(t)),p(i(e,t)),e===t)return e;for(var n=e.length+f,a=n;a<t.length&&!r(t,a);a++);return t.substr(0,a)}function u(e,t){var n=Math.min(e.length,t.length);if(0===n)return"";for(var i=0,a=0;n>=a;a++)if(r(e,a)&&r(t,a))i=a;else if(e.charAt(a)!==t.charAt(a))break;var s=e.substr(0,i);return p(o(s)),s}function c(e,t,n,r,o,u){e=e||"",t=t||"",p(e!==t);var c=i(t,e);p(c||i(e,t));for(var l=0,d=c?a:s,f=e;;f=d(f,t)){var v;if(o&&f===e||u&&f===t||(v=n(f,c,r)),v===!1||f===t)break;p(l++<h)}}var l=e("./ReactRootIndex"),p=e("./invariant"),d=".",f=d.length,h=100,v={createReactRootID:function(){return n(l.createReactRootIndex())},createReactID:function(e,t){return e+t},getReactRootIDFromNodeID:function(e){if(e&&e.charAt(0)===d&&e.length>1){var t=e.indexOf(d,1);return t>-1?e.substr(0,t):e}return null},traverseEnterLeave:function(e,t,n,r,o){var i=u(e,t);i!==e&&c(e,i,n,r,!1,!0),i!==t&&c(i,t,n,o,!0,!1)},traverseTwoPhase:function(e,t,n){e&&(c("",e,t,n,!0,!1),c(e,"",t,n,!1,!0))},traverseAncestors:function(e,t,n){c("",e,t,n,!0,!1)},_getFirstCommonAncestorID:u,_getNextDescendantID:s,isAncestorIDOf:i,SEPARATOR:d};t.exports=v},{"./ReactRootIndex":70,"./invariant":118}],58:[function(e,t){"use strict";var n=e("./adler32"),r={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=n(e);return e.replace(">"," "+r.CHECKSUM_ATTR_NAME+'="'+t+'">')},canReuseMarkup:function(e,t){var o=t.getAttribute(r.CHECKSUM_ATTR_NAME);o=o&&parseInt(o,10);var i=n(e);return i===o}};t.exports=r},{"./adler32":93}],59:[function(e,t){"use strict";function n(e){var t=g(e);return t&&T.getID(t)}function r(e){var t=o(e);if(t)if(D.hasOwnProperty(t)){var n=D[t];n!==e&&(C(!s(n,t)),D[t]=e)}else D[t]=e;return t}function o(e){return e&&e.getAttribute&&e.getAttribute(M)||""}function i(e,t){var n=o(e);n!==t&&delete D[n],e.setAttribute(M,t),D[t]=e}function a(e){return D.hasOwnProperty(e)&&s(D[e],e)||(D[e]=T.findReactNodeByID(e)),D[e]}function s(e,t){if(e){C(o(e)===t);var n=T.findReactContainerForID(t);if(n&&m(n,e))return!0}return!1}function u(e){delete D[e]}function c(e){var t=D[e];return t&&s(t,e)?void(_=t):!1}function l(e){_=null,h.traverseAncestors(e,c);var t=_;return _=null,t}var p=e("./DOMProperty"),d=e("./ReactBrowserEventEmitter"),f=(e("./ReactCurrentOwner"),e("./ReactDescriptor")),h=e("./ReactInstanceHandles"),v=e("./ReactPerf"),m=e("./containsNode"),g=e("./getReactRootElementInContainer"),y=e("./instantiateReactComponent"),C=e("./invariant"),E=e("./shouldUpdateReactComponent"),R=(e("./warning"),h.SEPARATOR),M=p.ID_ATTRIBUTE_NAME,D={},x=1,b=9,O={},P={},I=[],_=null,T={_instancesByReactRootID:O,scrollMonitor:function(e,t){t()},_updateRootComponent:function(e,t,n,r){var o=t.props;return T.scrollMonitor(n,function(){e.replaceProps(o,r)}),e},_registerComponent:function(e,t){C(t&&(t.nodeType===x||t.nodeType===b)),d.ensureScrollValueMonitoring();var n=T.registerContainer(t);return O[n]=e,n},_renderNewRootComponent:v.measure("ReactMount","_renderNewRootComponent",function(e,t,n){var r=y(e),o=T._registerComponent(r,t);return r.mountComponentIntoNode(o,t,n),r}),renderComponent:function(e,t,r){C(f.isValidDescriptor(e));var o=O[n(t)];if(o){var i=o._descriptor;if(E(i,e))return T._updateRootComponent(o,e,t,r);T.unmountComponentAtNode(t)}var a=g(t),s=a&&T.isRenderedByReact(a),u=s&&!o,c=T._renderNewRootComponent(e,t,u);return r&&r.call(c),c},constructAndRenderComponent:function(e,t,n){return T.renderComponent(e(t),n)},constructAndRenderComponentByID:function(e,t,n){var r=document.getElementById(n);return C(r),T.constructAndRenderComponent(e,t,r)},registerContainer:function(e){var t=n(e);return t&&(t=h.getReactRootIDFromNodeID(t)),t||(t=h.createReactRootID()),P[t]=e,t},unmountComponentAtNode:function(e){var t=n(e),r=O[t];return r?(T.unmountComponentFromNode(r,e),delete O[t],delete P[t],!0):!1},unmountComponentFromNode:function(e,t){for(e.unmountComponent(),t.nodeType===b&&(t=t.documentElement);t.lastChild;)t.removeChild(t.lastChild)},findReactContainerForID:function(e){var t=h.getReactRootIDFromNodeID(e),n=P[t];return n},findReactNodeByID:function(e){var t=T.findReactContainerForID(e);return T.findComponentRoot(t,e)},isRenderedByReact:function(e){if(1!==e.nodeType)return!1;var t=T.getID(e);return t?t.charAt(0)===R:!1},getFirstReactDOM:function(e){for(var t=e;t&&t.parentNode!==t;){if(T.isRenderedByReact(t))return t;t=t.parentNode}return null},findComponentRoot:function(e,t){var n=I,r=0,o=l(t)||e;for(n[0]=o.firstChild,n.length=1;r<n.length;){for(var i,a=n[r++];a;){var s=T.getID(a);s?t===s?i=a:h.isAncestorIDOf(s,t)&&(n.length=r=0,n.push(a.firstChild)):n.push(a.firstChild),a=a.nextSibling}if(i)return n.length=0,i}n.length=0,C(!1)},getReactRootID:n,getID:r,setID:i,getNode:a,purgeID:u};t.exports=T},{"./DOMProperty":10,"./ReactBrowserEventEmitter":29,"./ReactCurrentOwner":35,"./ReactDescriptor":49,"./ReactInstanceHandles":57,"./ReactPerf":63,"./containsNode":94,"./getReactRootElementInContainer":112,"./instantiateReactComponent":117,"./invariant":118,"./shouldUpdateReactComponent":136,"./warning":139}],60:[function(e,t){"use strict";function n(e,t,n){h.push({parentID:e,parentNode:null,type:c.INSERT_MARKUP,markupIndex:v.push(t)-1,textContent:null,fromIndex:null,toIndex:n})}function r(e,t,n){h.push({parentID:e,parentNode:null,type:c.MOVE_EXISTING,markupIndex:null,textContent:null,fromIndex:t,toIndex:n})}function o(e,t){h.push({parentID:e,parentNode:null,type:c.REMOVE_NODE,markupIndex:null,textContent:null,fromIndex:t,toIndex:null})}function i(e,t){h.push({parentID:e,parentNode:null,type:c.TEXT_CONTENT,markupIndex:null,textContent:t,fromIndex:null,toIndex:null})}function a(){h.length&&(u.BackendIDOperations.dangerouslyProcessChildrenUpdates(h,v),s())}function s(){h.length=0,v.length=0}var u=e("./ReactComponent"),c=e("./ReactMultiChildUpdateTypes"),l=e("./flattenChildren"),p=e("./instantiateReactComponent"),d=e("./shouldUpdateReactComponent"),f=0,h=[],v=[],m={Mixin:{mountChildren:function(e,t){var n=l(e),r=[],o=0;this._renderedChildren=n;for(var i in n){var a=n[i];if(n.hasOwnProperty(i)){var s=p(a);n[i]=s;var u=this._rootNodeID+i,c=s.mountComponent(u,t,this._mountDepth+1);s._mountIndex=o,r.push(c),o++}}return r},updateTextContent:function(e){f++;var t=!0;try{var n=this._renderedChildren;for(var r in n)n.hasOwnProperty(r)&&this._unmountChildByName(n[r],r);this.setTextContent(e),t=!1}finally{f--,f||(t?s():a())}},updateChildren:function(e,t){f++;var n=!0;try{this._updateChildren(e,t),n=!1}finally{f--,f||(n?s():a())}},_updateChildren:function(e,t){var n=l(e),r=this._renderedChildren;if(n||r){var o,i=0,a=0;for(o in n)if(n.hasOwnProperty(o)){var s=r&&r[o],u=s&&s._descriptor,c=n[o];if(d(u,c))this.moveChild(s,a,i),i=Math.max(s._mountIndex,i),s.receiveComponent(c,t),s._mountIndex=a;else{s&&(i=Math.max(s._mountIndex,i),this._unmountChildByName(s,o));var f=p(c);this._mountChildByNameAtIndex(f,o,a,t)}a++}for(o in r)!r.hasOwnProperty(o)||n&&n[o]||this._unmountChildByName(r[o],o)}},unmountChildren:function(){var e=this._renderedChildren;for(var t in e){var n=e[t];n.unmountComponent&&n.unmountComponent()}this._renderedChildren=null},moveChild:function(e,t,n){e._mountIndex<n&&r(this._rootNodeID,e._mountIndex,t)},createChild:function(e,t){n(this._rootNodeID,t,e._mountIndex)},removeChild:function(e){o(this._rootNodeID,e._mountIndex)},setTextContent:function(e){i(this._rootNodeID,e)},_mountChildByNameAtIndex:function(e,t,n,r){var o=this._rootNodeID+t,i=e.mountComponent(o,r,this._mountDepth+1);e._mountIndex=n,this.createChild(e,i),this._renderedChildren=this._renderedChildren||{},this._renderedChildren[t]=e},_unmountChildByName:function(e,t){this.removeChild(e),e._mountIndex=null,e.unmountComponent(),delete this._renderedChildren[t]}}};t.exports=m},{"./ReactComponent":31,"./ReactMultiChildUpdateTypes":61,"./flattenChildren":103,"./instantiateReactComponent":117,"./shouldUpdateReactComponent":136}],61:[function(e,t){"use strict";var n=e("./keyMirror"),r=n({INSERT_MARKUP:null,MOVE_EXISTING:null,REMOVE_NODE:null,TEXT_CONTENT:null});t.exports=r},{"./keyMirror":124}],62:[function(e,t){"use strict";var n=e("./emptyObject"),r=e("./invariant"),o={isValidOwner:function(e){return!(!e||"function"!=typeof e.attachRef||"function"!=typeof e.detachRef)},addComponentAsRefTo:function(e,t,n){r(o.isValidOwner(n)),n.attachRef(t,e)},removeComponentAsRefFrom:function(e,t,n){r(o.isValidOwner(n)),n.refs[t]===e&&n.detachRef(t)},Mixin:{construct:function(){this.refs=n},attachRef:function(e,t){r(t.isOwnedBy(this));var o=this.refs===n?this.refs={}:this.refs;o[e]=t},detachRef:function(e){delete this.refs[e]}}};t.exports=o},{"./emptyObject":101,"./invariant":118}],63:[function(e,t){"use strict";function n(e,t,n){return n}var r={enableMeasure:!1,storedMeasure:n,measure:function(e,t,n){return n},injection:{injectMeasure:function(e){r.storedMeasure=e}}};t.exports=r},{}],64:[function(e,t){"use strict";function n(e){return function(t,n,r){t[n]=t.hasOwnProperty(n)?e(t[n],r):r}}function r(e,t){for(var n in t)if(t.hasOwnProperty(n)){var r=c[n];r&&c.hasOwnProperty(n)?r(e,n,t[n]):e.hasOwnProperty(n)||(e[n]=t[n])}return e}var o=e("./emptyFunction"),i=e("./invariant"),a=e("./joinClasses"),s=e("./merge"),u=n(function(e,t){return s(t,e)}),c={children:o,className:n(a),key:o,ref:o,style:u},l={TransferStrategies:c,mergeProps:function(e,t){return r(s(e),t)},Mixin:{transferPropsTo:function(e){return i(e._owner===this),r(e.props,this.props),e}}};t.exports=l},{"./emptyFunction":100,"./invariant":118,"./joinClasses":123,"./merge":128}],65:[function(e,t){"use strict";var n={};t.exports=n},{}],66:[function(e,t){"use strict";var n=e("./keyMirror"),r=n({prop:null,context:null,childContext:null});t.exports=r},{"./keyMirror":124}],67:[function(e,t){"use strict";function n(e){function t(t,n,r,o,i){if(o=o||C,null!=n[r])return e(n,r,o,i);var a=g[i];return t?new Error("Required "+a+" `"+r+"` was not specified in "+("`"+o+"`.")):void 0}var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n}function r(e){function t(t,n,r,o){var i=t[n],a=h(i);if(a!==e){var s=g[o],u=v(i);return new Error("Invalid "+s+" `"+n+"` of type `"+u+"` "+("supplied to `"+r+"`, expected `"+e+"`."))}}return n(t)}function o(){return n(y.thatReturns())}function i(e){function t(t,n,r,o){var i=t[n];if(!Array.isArray(i)){var a=g[o],s=h(i);return new Error("Invalid "+a+" `"+n+"` of type "+("`"+s+"` supplied to `"+r+"`, expected an array."))}for(var u=0;u<i.length;u++){var c=e(i,u,r,o);if(c instanceof Error)return c}}return n(t)}function a(){function e(e,t,n,r){if(!m.isValidDescriptor(e[t])){var o=g[r];return new Error("Invalid "+o+" `"+t+"` supplied to "+("`"+n+"`, expected a React component."))}}return n(e)}function s(e){function t(t,n,r,o){if(!(t[n]instanceof e)){var i=g[o],a=e.name||C;return new Error("Invalid "+i+" `"+n+"` supplied to "+("`"+r+"`, expected instance of `"+a+"`."))}}return n(t)}function u(e){function t(t,n,r,o){for(var i=t[n],a=0;a<e.length;a++)if(i===e[a])return;var s=g[o],u=JSON.stringify(e);return new Error("Invalid "+s+" `"+n+"` of value `"+i+"` "+("supplied to `"+r+"`, expected one of "+u+"."))}return n(t)}function c(e){function t(t,n,r,o){var i=t[n],a=h(i);if("object"!==a){var s=g[o];return new Error("Invalid "+s+" `"+n+"` of type "+("`"+a+"` supplied to `"+r+"`, expected an object."))}for(var u in i)if(i.hasOwnProperty(u)){var c=e(i,u,r,o);if(c instanceof Error)return c}}return n(t)}function l(e){function t(t,n,r,o){for(var i=0;i<e.length;i++){var a=e[i];if(null==a(t,n,r,o))return}var s=g[o];return new Error("Invalid "+s+" `"+n+"` supplied to "+("`"+r+"`."))}return n(t)}function p(){function e(e,t,n,r){if(!f(e[t])){var o=g[r];return new Error("Invalid "+o+" `"+t+"` supplied to "+("`"+n+"`, expected a renderable prop."))}}return n(e)}function d(e){function t(t,n,r,o){var i=t[n],a=h(i);if("object"!==a){var s=g[o];return new Error("Invalid "+s+" `"+n+"` of type `"+a+"` "+("supplied to `"+r+"`, expected `object`."))}for(var u in e){var c=e[u];if(c){var l=c(i,u,r,o);if(l)return l}}}return n(t,"expected `object`")}function f(e){switch(typeof e){case"number":case"string":return!0;case"boolean":return!e;case"object":if(Array.isArray(e))return e.every(f);if(m.isValidDescriptor(e))return!0;for(var t in e)if(!f(e[t]))return!1;return!0;default:return!1}}function h(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":t}function v(e){var t=h(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}var m=e("./ReactDescriptor"),g=e("./ReactPropTypeLocationNames"),y=e("./emptyFunction"),C="<<anonymous>>",E={array:r("array"),bool:r("boolean"),func:r("function"),number:r("number"),object:r("object"),string:r("string"),any:o(),arrayOf:i,component:a(),instanceOf:s,objectOf:c,oneOf:u,oneOfType:l,renderable:p(),shape:d};t.exports=E},{"./ReactDescriptor":49,"./ReactPropTypeLocationNames":65,"./emptyFunction":100}],68:[function(e,t){"use strict";function n(){this.listenersToPut=[]}var r=e("./PooledClass"),o=e("./ReactBrowserEventEmitter"),i=e("./mixInto");i(n,{enqueuePutListener:function(e,t,n){this.listenersToPut.push({rootNodeID:e,propKey:t,propValue:n})},putListeners:function(){for(var e=0;e<this.listenersToPut.length;e++){var t=this.listenersToPut[e];o.putListener(t.rootNodeID,t.propKey,t.propValue)}},reset:function(){this.listenersToPut.length=0},destructor:function(){this.reset()}}),r.addPoolingTo(n),t.exports=n},{"./PooledClass":26,"./ReactBrowserEventEmitter":29,"./mixInto":131}],69:[function(e,t){"use strict";function n(){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=r.getPooled(null),this.putListenerQueue=s.getPooled()}var r=e("./CallbackQueue"),o=e("./PooledClass"),i=e("./ReactBrowserEventEmitter"),a=e("./ReactInputSelection"),s=e("./ReactPutListenerQueue"),u=e("./Transaction"),c=e("./mixInto"),l={initialize:a.getSelectionInformation,close:a.restoreSelection},p={initialize:function(){var e=i.isEnabled();return i.setEnabled(!1),e},close:function(e){i.setEnabled(e)}},d={initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}},f={initialize:function(){this.putListenerQueue.reset()},close:function(){this.putListenerQueue.putListeners()}},h=[f,l,p,d],v={getTransactionWrappers:function(){return h},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){r.release(this.reactMountReady),this.reactMountReady=null,s.release(this.putListenerQueue),this.putListenerQueue=null}};c(n,u.Mixin),c(n,v),o.addPoolingTo(n),t.exports=n},{"./CallbackQueue":5,"./PooledClass":26,"./ReactBrowserEventEmitter":29,"./ReactInputSelection":56,"./ReactPutListenerQueue":68,"./Transaction":90,"./mixInto":131}],70:[function(e,t){"use strict";var n={injectCreateReactRootIndex:function(e){r.createReactRootIndex=e}},r={createReactRootIndex:null,injection:n};t.exports=r},{}],71:[function(e,t){"use strict";function n(e){c(o.isValidDescriptor(e)),c(!(2===arguments.length&&"function"==typeof arguments[1]));var t;try{var n=i.createReactRootID();return t=s.getPooled(!1),t.perform(function(){var r=u(e),o=r.mountComponent(n,t,0);return a.addChecksumToMarkup(o)},null)}finally{s.release(t)}}function r(e){c(o.isValidDescriptor(e));var t;try{var n=i.createReactRootID();return t=s.getPooled(!0),t.perform(function(){var r=u(e);return r.mountComponent(n,t,0)},null)}finally{s.release(t)}}var o=e("./ReactDescriptor"),i=e("./ReactInstanceHandles"),a=e("./ReactMarkupChecksum"),s=e("./ReactServerRenderingTransaction"),u=e("./instantiateReactComponent"),c=e("./invariant");t.exports={renderComponentToString:n,renderComponentToStaticMarkup:r}},{"./ReactDescriptor":49,"./ReactInstanceHandles":57,"./ReactMarkupChecksum":58,"./ReactServerRenderingTransaction":72,"./instantiateReactComponent":117,"./invariant":118}],72:[function(e,t){"use strict";function n(e){this.reinitializeTransaction(),this.renderToStaticMarkup=e,this.reactMountReady=o.getPooled(null),this.putListenerQueue=i.getPooled()}var r=e("./PooledClass"),o=e("./CallbackQueue"),i=e("./ReactPutListenerQueue"),a=e("./Transaction"),s=e("./emptyFunction"),u=e("./mixInto"),c={initialize:function(){this.reactMountReady.reset()},close:s},l={initialize:function(){this.putListenerQueue.reset()},close:s},p=[l,c],d={getTransactionWrappers:function(){return p},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){o.release(this.reactMountReady),this.reactMountReady=null,i.release(this.putListenerQueue),this.putListenerQueue=null}};u(n,a.Mixin),u(n,d),r.addPoolingTo(n),t.exports=n},{"./CallbackQueue":5,"./PooledClass":26,"./ReactPutListenerQueue":68,"./Transaction":90,"./emptyFunction":100,"./mixInto":131}],73:[function(e,t){"use strict";var n=e("./DOMPropertyOperations"),r=e("./ReactBrowserComponentMixin"),o=e("./ReactComponent"),i=e("./ReactDescriptor"),a=e("./escapeTextForBrowser"),s=e("./mixInto"),u=function(e){this.construct(e)};s(u,o.Mixin),s(u,r),s(u,{mountComponent:function(e,t,r){o.Mixin.mountComponent.call(this,e,t,r);var i=a(this.props);return t.renderToStaticMarkup?i:"<span "+n.createMarkupForID(e)+">"+i+"</span>"},receiveComponent:function(e){var t=e.props;t!==this.props&&(this.props=t,o.BackendIDOperations.updateTextContentByID(this._rootNodeID,t))}}),t.exports=i.createFactory(u)},{"./DOMPropertyOperations":11,"./ReactBrowserComponentMixin":28,"./ReactComponent":31,"./ReactDescriptor":49,"./escapeTextForBrowser":102,"./mixInto":131}],74:[function(e,t){"use strict";function n(){d(R.ReactReconcileTransaction&&v)}function r(){this.reinitializeTransaction(),this.dirtyComponentsLength=null,this.callbackQueue=u.getPooled(null),this.reconcileTransaction=R.ReactReconcileTransaction.getPooled()}function o(e,t,r){n(),v.batchedUpdates(e,t,r)}function i(e,t){return e._mountDepth-t._mountDepth}function a(e){var t=e.dirtyComponentsLength;d(t===h.length),h.sort(i);for(var n=0;t>n;n++){var r=h[n];if(r.isMounted()){var o=r._pendingCallbacks;if(r._pendingCallbacks=null,r.performUpdateIfNecessary(e.reconcileTransaction),o)for(var a=0;a<o.length;a++)e.callbackQueue.enqueue(o[a],r)}}}function s(e,t){return d(!t||"function"==typeof t),n(),v.isBatchingUpdates?(h.push(e),void(t&&(e._pendingCallbacks?e._pendingCallbacks.push(t):e._pendingCallbacks=[t]))):void v.batchedUpdates(s,e,t)}var u=e("./CallbackQueue"),c=e("./PooledClass"),l=(e("./ReactCurrentOwner"),e("./ReactPerf")),p=e("./Transaction"),d=e("./invariant"),f=e("./mixInto"),h=(e("./warning"),[]),v=null,m={initialize:function(){this.dirtyComponentsLength=h.length},close:function(){this.dirtyComponentsLength!==h.length?(h.splice(0,this.dirtyComponentsLength),C()):h.length=0}},g={initialize:function(){this.callbackQueue.reset()},close:function(){this.callbackQueue.notifyAll()}},y=[m,g];f(r,p.Mixin),f(r,{getTransactionWrappers:function(){return y},destructor:function(){this.dirtyComponentsLength=null,u.release(this.callbackQueue),this.callbackQueue=null,R.ReactReconcileTransaction.release(this.reconcileTransaction),this.reconcileTransaction=null},perform:function(e,t,n){return p.Mixin.perform.call(this,this.reconcileTransaction.perform,this.reconcileTransaction,e,t,n)}}),c.addPoolingTo(r);var C=l.measure("ReactUpdates","flushBatchedUpdates",function(){for(;h.length;){var e=r.getPooled();e.perform(a,null,e),r.release(e)}}),E={injectReconcileTransaction:function(e){d(e),R.ReactReconcileTransaction=e},injectBatchingStrategy:function(e){d(e),d("function"==typeof e.batchedUpdates),d("boolean"==typeof e.isBatchingUpdates),v=e}},R={ReactReconcileTransaction:null,batchedUpdates:o,enqueueUpdate:s,flushBatchedUpdates:C,injection:E};t.exports=R},{"./CallbackQueue":5,"./PooledClass":26,"./ReactCurrentOwner":35,"./ReactPerf":63,"./Transaction":90,"./invariant":118,"./mixInto":131,"./warning":139}],75:[function(e,t){"use strict";var n=e("./DOMProperty"),r=n.injection.MUST_USE_ATTRIBUTE,o={Properties:{cx:r,cy:r,d:r,dx:r,dy:r,fill:r,fillOpacity:r,fontFamily:r,fontSize:r,fx:r,fy:r,gradientTransform:r,gradientUnits:r,markerEnd:r,markerMid:r,markerStart:r,offset:r,opacity:r,patternContentUnits:r,patternUnits:r,points:r,preserveAspectRatio:r,r:r,rx:r,ry:r,spreadMethod:r,stopColor:r,stopOpacity:r,stroke:r,strokeDasharray:r,strokeLinecap:r,strokeOpacity:r,strokeWidth:r,textAnchor:r,transform:r,version:r,viewBox:r,x1:r,x2:r,x:r,y1:r,y2:r,y:r},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"}};
t.exports=o},{"./DOMProperty":10}],76:[function(e,t){"use strict";function n(e){if("selectionStart"in e&&a.hasSelectionCapabilities(e))return{start:e.selectionStart,end:e.selectionEnd};if(document.selection){var t=document.selection.createRange();return{parentElement:t.parentElement(),text:t.text,top:t.boundingTop,left:t.boundingLeft}}var n=window.getSelection();return{anchorNode:n.anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset}}function r(e){if(!g&&null!=h&&h==u()){var t=n(h);if(!m||!p(m,t)){m=t;var r=s.getPooled(f.select,v,e);return r.type="select",r.target=h,i.accumulateTwoPhaseDispatches(r),r}}}var o=e("./EventConstants"),i=e("./EventPropagators"),a=e("./ReactInputSelection"),s=e("./SyntheticEvent"),u=e("./getActiveElement"),c=e("./isTextInputElement"),l=e("./keyOf"),p=e("./shallowEqual"),d=o.topLevelTypes,f={select:{phasedRegistrationNames:{bubbled:l({onSelect:null}),captured:l({onSelectCapture:null})},dependencies:[d.topBlur,d.topContextMenu,d.topFocus,d.topKeyDown,d.topMouseDown,d.topMouseUp,d.topSelectionChange]}},h=null,v=null,m=null,g=!1,y={eventTypes:f,extractEvents:function(e,t,n,o){switch(e){case d.topFocus:(c(t)||"true"===t.contentEditable)&&(h=t,v=n,m=null);break;case d.topBlur:h=null,v=null,m=null;break;case d.topMouseDown:g=!0;break;case d.topContextMenu:case d.topMouseUp:return g=!1,r(o);case d.topSelectionChange:case d.topKeyDown:case d.topKeyUp:return r(o)}}};t.exports=y},{"./EventConstants":15,"./EventPropagators":20,"./ReactInputSelection":56,"./SyntheticEvent":82,"./getActiveElement":106,"./isTextInputElement":121,"./keyOf":125,"./shallowEqual":135}],77:[function(e,t){"use strict";var n=Math.pow(2,53),r={createReactRootIndex:function(){return Math.ceil(Math.random()*n)}};t.exports=r},{}],78:[function(e,t){"use strict";var n=e("./EventConstants"),r=e("./EventPluginUtils"),o=e("./EventPropagators"),i=e("./SyntheticClipboardEvent"),a=e("./SyntheticEvent"),s=e("./SyntheticFocusEvent"),u=e("./SyntheticKeyboardEvent"),c=e("./SyntheticMouseEvent"),l=e("./SyntheticDragEvent"),p=e("./SyntheticTouchEvent"),d=e("./SyntheticUIEvent"),f=e("./SyntheticWheelEvent"),h=e("./invariant"),v=e("./keyOf"),m=n.topLevelTypes,g={blur:{phasedRegistrationNames:{bubbled:v({onBlur:!0}),captured:v({onBlurCapture:!0})}},click:{phasedRegistrationNames:{bubbled:v({onClick:!0}),captured:v({onClickCapture:!0})}},contextMenu:{phasedRegistrationNames:{bubbled:v({onContextMenu:!0}),captured:v({onContextMenuCapture:!0})}},copy:{phasedRegistrationNames:{bubbled:v({onCopy:!0}),captured:v({onCopyCapture:!0})}},cut:{phasedRegistrationNames:{bubbled:v({onCut:!0}),captured:v({onCutCapture:!0})}},doubleClick:{phasedRegistrationNames:{bubbled:v({onDoubleClick:!0}),captured:v({onDoubleClickCapture:!0})}},drag:{phasedRegistrationNames:{bubbled:v({onDrag:!0}),captured:v({onDragCapture:!0})}},dragEnd:{phasedRegistrationNames:{bubbled:v({onDragEnd:!0}),captured:v({onDragEndCapture:!0})}},dragEnter:{phasedRegistrationNames:{bubbled:v({onDragEnter:!0}),captured:v({onDragEnterCapture:!0})}},dragExit:{phasedRegistrationNames:{bubbled:v({onDragExit:!0}),captured:v({onDragExitCapture:!0})}},dragLeave:{phasedRegistrationNames:{bubbled:v({onDragLeave:!0}),captured:v({onDragLeaveCapture:!0})}},dragOver:{phasedRegistrationNames:{bubbled:v({onDragOver:!0}),captured:v({onDragOverCapture:!0})}},dragStart:{phasedRegistrationNames:{bubbled:v({onDragStart:!0}),captured:v({onDragStartCapture:!0})}},drop:{phasedRegistrationNames:{bubbled:v({onDrop:!0}),captured:v({onDropCapture:!0})}},focus:{phasedRegistrationNames:{bubbled:v({onFocus:!0}),captured:v({onFocusCapture:!0})}},input:{phasedRegistrationNames:{bubbled:v({onInput:!0}),captured:v({onInputCapture:!0})}},keyDown:{phasedRegistrationNames:{bubbled:v({onKeyDown:!0}),captured:v({onKeyDownCapture:!0})}},keyPress:{phasedRegistrationNames:{bubbled:v({onKeyPress:!0}),captured:v({onKeyPressCapture:!0})}},keyUp:{phasedRegistrationNames:{bubbled:v({onKeyUp:!0}),captured:v({onKeyUpCapture:!0})}},load:{phasedRegistrationNames:{bubbled:v({onLoad:!0}),captured:v({onLoadCapture:!0})}},error:{phasedRegistrationNames:{bubbled:v({onError:!0}),captured:v({onErrorCapture:!0})}},mouseDown:{phasedRegistrationNames:{bubbled:v({onMouseDown:!0}),captured:v({onMouseDownCapture:!0})}},mouseMove:{phasedRegistrationNames:{bubbled:v({onMouseMove:!0}),captured:v({onMouseMoveCapture:!0})}},mouseOut:{phasedRegistrationNames:{bubbled:v({onMouseOut:!0}),captured:v({onMouseOutCapture:!0})}},mouseOver:{phasedRegistrationNames:{bubbled:v({onMouseOver:!0}),captured:v({onMouseOverCapture:!0})}},mouseUp:{phasedRegistrationNames:{bubbled:v({onMouseUp:!0}),captured:v({onMouseUpCapture:!0})}},paste:{phasedRegistrationNames:{bubbled:v({onPaste:!0}),captured:v({onPasteCapture:!0})}},reset:{phasedRegistrationNames:{bubbled:v({onReset:!0}),captured:v({onResetCapture:!0})}},scroll:{phasedRegistrationNames:{bubbled:v({onScroll:!0}),captured:v({onScrollCapture:!0})}},submit:{phasedRegistrationNames:{bubbled:v({onSubmit:!0}),captured:v({onSubmitCapture:!0})}},touchCancel:{phasedRegistrationNames:{bubbled:v({onTouchCancel:!0}),captured:v({onTouchCancelCapture:!0})}},touchEnd:{phasedRegistrationNames:{bubbled:v({onTouchEnd:!0}),captured:v({onTouchEndCapture:!0})}},touchMove:{phasedRegistrationNames:{bubbled:v({onTouchMove:!0}),captured:v({onTouchMoveCapture:!0})}},touchStart:{phasedRegistrationNames:{bubbled:v({onTouchStart:!0}),captured:v({onTouchStartCapture:!0})}},wheel:{phasedRegistrationNames:{bubbled:v({onWheel:!0}),captured:v({onWheelCapture:!0})}}},y={topBlur:g.blur,topClick:g.click,topContextMenu:g.contextMenu,topCopy:g.copy,topCut:g.cut,topDoubleClick:g.doubleClick,topDrag:g.drag,topDragEnd:g.dragEnd,topDragEnter:g.dragEnter,topDragExit:g.dragExit,topDragLeave:g.dragLeave,topDragOver:g.dragOver,topDragStart:g.dragStart,topDrop:g.drop,topError:g.error,topFocus:g.focus,topInput:g.input,topKeyDown:g.keyDown,topKeyPress:g.keyPress,topKeyUp:g.keyUp,topLoad:g.load,topMouseDown:g.mouseDown,topMouseMove:g.mouseMove,topMouseOut:g.mouseOut,topMouseOver:g.mouseOver,topMouseUp:g.mouseUp,topPaste:g.paste,topReset:g.reset,topScroll:g.scroll,topSubmit:g.submit,topTouchCancel:g.touchCancel,topTouchEnd:g.touchEnd,topTouchMove:g.touchMove,topTouchStart:g.touchStart,topWheel:g.wheel};for(var C in y)y[C].dependencies=[C];var E={eventTypes:g,executeDispatch:function(e,t,n){var o=r.executeDispatch(e,t,n);o===!1&&(e.stopPropagation(),e.preventDefault())},extractEvents:function(e,t,n,r){var v=y[e];if(!v)return null;var g;switch(e){case m.topInput:case m.topLoad:case m.topError:case m.topReset:case m.topSubmit:g=a;break;case m.topKeyPress:if(0===r.charCode)return null;case m.topKeyDown:case m.topKeyUp:g=u;break;case m.topBlur:case m.topFocus:g=s;break;case m.topClick:if(2===r.button)return null;case m.topContextMenu:case m.topDoubleClick:case m.topMouseDown:case m.topMouseMove:case m.topMouseOut:case m.topMouseOver:case m.topMouseUp:g=c;break;case m.topDrag:case m.topDragEnd:case m.topDragEnter:case m.topDragExit:case m.topDragLeave:case m.topDragOver:case m.topDragStart:case m.topDrop:g=l;break;case m.topTouchCancel:case m.topTouchEnd:case m.topTouchMove:case m.topTouchStart:g=p;break;case m.topScroll:g=d;break;case m.topWheel:g=f;break;case m.topCopy:case m.topCut:case m.topPaste:g=i}h(g);var C=g.getPooled(v,n,r);return o.accumulateTwoPhaseDispatches(C),C}};t.exports=E},{"./EventConstants":15,"./EventPluginUtils":19,"./EventPropagators":20,"./SyntheticClipboardEvent":79,"./SyntheticDragEvent":81,"./SyntheticEvent":82,"./SyntheticFocusEvent":83,"./SyntheticKeyboardEvent":85,"./SyntheticMouseEvent":86,"./SyntheticTouchEvent":87,"./SyntheticUIEvent":88,"./SyntheticWheelEvent":89,"./invariant":118,"./keyOf":125}],79:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticEvent"),o={clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}};r.augmentClass(n,o),t.exports=n},{"./SyntheticEvent":82}],80:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticEvent"),o={data:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticEvent":82}],81:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticMouseEvent"),o={dataTransfer:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticMouseEvent":86}],82:[function(e,t){"use strict";function n(e,t,n){this.dispatchConfig=e,this.dispatchMarker=t,this.nativeEvent=n;var r=this.constructor.Interface;for(var i in r)if(r.hasOwnProperty(i)){var a=r[i];this[i]=a?a(n):n[i]}var s=null!=n.defaultPrevented?n.defaultPrevented:n.returnValue===!1;this.isDefaultPrevented=s?o.thatReturnsTrue:o.thatReturnsFalse,this.isPropagationStopped=o.thatReturnsFalse}var r=e("./PooledClass"),o=e("./emptyFunction"),i=e("./getEventTarget"),a=e("./merge"),s=e("./mergeInto"),u={type:null,target:i,currentTarget:o.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};s(n.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e.preventDefault?e.preventDefault():e.returnValue=!1,this.isDefaultPrevented=o.thatReturnsTrue},stopPropagation:function(){var e=this.nativeEvent;e.stopPropagation?e.stopPropagation():e.cancelBubble=!0,this.isPropagationStopped=o.thatReturnsTrue},persist:function(){this.isPersistent=o.thatReturnsTrue},isPersistent:o.thatReturnsFalse,destructor:function(){var e=this.constructor.Interface;for(var t in e)this[t]=null;this.dispatchConfig=null,this.dispatchMarker=null,this.nativeEvent=null}}),n.Interface=u,n.augmentClass=function(e,t){var n=this,o=Object.create(n.prototype);s(o,e.prototype),e.prototype=o,e.prototype.constructor=e,e.Interface=a(n.Interface,t),e.augmentClass=n.augmentClass,r.addPoolingTo(e,r.threeArgumentPooler)},r.addPoolingTo(n,r.threeArgumentPooler),t.exports=n},{"./PooledClass":26,"./emptyFunction":100,"./getEventTarget":109,"./merge":128,"./mergeInto":130}],83:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticUIEvent"),o={relatedTarget:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticUIEvent":88}],84:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticEvent"),o={data:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticEvent":82}],85:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticUIEvent"),o=e("./getEventKey"),i=e("./getEventModifierState"),a={key:o,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:i,charCode:function(e){return"keypress"===e.type?"charCode"in e?e.charCode:e.keyCode:0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return e.keyCode||e.charCode}};r.augmentClass(n,a),t.exports=n},{"./SyntheticUIEvent":88,"./getEventKey":107,"./getEventModifierState":108}],86:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticUIEvent"),o=e("./ViewportMetrics"),i=e("./getEventModifierState"),a={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:i,button:function(e){var t=e.button;return"which"in e?t:2===t?2:4===t?1:0},buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},pageX:function(e){return"pageX"in e?e.pageX:e.clientX+o.currentScrollLeft},pageY:function(e){return"pageY"in e?e.pageY:e.clientY+o.currentScrollTop}};r.augmentClass(n,a),t.exports=n},{"./SyntheticUIEvent":88,"./ViewportMetrics":91,"./getEventModifierState":108}],87:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticUIEvent"),o=e("./getEventModifierState"),i={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:o};r.augmentClass(n,i),t.exports=n},{"./SyntheticUIEvent":88,"./getEventModifierState":108}],88:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticEvent"),o=e("./getEventTarget"),i={view:function(e){if(e.view)return e.view;var t=o(e);if(null!=t&&t.window===t)return t;var n=t.ownerDocument;return n?n.defaultView||n.parentWindow:window},detail:function(e){return e.detail||0}};r.augmentClass(n,i),t.exports=n},{"./SyntheticEvent":82,"./getEventTarget":109}],89:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticMouseEvent"),o={deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticMouseEvent":86}],90:[function(e,t){"use strict";var n=e("./invariant"),r={reinitializeTransaction:function(){this.transactionWrappers=this.getTransactionWrappers(),this.wrapperInitData?this.wrapperInitData.length=0:this.wrapperInitData=[],this._isInTransaction=!1},_isInTransaction:!1,getTransactionWrappers:null,isInTransaction:function(){return!!this._isInTransaction},perform:function(e,t,r,o,i,a,s,u){n(!this.isInTransaction());var c,l;try{this._isInTransaction=!0,c=!0,this.initializeAll(0),l=e.call(t,r,o,i,a,s,u),c=!1}finally{try{if(c)try{this.closeAll(0)}catch(p){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return l},initializeAll:function(e){for(var t=this.transactionWrappers,n=e;n<t.length;n++){var r=t[n];try{this.wrapperInitData[n]=o.OBSERVED_ERROR,this.wrapperInitData[n]=r.initialize?r.initialize.call(this):null}finally{if(this.wrapperInitData[n]===o.OBSERVED_ERROR)try{this.initializeAll(n+1)}catch(i){}}}},closeAll:function(e){n(this.isInTransaction());for(var t=this.transactionWrappers,r=e;r<t.length;r++){var i,a=t[r],s=this.wrapperInitData[r];try{i=!0,s!==o.OBSERVED_ERROR&&a.close&&a.close.call(this,s),i=!1}finally{if(i)try{this.closeAll(r+1)}catch(u){}}}this.wrapperInitData.length=0}},o={Mixin:r,OBSERVED_ERROR:{}};t.exports=o},{"./invariant":118}],91:[function(e,t){"use strict";var n=e("./getUnboundedScrollPosition"),r={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(){var e=n(window);r.currentScrollLeft=e.x,r.currentScrollTop=e.y}};t.exports=r},{"./getUnboundedScrollPosition":114}],92:[function(e,t){"use strict";function n(e,t){if(r(null!=t),null==e)return t;var n=Array.isArray(e),o=Array.isArray(t);return n?e.concat(t):o?[e].concat(t):[e,t]}var r=e("./invariant");t.exports=n},{"./invariant":118}],93:[function(e,t){"use strict";function n(e){for(var t=1,n=0,o=0;o<e.length;o++)t=(t+e.charCodeAt(o))%r,n=(n+t)%r;return t|n<<16}var r=65521;t.exports=n},{}],94:[function(e,t){function n(e,t){return e&&t?e===t?!0:r(e)?!1:r(t)?n(e,t.parentNode):e.contains?e.contains(t):e.compareDocumentPosition?!!(16&e.compareDocumentPosition(t)):!1:!1}var r=e("./isTextNode");t.exports=n},{"./isTextNode":122}],95:[function(e,t){function n(e,t,n,r,o,i){e=e||{};for(var a,s=[t,n,r,o,i],u=0;s[u];){a=s[u++];for(var c in a)e[c]=a[c];a.hasOwnProperty&&a.hasOwnProperty("toString")&&"undefined"!=typeof a.toString&&e.toString!==a.toString&&(e.toString=a.toString)}return e}t.exports=n},{}],96:[function(e,t){function n(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"length"in e&&!("setInterval"in e)&&"number"!=typeof e.nodeType&&(Array.isArray(e)||"callee"in e||"item"in e)}function r(e){return n(e)?Array.isArray(e)?e.slice():o(e):[e]}var o=e("./toArray");t.exports=r},{"./toArray":137}],97:[function(e,t){"use strict";function n(e){var t=r.createClass({displayName:"ReactFullPageComponent"+(e.type.displayName||""),componentWillUnmount:function(){o(!1)},render:function(){return this.transferPropsTo(e(null,this.props.children))}});return t}var r=e("./ReactCompositeComponent"),o=e("./invariant");t.exports=n},{"./ReactCompositeComponent":33,"./invariant":118}],98:[function(e,t){function n(e){var t=e.match(c);return t&&t[1].toLowerCase()}function r(e,t){var r=u;s(!!u);var o=n(e),c=o&&a(o);if(c){r.innerHTML=c[1]+e+c[2];for(var l=c[0];l--;)r=r.lastChild}else r.innerHTML=e;var p=r.getElementsByTagName("script");p.length&&(s(t),i(p).forEach(t));for(var d=i(r.childNodes);r.lastChild;)r.removeChild(r.lastChild);return d}var o=e("./ExecutionEnvironment"),i=e("./createArrayFrom"),a=e("./getMarkupWrap"),s=e("./invariant"),u=o.canUseDOM?document.createElement("div"):null,c=/^\s*<(\w+)/;t.exports=r},{"./ExecutionEnvironment":21,"./createArrayFrom":96,"./getMarkupWrap":110,"./invariant":118}],99:[function(e,t){"use strict";function n(e,t){var n=null==t||"boolean"==typeof t||""===t;if(n)return"";var r=isNaN(t);return r||0===t||o.hasOwnProperty(e)&&o[e]?""+t:("string"==typeof t&&(t=t.trim()),t+"px")}var r=e("./CSSProperty"),o=r.isUnitlessNumber;t.exports=n},{"./CSSProperty":3}],100:[function(e,t){function n(e){return function(){return e}}function r(){}var o=e("./copyProperties");o(r,{thatReturns:n,thatReturnsFalse:n(!1),thatReturnsTrue:n(!0),thatReturnsNull:n(null),thatReturnsThis:function(){return this},thatReturnsArgument:function(e){return e}}),t.exports=r},{"./copyProperties":95}],101:[function(e,t){"use strict";var n={};t.exports=n},{}],102:[function(e,t){"use strict";function n(e){return o[e]}function r(e){return(""+e).replace(i,n)}var o={"&":"&",">":">","<":"<",'"':""","'":"'"},i=/[&><"']/g;t.exports=r},{}],103:[function(e,t){"use strict";function n(e,t,n){var r=e,o=!r.hasOwnProperty(n);o&&null!=t&&(r[n]=t)}function r(e){if(null==e)return e;var t={};return o(e,n,t),t}{var o=e("./traverseAllChildren");e("./warning")}t.exports=r},{"./traverseAllChildren":138,"./warning":139}],104:[function(e,t){"use strict";function n(e){e.disabled||e.focus()}t.exports=n},{}],105:[function(e,t){"use strict";var n=function(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)};t.exports=n},{}],106:[function(e,t){function n(){try{return document.activeElement||document.body}catch(e){return document.body}}t.exports=n},{}],107:[function(e,t){"use strict";function n(e){if(e.key){var t=o[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n="charCode"in e?e.charCode:e.keyCode;return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?i[e.keyCode]||"Unidentified":void r(!1)}var r=e("./invariant"),o={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},i={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"};t.exports=n},{"./invariant":118}],108:[function(e,t){"use strict";function n(e){var t=this,n=t.nativeEvent;if(n.getModifierState)return n.getModifierState(e);var r=o[e];return r?!!n[r]:!1}function r(){return n}var o={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};t.exports=r},{}],109:[function(e,t){"use strict";function n(e){var t=e.target||e.srcElement||window;return 3===t.nodeType?t.parentNode:t}t.exports=n},{}],110:[function(e,t){function n(e){return o(!!i),p.hasOwnProperty(e)||(e="*"),a.hasOwnProperty(e)||(i.innerHTML="*"===e?"<link />":"<"+e+"></"+e+">",a[e]=!i.firstChild),a[e]?p[e]:null}var r=e("./ExecutionEnvironment"),o=e("./invariant"),i=r.canUseDOM?document.createElement("div"):null,a={circle:!0,defs:!0,ellipse:!0,g:!0,line:!0,linearGradient:!0,path:!0,polygon:!0,polyline:!0,radialGradient:!0,rect:!0,stop:!0,text:!0},s=[1,'<select multiple="true">',"</select>"],u=[1,"<table>","</table>"],c=[3,"<table><tbody><tr>","</tr></tbody></table>"],l=[1,"<svg>","</svg>"],p={"*":[1,"?<div>","</div>"],area:[1,"<map>","</map>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],legend:[1,"<fieldset>","</fieldset>"],param:[1,"<object>","</object>"],tr:[2,"<table><tbody>","</tbody></table>"],optgroup:s,option:s,caption:u,colgroup:u,tbody:u,tfoot:u,thead:u,td:c,th:c,circle:l,defs:l,ellipse:l,g:l,line:l,linearGradient:l,path:l,polygon:l,polyline:l,radialGradient:l,rect:l,stop:l,text:l};t.exports=n},{"./ExecutionEnvironment":21,"./invariant":118}],111:[function(e,t){"use strict";function n(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function r(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function o(e,t){for(var o=n(e),i=0,a=0;o;){if(3==o.nodeType){if(a=i+o.textContent.length,t>=i&&a>=t)return{node:o,offset:t-i};i=a}o=n(r(o))}}t.exports=o},{}],112:[function(e,t){"use strict";function n(e){return e?e.nodeType===r?e.documentElement:e.firstChild:null}var r=9;t.exports=n},{}],113:[function(e,t){"use strict";function n(){return!o&&r.canUseDOM&&(o="textContent"in document.documentElement?"textContent":"innerText"),o}var r=e("./ExecutionEnvironment"),o=null;t.exports=n},{"./ExecutionEnvironment":21}],114:[function(e,t){"use strict";function n(e){return e===window?{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}t.exports=n},{}],115:[function(e,t){function n(e){return e.replace(r,"-$1").toLowerCase()}var r=/([A-Z])/g;t.exports=n},{}],116:[function(e,t){"use strict";function n(e){return r(e).replace(o,"-ms-")}var r=e("./hyphenate"),o=/^ms-/;t.exports=n},{"./hyphenate":115}],117:[function(e,t){"use strict";function n(e){return e&&"function"==typeof e.type&&"function"==typeof e.type.prototype.mountComponent&&"function"==typeof e.type.prototype.receiveComponent}function r(e){return o(n(e)),new e.type(e)}var o=e("./invariant");t.exports=r},{"./invariant":118}],118:[function(e,t){"use strict";var n=function(e,t,n,r,o,i,a,s){if(!e){var u;if(void 0===t)u=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[n,r,o,i,a,s],l=0;u=new Error("Invariant Violation: "+t.replace(/%s/g,function(){return c[l++]}))}throw u.framesToPop=1,u}};t.exports=n},{}],119:[function(e,t){"use strict";function n(e,t){if(!o.canUseDOM||t&&!("addEventListener"in document))return!1;var n="on"+e,i=n in document;if(!i){var a=document.createElement("div");a.setAttribute(n,"return;"),i="function"==typeof a[n]}return!i&&r&&"wheel"===e&&(i=document.implementation.hasFeature("Events.wheel","3.0")),i}var r,o=e("./ExecutionEnvironment");o.canUseDOM&&(r=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),t.exports=n},{"./ExecutionEnvironment":21}],120:[function(e,t){function n(e){return!(!e||!("function"==typeof Node?e instanceof Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}t.exports=n},{}],121:[function(e,t){"use strict";function n(e){return e&&("INPUT"===e.nodeName&&r[e.type]||"TEXTAREA"===e.nodeName)}var r={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};t.exports=n},{}],122:[function(e,t){function n(e){return r(e)&&3==e.nodeType}var r=e("./isNode");t.exports=n},{"./isNode":120}],123:[function(e,t){"use strict";function n(e){e||(e="");var t,n=arguments.length;if(n>1)for(var r=1;n>r;r++)t=arguments[r],t&&(e+=" "+t);return e}t.exports=n},{}],124:[function(e,t){"use strict";var n=e("./invariant"),r=function(e){var t,r={};n(e instanceof Object&&!Array.isArray(e));for(t in e)e.hasOwnProperty(t)&&(r[t]=t);return r};t.exports=r},{"./invariant":118}],125:[function(e,t){var n=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};t.exports=n},{}],126:[function(e,t){"use strict";function n(e,t,n){if(!e)return null;var r=0,o={};for(var i in e)e.hasOwnProperty(i)&&(o[i]=t.call(n,e[i],i,r++));return o}t.exports=n},{}],127:[function(e,t){"use strict";function n(e){var t={};return function(n){return t.hasOwnProperty(n)?t[n]:t[n]=e.call(this,n)}}t.exports=n},{}],128:[function(e,t){"use strict";var n=e("./mergeInto"),r=function(e,t){var r={};return n(r,e),n(r,t),r};t.exports=r},{"./mergeInto":130}],129:[function(e,t){"use strict";var n=e("./invariant"),r=e("./keyMirror"),o=36,i=function(e){return"object"!=typeof e||null===e},a={MAX_MERGE_DEPTH:o,isTerminal:i,normalizeMergeArg:function(e){return void 0===e||null===e?{}:e},checkMergeArrayArgs:function(e,t){n(Array.isArray(e)&&Array.isArray(t))},checkMergeObjectArgs:function(e,t){a.checkMergeObjectArg(e),a.checkMergeObjectArg(t)},checkMergeObjectArg:function(e){n(!i(e)&&!Array.isArray(e))},checkMergeIntoObjectArg:function(e){n(!(i(e)&&"function"!=typeof e||Array.isArray(e)))},checkMergeLevel:function(e){n(o>e)},checkArrayStrategy:function(e){n(void 0===e||e in a.ArrayStrategies)},ArrayStrategies:r({Clobber:!0,IndexByIndex:!0})};t.exports=a},{"./invariant":118,"./keyMirror":124}],130:[function(e,t){"use strict";function n(e,t){if(i(e),null!=t){o(t);for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])}}var r=e("./mergeHelpers"),o=r.checkMergeObjectArg,i=r.checkMergeIntoObjectArg;t.exports=n},{"./mergeHelpers":129}],131:[function(e,t){"use strict";var n=function(e,t){var n;for(n in t)t.hasOwnProperty(n)&&(e.prototype[n]=t[n])};t.exports=n},{}],132:[function(e,t){"use strict";function n(e){r(e&&!/[^a-z0-9_]/.test(e))}var r=e("./invariant");t.exports=n},{"./invariant":118}],133:[function(e,t){"use strict";function n(e){return o(r.isValidDescriptor(e)),e}var r=e("./ReactDescriptor"),o=e("./invariant");t.exports=n},{"./ReactDescriptor":49,"./invariant":118}],134:[function(e,t){"use strict";var n=e("./ExecutionEnvironment"),r=function(e,t){e.innerHTML=t};if(n.canUseDOM){var o=document.createElement("div");o.innerHTML=" ",""===o.innerHTML&&(r=function(e,t){if(e.parentNode&&e.parentNode.replaceChild(e,e),t.match(/^[ \r\n\t\f]/)||"<"===t[0]&&(-1!==t.indexOf("<noscript")||-1!==t.indexOf("<script")||-1!==t.indexOf("<style")||-1!==t.indexOf("<meta")||-1!==t.indexOf("<link"))){e.innerHTML=""+t;var n=e.firstChild;1===n.data.length?e.removeChild(n):n.deleteData(0,1)}else e.innerHTML=t})}t.exports=r},{"./ExecutionEnvironment":21}],135:[function(e,t){"use strict";function n(e,t){if(e===t)return!0;var n;for(n in e)if(e.hasOwnProperty(n)&&(!t.hasOwnProperty(n)||e[n]!==t[n]))return!1;for(n in t)if(t.hasOwnProperty(n)&&!e.hasOwnProperty(n))return!1;return!0}t.exports=n},{}],136:[function(e,t){"use strict";function n(e,t){return e&&t&&e.type===t.type&&(e.props&&e.props.key)===(t.props&&t.props.key)&&e._owner===t._owner?!0:!1}t.exports=n},{}],137:[function(e,t){function n(e){var t=e.length;if(r(!Array.isArray(e)&&("object"==typeof e||"function"==typeof e)),r("number"==typeof t),r(0===t||t-1 in e),e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(n){}for(var o=Array(t),i=0;t>i;i++)o[i]=e[i];return o}var r=e("./invariant");t.exports=n},{"./invariant":118}],138:[function(e,t){"use strict";function n(e){return d[e]}function r(e,t){return e&&e.props&&null!=e.props.key?i(e.props.key):t.toString(36)}function o(e){return(""+e).replace(f,n)}function i(e){return"$"+o(e)}function a(e,t,n){return null==e?0:h(e,"",0,t,n)}var s=e("./ReactInstanceHandles"),u=e("./ReactTextComponent"),c=e("./invariant"),l=s.SEPARATOR,p=":",d={"=":"=0",".":"=1",":":"=2"},f=/[=.:]/g,h=function(e,t,n,o,a){var s=0;if(Array.isArray(e))for(var d=0;d<e.length;d++){var f=e[d],v=t+(t?p:l)+r(f,d),m=n+s;s+=h(f,v,m,o,a)}else{var g=typeof e,y=""===t,C=y?l+r(e,0):t;if(null==e||"boolean"===g)o(a,null,C,n),s=1;else if(e.type&&e.type.prototype&&e.type.prototype.mountComponentIntoNode)o(a,e,C,n),s=1;else if("object"===g){c(!e||1!==e.nodeType);for(var E in e)e.hasOwnProperty(E)&&(s+=h(e[E],t+(t?p:l)+i(E)+p+r(e[E],0),n+s,o,a))}else if("string"===g){var R=u(e);o(a,R,C,n),s+=1}else if("number"===g){var M=u(""+e);o(a,M,C,n),s+=1}}return s};t.exports=a},{"./ReactInstanceHandles":57,"./ReactTextComponent":73,"./invariant":118}],139:[function(e,t){"use strict";var n=e("./emptyFunction"),r=n;t.exports=r},{"./emptyFunction":100}]},{},[27])(27)});
|
src/svg-icons/content/add-circle.js
|
manchesergit/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentAddCircle = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 11h-4v4h-2v-4H7v-2h4V7h2v4h4v2z"/>
</SvgIcon>
);
ContentAddCircle = pure(ContentAddCircle);
ContentAddCircle.displayName = 'ContentAddCircle';
ContentAddCircle.muiName = 'SvgIcon';
export default ContentAddCircle;
|
admin/src/components/DashBoard/DashBoard.js
|
nathandao/vantaa
|
import React from 'react';
import RequireAuthentication from 'decorators/RequireAuthentication';
@RequireAuthentication
class DashBoard extends React.Component {
constructor(props) {
super(props)
}
render() {
return(
<div className="interation-container">
<div className="interaction-area"></div>
<div className="interaction-message"></div>
<div className="interaction-commands"></div>
</div>
);
}
}
export default DashBoard;
|
packages/material-ui/src/OutlinedInput/OutlinedInput.js
|
kybarg/material-ui
|
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { refType } from '@material-ui/utils';
import InputBase from '../InputBase';
import NotchedOutline from './NotchedOutline';
import withStyles from '../styles/withStyles';
export const styles = theme => {
const borderColor =
theme.palette.type === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)';
return {
/* Styles applied to the root element. */
root: {
position: 'relative',
'&:hover $notchedOutline': {
borderColor: theme.palette.text.primary,
},
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
'&:hover $notchedOutline': {
borderColor,
},
},
'&$focused $notchedOutline': {
borderColor: theme.palette.primary.main,
borderWidth: 2,
},
'&$error $notchedOutline': {
borderColor: theme.palette.error.main,
},
'&$disabled $notchedOutline': {
borderColor: theme.palette.action.disabled,
},
},
/* Styles applied to the root element if the component is focused. */
focused: {},
/* Styles applied to the root element if `disabled={true}`. */
disabled: {},
/* Styles applied to the root element if `startAdornment` is provided. */
adornedStart: {
paddingLeft: 14,
},
/* Styles applied to the root element if `endAdornment` is provided. */
adornedEnd: {
paddingRight: 14,
},
/* Styles applied to the root element if `error={true}`. */
error: {},
/* Styles applied to the `input` element if `margin="dense"`. */
marginDense: {},
/* Styles applied to the root element if `multiline={true}`. */
multiline: {
padding: '18.5px 14px',
'&$marginDense': {
paddingTop: 10.5,
paddingBottom: 10.5,
},
},
/* Styles applied to the `NotchedOutline` element. */
notchedOutline: {
borderColor,
},
/* Styles applied to the `input` element. */
input: {
padding: '18.5px 14px',
},
/* Styles applied to the `input` element if `margin="dense"`. */
inputMarginDense: {
paddingTop: 10.5,
paddingBottom: 10.5,
},
/* Styles applied to the `input` element if `select={true}`. */
inputSelect: {
paddingRight: 24,
},
/* Styles applied to the `input` element if `multiline={true}`. */
inputMultiline: {
padding: 0,
},
/* Styles applied to the `input` element if `startAdornment` is provided. */
inputAdornedStart: {
paddingLeft: 0,
},
/* Styles applied to the `input` element if `endAdornment` is provided. */
inputAdornedEnd: {
paddingRight: 0,
},
};
};
const OutlinedInput = React.forwardRef(function OutlinedInput(props, ref) {
const {
classes,
fullWidth = false,
inputComponent = 'input',
labelWidth = 0,
multiline = false,
notched,
type = 'text',
...other
} = props;
return (
<InputBase
renderSuffix={state => (
<NotchedOutline
className={classes.notchedOutline}
labelWidth={labelWidth}
notched={
typeof notched !== 'undefined'
? notched
: Boolean(state.startAdornment || state.filled || state.focused)
}
/>
)}
classes={{
...classes,
root: clsx(classes.root, classes.underline),
notchedOutline: null,
}}
fullWidth={fullWidth}
inputComponent={inputComponent}
multiline={multiline}
ref={ref}
type={type}
{...other}
/>
);
});
OutlinedInput.propTypes = {
/**
* This prop helps users to fill forms faster, especially on mobile devices.
* The name can be confusing, as it's more like an autofill.
* You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).
*/
autoComplete: PropTypes.string,
/**
* If `true`, the `input` element will be focused during the first mount.
*/
autoFocus: PropTypes.bool,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* The CSS class name of the wrapper element.
*/
className: PropTypes.string,
/**
* The default `input` element value. Use when the component is not controlled.
*/
defaultValue: PropTypes.any,
/**
* If `true`, the `input` element will be disabled.
*/
disabled: PropTypes.bool,
/**
* End `InputAdornment` for this component.
*/
endAdornment: PropTypes.node,
/**
* If `true`, the input will indicate an error. This is normally obtained via context from
* FormControl.
*/
error: PropTypes.bool,
/**
* If `true`, the input will take up the full width of its container.
*/
fullWidth: PropTypes.bool,
/**
* The id of the `input` element.
*/
id: PropTypes.string,
/**
* The component used for the native input.
* Either a string to use a DOM element or a component.
*/
inputComponent: PropTypes.elementType,
/**
* [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
*/
inputProps: PropTypes.object,
/**
* Pass a ref to the `input` element.
*/
inputRef: refType,
/**
* The width of the label.
*/
labelWidth: PropTypes.number,
/**
* If `dense`, will adjust vertical spacing. This is normally obtained via context from
* FormControl.
*/
margin: PropTypes.oneOf(['dense', 'none']),
/**
* If `true`, a textarea element will be rendered.
*/
multiline: PropTypes.bool,
/**
* Name attribute of the `input` element.
*/
name: PropTypes.string,
/**
* If `true`, the outline is notched to accommodate the label.
*/
notched: PropTypes.bool,
/**
* Callback fired when the value is changed.
*
* @param {object} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (string).
*/
onChange: PropTypes.func,
/**
* The short hint displayed in the input before the user enters a value.
*/
placeholder: PropTypes.string,
/**
* It prevents the user from changing the value of the field
* (not from interacting with the field).
*/
readOnly: PropTypes.bool,
/**
* If `true`, the `input` element will be required.
*/
required: PropTypes.bool,
/**
* Number of rows to display when multiline option is set to true.
*/
rows: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/**
* Maximum number of rows to display when multiline option is set to true.
*/
rowsMax: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/**
* Start `InputAdornment` for this component.
*/
startAdornment: PropTypes.node,
/**
* Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).
*/
type: PropTypes.string,
/**
* The value of the `input` element, required for a controlled component.
*/
value: PropTypes.any,
};
OutlinedInput.muiName = 'Input';
export default withStyles(styles, { name: 'MuiOutlinedInput' })(OutlinedInput);
|
themes/flatly/scripts/jquery.min.js
|
spark-developer/custom-docstrap
|
/*! jQuery v1.8.3 jquery.com | jquery.org/license */
(function(e, t) {
function _(e) {
var t = M[e] = {};
return v.each(e.split(y), function(e, n) {
t[n] = !0
}), t
}
function H(e, n, r) {
if (r === t && e.nodeType === 1) {
var i = "data-" + n.replace(P, "-$1").toLowerCase();
r = e.getAttribute(i);
if (typeof r == "string") {
try {
r = r === "true" ? !0 : r === "false" ? !1 : r === "null" ? null : +r + "" === r ? +r : D.test(r) ? v.parseJSON(r) : r
} catch (s) {}
v.data(e, n, r)
} else r = t
}
return r
}
function B(e) {
var t;
for (t in e) {
if (t === "data" && v.isEmptyObject(e[t])) continue;
if (t !== "toJSON") return !1
}
return !0
}
function et() {
return !1
}
function tt() {
return !0
}
function ut(e) {
return !e || !e.parentNode || e.parentNode.nodeType === 11
}
function at(e, t) {
do e = e[t];
while (e && e.nodeType !== 1);
return e
}
function ft(e, t, n) {
t = t || 0;
if (v.isFunction(t)) return v.grep(e, function(e, r) {
var i = !! t.call(e, r, e);
return i === n
});
if (t.nodeType) return v.grep(e, function(e, r) {
return e === t === n
});
if (typeof t == "string") {
var r = v.grep(e, function(e) {
return e.nodeType === 1
});
if (it.test(t)) return v.filter(t, r, !n);
t = v.filter(t, r)
}
return v.grep(e, function(e, r) {
return v.inArray(e, t) >= 0 === n
})
}
function lt(e) {
var t = ct.split("|"),
n = e.createDocumentFragment();
if (n.createElement) while (t.length) n.createElement(t.pop());
return n
}
function Lt(e, t) {
return e.getElementsByTagName(t)[0] || e.appendChild(e.ownerDocument.createElement(t))
}
function At(e, t) {
if (t.nodeType !== 1 || !v.hasData(e)) return;
var n, r, i, s = v._data(e),
o = v._data(t, s),
u = s.events;
if (u) {
delete o.handle, o.events = {};
for (n in u) for (r = 0, i = u[n].length; r < i; r++) v.event.add(t, n, u[n][r])
}
o.data && (o.data = v.extend({}, o.data))
}
function Ot(e, t) {
var n;
if (t.nodeType !== 1) return;
t.clearAttributes && t.clearAttributes(), t.mergeAttributes && t.mergeAttributes(e), n = t.nodeName.toLowerCase(), n === "object" ? (t.parentNode && (t.outerHTML = e.outerHTML), v.support.html5Clone && e.innerHTML && !v.trim(t.innerHTML) && (t.innerHTML = e.innerHTML)) : n === "input" && Et.test(e.type) ? (t.defaultChecked = t.checked = e.checked, t.value !== e.value && (t.value = e.value)) : n === "option" ? t.selected = e.defaultSelected : n === "input" || n === "textarea" ? t.defaultValue = e.defaultValue : n === "script" && t.text !== e.text && (t.text = e.text), t.removeAttribute(v.expando)
}
function Mt(e) {
return typeof e.getElementsByTagName != "undefined" ? e.getElementsByTagName("*") : typeof e.querySelectorAll != "undefined" ? e.querySelectorAll("*") : []
}
function _t(e) {
Et.test(e.type) && (e.defaultChecked = e.checked)
}
function Qt(e, t) {
if (t in e) return t;
var n = t.charAt(0).toUpperCase() + t.slice(1),
r = t,
i = Jt.length;
while (i--) {
t = Jt[i] + n;
if (t in e) return t
}
return r
}
function Gt(e, t) {
return e = t || e, v.css(e, "display") === "none" || !v.contains(e.ownerDocument, e)
}
function Yt(e, t) {
var n, r, i = [],
s = 0,
o = e.length;
for (; s < o; s++) {
n = e[s];
if (!n.style) continue;
i[s] = v._data(n, "olddisplay"), t ? (!i[s] && n.style.display === "none" && (n.style.display = ""), n.style.display === "" && Gt(n) && (i[s] = v._data(n, "olddisplay", nn(n.nodeName)))) : (r = Dt(n, "display"), !i[s] && r !== "none" && v._data(n, "olddisplay", r))
}
for (s = 0; s < o; s++) {
n = e[s];
if (!n.style) continue;
if (!t || n.style.display === "none" || n.style.display === "") n.style.display = t ? i[s] || "" : "none"
}
return e
}
function Zt(e, t, n) {
var r = Rt.exec(t);
return r ? Math.max(0, r[1] - (n || 0)) + (r[2] || "px") : t
}
function en(e, t, n, r) {
var i = n === (r ? "border" : "content") ? 4 : t === "width" ? 1 : 0,
s = 0;
for (; i < 4; i += 2) n === "margin" && (s += v.css(e, n + $t[i], !0)), r ? (n === "content" && (s -= parseFloat(Dt(e, "padding" + $t[i])) || 0), n !== "margin" && (s -= parseFloat(Dt(e, "border" + $t[i] + "Width")) || 0)) : (s += parseFloat(Dt(e, "padding" + $t[i])) || 0, n !== "padding" && (s += parseFloat(Dt(e, "border" + $t[i] + "Width")) || 0));
return s
}
function tn(e, t, n) {
var r = t === "width" ? e.offsetWidth : e.offsetHeight,
i = !0,
s = v.support.boxSizing && v.css(e, "boxSizing") === "border-box";
if (r <= 0 || r == null) {
r = Dt(e, t);
if (r < 0 || r == null) r = e.style[t];
if (Ut.test(r)) return r;
i = s && (v.support.boxSizingReliable || r === e.style[t]), r = parseFloat(r) || 0
}
return r + en(e, t, n || (s ? "border" : "content"), i) + "px"
}
function nn(e) {
if (Wt[e]) return Wt[e];
var t = v("<" + e + ">").appendTo(i.body),
n = t.css("display");
t.remove();
if (n === "none" || n === "") {
Pt = i.body.appendChild(Pt || v.extend(i.createElement("iframe"), {
frameBorder: 0,
width: 0,
height: 0
}));
if (!Ht || !Pt.createElement) Ht = (Pt.contentWindow || Pt.contentDocument).document, Ht.write("<!doctype html><html><body>"), Ht.close();
t = Ht.body.appendChild(Ht.createElement(e)), n = Dt(t, "display"), i.body.removeChild(Pt)
}
return Wt[e] = n, n
}
function fn(e, t, n, r) {
var i;
if (v.isArray(t)) v.each(t, function(t, i) {
n || sn.test(e) ? r(e, i) : fn(e + "[" + (typeof i == "object" ? t : "") + "]", i, n, r)
});
else if (!n && v.type(t) === "object") for (i in t) fn(e + "[" + i + "]", t[i], n, r);
else r(e, t)
}
function Cn(e) {
return function(t, n) {
typeof t != "string" && (n = t, t = "*");
var r, i, s, o = t.toLowerCase().split(y),
u = 0,
a = o.length;
if (v.isFunction(n)) for (; u < a; u++) r = o[u], s = /^\+/.test(r), s && (r = r.substr(1) || "*"), i = e[r] = e[r] || [], i[s ? "unshift" : "push"](n)
}
}
function kn(e, n, r, i, s, o) {
s = s || n.dataTypes[0], o = o || {}, o[s] = !0;
var u, a = e[s],
f = 0,
l = a ? a.length : 0,
c = e === Sn;
for (; f < l && (c || !u); f++) u = a[f](n, r, i), typeof u == "string" && (!c || o[u] ? u = t : (n.dataTypes.unshift(u), u = kn(e, n, r, i, u, o)));
return (c || !u) && !o["*"] && (u = kn(e, n, r, i, "*", o)), u
}
function Ln(e, n) {
var r, i, s = v.ajaxSettings.flatOptions || {};
for (r in n) n[r] !== t && ((s[r] ? e : i || (i = {}))[r] = n[r]);
i && v.extend(!0, e, i)
}
function An(e, n, r) {
var i, s, o, u, a = e.contents,
f = e.dataTypes,
l = e.responseFields;
for (s in l) s in r && (n[l[s]] = r[s]);
while (f[0] === "*") f.shift(), i === t && (i = e.mimeType || n.getResponseHeader("content-type"));
if (i) for (s in a) if (a[s] && a[s].test(i)) {
f.unshift(s);
break
}
if (f[0] in r) o = f[0];
else {
for (s in r) {
if (!f[0] || e.converters[s + " " + f[0]]) {
o = s;
break
}
u || (u = s)
}
o = o || u
}
if (o) return o !== f[0] && f.unshift(o), r[o]
}
function On(e, t) {
var n, r, i, s, o = e.dataTypes.slice(),
u = o[0],
a = {},
f = 0;
e.dataFilter && (t = e.dataFilter(t, e.dataType));
if (o[1]) for (n in e.converters) a[n.toLowerCase()] = e.converters[n];
for (; i = o[++f];) if (i !== "*") {
if (u !== "*" && u !== i) {
n = a[u + " " + i] || a["* " + i];
if (!n) for (r in a) {
s = r.split(" ");
if (s[1] === i) {
n = a[u + " " + s[0]] || a["* " + s[0]];
if (n) {
n === !0 ? n = a[r] : a[r] !== !0 && (i = s[0], o.splice(f--, 0, i));
break
}
}
}
if (n !== !0) if (n && e["throws"]) t = n(t);
else try {
t = n(t)
} catch (l) {
return {
state: "parsererror",
error: n ? l : "No conversion from " + u + " to " + i
}
}
}
u = i
}
return {
state: "success",
data: t
}
}
function Fn() {
try {
return new e.XMLHttpRequest
} catch (t) {}
}
function In() {
try {
return new e.ActiveXObject("Microsoft.XMLHTTP")
} catch (t) {}
}
function $n() {
return setTimeout(function() {
qn = t
}, 0), qn = v.now()
}
function Jn(e, t) {
v.each(t, function(t, n) {
var r = (Vn[t] || []).concat(Vn["*"]),
i = 0,
s = r.length;
for (; i < s; i++) if (r[i].call(e, t, n)) return
})
}
function Kn(e, t, n) {
var r, i = 0,
s = 0,
o = Xn.length,
u = v.Deferred().always(function() {
delete a.elem
}),
a = function() {
var t = qn || $n(),
n = Math.max(0, f.startTime + f.duration - t),
r = n / f.duration || 0,
i = 1 - r,
s = 0,
o = f.tweens.length;
for (; s < o; s++) f.tweens[s].run(i);
return u.notifyWith(e, [f, i, n]), i < 1 && o ? n : (u.resolveWith(e, [f]), !1)
},
f = u.promise({
elem: e,
props: v.extend({}, t),
opts: v.extend(!0, {
specialEasing: {}
}, n),
originalProperties: t,
originalOptions: n,
startTime: qn || $n(),
duration: n.duration,
tweens: [],
createTween: function(t, n, r) {
var i = v.Tween(e, f.opts, t, n, f.opts.specialEasing[t] || f.opts.easing);
return f.tweens.push(i), i
},
stop: function(t) {
var n = 0,
r = t ? f.tweens.length : 0;
for (; n < r; n++) f.tweens[n].run(1);
return t ? u.resolveWith(e, [f, t]) : u.rejectWith(e, [f, t]), this
}
}),
l = f.props;
Qn(l, f.opts.specialEasing);
for (; i < o; i++) {
r = Xn[i].call(f, e, l, f.opts);
if (r) return r
}
return Jn(f, l), v.isFunction(f.opts.start) && f.opts.start.call(e, f), v.fx.timer(v.extend(a, {
anim: f,
queue: f.opts.queue,
elem: e
})), f.progress(f.opts.progress).done(f.opts.done, f.opts.complete).fail(f.opts.fail).always(f.opts.always)
}
function Qn(e, t) {
var n, r, i, s, o;
for (n in e) {
r = v.camelCase(n), i = t[r], s = e[n], v.isArray(s) && (i = s[1], s = e[n] = s[0]), n !== r && (e[r] = s, delete e[n]), o = v.cssHooks[r];
if (o && "expand" in o) {
s = o.expand(s), delete e[r];
for (n in s) n in e || (e[n] = s[n], t[n] = i)
} else t[r] = i
}
}
function Gn(e, t, n) {
var r, i, s, o, u, a, f, l, c, h = this,
p = e.style,
d = {},
m = [],
g = e.nodeType && Gt(e);
n.queue || (l = v._queueHooks(e, "fx"), l.unqueued == null && (l.unqueued = 0, c = l.empty.fire, l.empty.fire = function() {
l.unqueued || c()
}), l.unqueued++, h.always(function() {
h.always(function() {
l.unqueued--, v.queue(e, "fx").length || l.empty.fire()
})
})), e.nodeType === 1 && ("height" in t || "width" in t) && (n.overflow = [p.overflow, p.overflowX, p.overflowY], v.css(e, "display") === "inline" && v.css(e, "float") === "none" && (!v.support.inlineBlockNeedsLayout || nn(e.nodeName) === "inline" ? p.display = "inline-block" : p.zoom = 1)), n.overflow && (p.overflow = "hidden", v.support.shrinkWrapBlocks || h.done(function() {
p.overflow = n.overflow[0], p.overflowX = n.overflow[1], p.overflowY = n.overflow[2]
}));
for (r in t) {
s = t[r];
if (Un.exec(s)) {
delete t[r], a = a || s === "toggle";
if (s === (g ? "hide" : "show")) continue;
m.push(r)
}
}
o = m.length;
if (o) {
u = v._data(e, "fxshow") || v._data(e, "fxshow", {}), "hidden" in u && (g = u.hidden), a && (u.hidden = !g), g ? v(e).show() : h.done(function() {
v(e).hide()
}), h.done(function() {
var t;
v.removeData(e, "fxshow", !0);
for (t in d) v.style(e, t, d[t])
});
for (r = 0; r < o; r++) i = m[r], f = h.createTween(i, g ? u[i] : 0), d[i] = u[i] || v.style(e, i), i in u || (u[i] = f.start, g && (f.end = f.start, f.start = i === "width" || i === "height" ? 1 : 0))
}
}
function Yn(e, t, n, r, i) {
return new Yn.prototype.init(e, t, n, r, i)
}
function Zn(e, t) {
var n, r = {
height: e
},
i = 0;
t = t ? 1 : 0;
for (; i < 4; i += 2 - t) n = $t[i], r["margin" + n] = r["padding" + n] = e;
return t && (r.opacity = r.width = e), r
}
function tr(e) {
return v.isWindow(e) ? e : e.nodeType === 9 ? e.defaultView || e.parentWindow : !1
}
var n, r, i = e.document,
s = e.location,
o = e.navigator,
u = e.jQuery,
a = e.$,
f = Array.prototype.push,
l = Array.prototype.slice,
c = Array.prototype.indexOf,
h = Object.prototype.toString,
p = Object.prototype.hasOwnProperty,
d = String.prototype.trim,
v = function(e, t) {
return new v.fn.init(e, t, n)
},
m = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,
g = /\S/,
y = /\s+/,
b = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
w = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
E = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
S = /^[\],:{}\s]*$/,
x = /(?:^|:|,)(?:\s*\[)+/g,
T = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
N = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,
C = /^-ms-/,
k = /-([\da-z])/gi,
L = function(e, t) {
return (t + "").toUpperCase()
},
A = function() {
i.addEventListener ? (i.removeEventListener("DOMContentLoaded", A, !1), v.ready()) : i.readyState === "complete" && (i.detachEvent("onreadystatechange", A), v.ready())
},
O = {};
v.fn = v.prototype = {
constructor: v,
init: function(e, n, r) {
var s, o, u, a;
if (!e) return this;
if (e.nodeType) return this.context = this[0] = e, this.length = 1, this;
if (typeof e == "string") {
e.charAt(0) === "<" && e.charAt(e.length - 1) === ">" && e.length >= 3 ? s = [null, e, null] : s = w.exec(e);
if (s && (s[1] || !n)) {
if (s[1]) return n = n instanceof v ? n[0] : n, a = n && n.nodeType ? n.ownerDocument || n : i, e = v.parseHTML(s[1], a, !0), E.test(s[1]) && v.isPlainObject(n) && this.attr.call(e, n, !0), v.merge(this, e);
o = i.getElementById(s[2]);
if (o && o.parentNode) {
if (o.id !== s[2]) return r.find(e);
this.length = 1, this[0] = o
}
return this.context = i, this.selector = e, this
}
return !n || n.jquery ? (n || r).find(e) : this.constructor(n).find(e)
}
return v.isFunction(e) ? r.ready(e) : (e.selector !== t && (this.selector = e.selector, this.context = e.context), v.makeArray(e, this))
},
selector: "",
jquery: "1.8.3",
length: 0,
size: function() {
return this.length
},
toArray: function() {
return l.call(this)
},
get: function(e) {
return e == null ? this.toArray() : e < 0 ? this[this.length + e] : this[e]
},
pushStack: function(e, t, n) {
var r = v.merge(this.constructor(), e);
return r.prevObject = this, r.context = this.context, t === "find" ? r.selector = this.selector + (this.selector ? " " : "") + n : t && (r.selector = this.selector + "." + t + "(" + n + ")"), r
},
each: function(e, t) {
return v.each(this, e, t)
},
ready: function(e) {
return v.ready.promise().done(e), this
},
eq: function(e) {
return e = +e, e === -1 ? this.slice(e) : this.slice(e, e + 1)
},
first: function() {
return this.eq(0)
},
last: function() {
return this.eq(-1)
},
slice: function() {
return this.pushStack(l.apply(this, arguments), "slice", l.call(arguments).join(","))
},
map: function(e) {
return this.pushStack(v.map(this, function(t, n) {
return e.call(t, n, t)
}))
},
end: function() {
return this.prevObject || this.constructor(null)
},
push: f,
sort: [].sort,
splice: [].splice
}, v.fn.init.prototype = v.fn, v.extend = v.fn.extend = function() {
var e, n, r, i, s, o, u = arguments[0] || {},
a = 1,
f = arguments.length,
l = !1;
typeof u == "boolean" && (l = u, u = arguments[1] || {}, a = 2), typeof u != "object" && !v.isFunction(u) && (u = {}), f === a && (u = this, --a);
for (; a < f; a++) if ((e = arguments[a]) != null) for (n in e) {
r = u[n], i = e[n];
if (u === i) continue;
l && i && (v.isPlainObject(i) || (s = v.isArray(i))) ? (s ? (s = !1, o = r && v.isArray(r) ? r : []) : o = r && v.isPlainObject(r) ? r : {}, u[n] = v.extend(l, o, i)) : i !== t && (u[n] = i)
}
return u
}, v.extend({
noConflict: function(t) {
return e.$ === v && (e.$ = a), t && e.jQuery === v && (e.jQuery = u), v
},
isReady: !1,
readyWait: 1,
holdReady: function(e) {
e ? v.readyWait++ : v.ready(!0)
},
ready: function(e) {
if (e === !0 ? --v.readyWait : v.isReady) return;
if (!i.body) return setTimeout(v.ready, 1);
v.isReady = !0;
if (e !== !0 && --v.readyWait > 0) return;
r.resolveWith(i, [v]), v.fn.trigger && v(i).trigger("ready").off("ready")
},
isFunction: function(e) {
return v.type(e) === "function"
},
isArray: Array.isArray ||
function(e) {
return v.type(e) === "array"
},
isWindow: function(e) {
return e != null && e == e.window
},
isNumeric: function(e) {
return !isNaN(parseFloat(e)) && isFinite(e)
},
type: function(e) {
return e == null ? String(e) : O[h.call(e)] || "object"
},
isPlainObject: function(e) {
if (!e || v.type(e) !== "object" || e.nodeType || v.isWindow(e)) return !1;
try {
if (e.constructor && !p.call(e, "constructor") && !p.call(e.constructor.prototype, "isPrototypeOf")) return !1
} catch (n) {
return !1
}
var r;
for (r in e);
return r === t || p.call(e, r)
},
isEmptyObject: function(e) {
var t;
for (t in e) return !1;
return !0
},
error: function(e) {
throw new Error(e)
},
parseHTML: function(e, t, n) {
var r;
return !e || typeof e != "string" ? null : (typeof t == "boolean" && (n = t, t = 0), t = t || i, (r = E.exec(e)) ? [t.createElement(r[1])] : (r = v.buildFragment([e], t, n ? null : []), v.merge([], (r.cacheable ? v.clone(r.fragment) : r.fragment).childNodes)))
},
parseJSON: function(t) {
if (!t || typeof t != "string") return null;
t = v.trim(t);
if (e.JSON && e.JSON.parse) return e.JSON.parse(t);
if (S.test(t.replace(T, "@").replace(N, "]").replace(x, ""))) return (new Function("return " + t))();
v.error("Invalid JSON: " + t)
},
parseXML: function(n) {
var r, i;
if (!n || typeof n != "string") 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 (s) {
r = t
}
return (!r || !r.documentElement || r.getElementsByTagName("parsererror").length) && v.error("Invalid XML: " + n), r
},
noop: function() {},
globalEval: function(t) {
t && g.test(t) && (e.execScript ||
function(t) {
e.eval.call(e, t)
})(t)
},
camelCase: function(e) {
return e.replace(C, "ms-").replace(k, L)
},
nodeName: function(e, t) {
return e.nodeName && e.nodeName.toLowerCase() === t.toLowerCase()
},
each: function(e, n, r) {
var i, s = 0,
o = e.length,
u = o === t || v.isFunction(e);
if (r) {
if (u) {
for (i in e) if (n.apply(e[i], r) === !1) break
} else for (; s < o;) if (n.apply(e[s++], r) === !1) break
} else if (u) {
for (i in e) if (n.call(e[i], i, e[i]) === !1) break
} else for (; s < o;) if (n.call(e[s], s, e[s++]) === !1) break;
return e
},
trim: d && !d.call("\ufeff\u00a0") ?
function(e) {
return e == null ? "" : d.call(e)
} : function(e) {
return e == null ? "" : (e + "").replace(b, "")
},
makeArray: function(e, t) {
var n, r = t || [];
return e != null && (n = v.type(e), e.length == null || n === "string" || n === "function" || n === "regexp" || v.isWindow(e) ? f.call(r, e) : v.merge(r, e)), r
},
inArray: function(e, t, n) {
var r;
if (t) {
if (c) return c.call(t, e, n);
r = t.length, n = n ? n < 0 ? Math.max(0, r + n) : n : 0;
for (; n < r; n++) if (n in t && t[n] === e) return n
}
return -1
},
merge: function(e, n) {
var r = n.length,
i = e.length,
s = 0;
if (typeof r == "number") for (; s < r; s++) e[i++] = n[s];
else while (n[s] !== t) e[i++] = n[s++];
return e.length = i, e
},
grep: function(e, t, n) {
var r, i = [],
s = 0,
o = e.length;
n = !! n;
for (; s < o; s++) r = !! t(e[s], s), n !== r && i.push(e[s]);
return i
},
map: function(e, n, r) {
var i, s, o = [],
u = 0,
a = e.length,
f = e instanceof v || a !== t && typeof a == "number" && (a > 0 && e[0] && e[a - 1] || a === 0 || v.isArray(e));
if (f) for (; u < a; u++) i = n(e[u], u, r), i != null && (o[o.length] = i);
else for (s in e) i = n(e[s], s, r), i != null && (o[o.length] = i);
return o.concat.apply([], o)
},
guid: 1,
proxy: function(e, n) {
var r, i, s;
return typeof n == "string" && (r = e[n], n = e, e = r), v.isFunction(e) ? (i = l.call(arguments, 2), s = function() {
return e.apply(n, i.concat(l.call(arguments)))
}, s.guid = e.guid = e.guid || v.guid++, s) : t
},
access: function(e, n, r, i, s, o, u) {
var a, f = r == null,
l = 0,
c = e.length;
if (r && typeof r == "object") {
for (l in r) v.access(e, n, l, r[l], 1, o, i);
s = 1
} else if (i !== t) {
a = u === t && v.isFunction(i), f && (a ? (a = n, n = function(e, t, n) {
return a.call(v(e), n)
}) : (n.call(e, i), n = null));
if (n) for (; l < c; l++) n(e[l], r, a ? i.call(e[l], l, n(e[l], r)) : i, u);
s = 1
}
return s ? e : f ? n.call(e) : c ? n(e[0], r) : o
},
now: function() {
return (new Date).getTime()
}
}), v.ready.promise = function(t) {
if (!r) {
r = v.Deferred();
if (i.readyState === "complete") setTimeout(v.ready, 1);
else if (i.addEventListener) i.addEventListener("DOMContentLoaded", A, !1), e.addEventListener("load", v.ready, !1);
else {
i.attachEvent("onreadystatechange", A), e.attachEvent("onload", v.ready);
var n = !1;
try {
n = e.frameElement == null && i.documentElement
} catch (s) {}
n && n.doScroll &&
function o() {
if (!v.isReady) {
try {
n.doScroll("left")
} catch (e) {
return setTimeout(o, 50)
}
v.ready()
}
}()
}
}
return r.promise(t)
}, v.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(e, t) {
O["[object " + t + "]"] = t.toLowerCase()
}), n = v(i);
var M = {};
v.Callbacks = function(e) {
e = typeof e == "string" ? M[e] || _(e) : v.extend({}, e);
var n, r, i, s, o, u, a = [],
f = !e.once && [],
l = function(t) {
n = e.memory && t, r = !0, u = s || 0, s = 0, o = a.length, i = !0;
for (; a && u < o; u++) if (a[u].apply(t[0], t[1]) === !1 && e.stopOnFalse) {
n = !1;
break
}
i = !1, a && (f ? f.length && l(f.shift()) : n ? a = [] : c.disable())
},
c = {
add: function() {
if (a) {
var t = a.length;
(function r(t) {
v.each(t, function(t, n) {
var i = v.type(n);
i === "function" ? (!e.unique || !c.has(n)) && a.push(n) : n && n.length && i !== "string" && r(n)
})
})(arguments), i ? o = a.length : n && (s = t, l(n))
}
return this
},
remove: function() {
return a && v.each(arguments, function(e, t) {
var n;
while ((n = v.inArray(t, a, n)) > -1) a.splice(n, 1), i && (n <= o && o--, n <= u && u--)
}), this
},
has: function(e) {
return v.inArray(e, a) > -1
},
empty: function() {
return a = [], this
},
disable: function() {
return a = f = n = t, this
},
disabled: function() {
return !a
},
lock: function() {
return f = t, n || c.disable(), this
},
locked: function() {
return !f
},
fireWith: function(e, t) {
return t = t || [], t = [e, t.slice ? t.slice() : t], a && (!r || f) && (i ? f.push(t) : l(t)), this
},
fire: function() {
return c.fireWith(this, arguments), this
},
fired: function() {
return !!r
}
};
return c
}, v.extend({
Deferred: function(e) {
var t = [
["resolve", "done", v.Callbacks("once memory"), "resolved"],
["reject", "fail", v.Callbacks("once memory"), "rejected"],
["notify", "progress", v.Callbacks("memory")]
],
n = "pending",
r = {
state: function() {
return n
},
always: function() {
return i.done(arguments).fail(arguments), this
},
then: function() {
var e = arguments;
return v.Deferred(function(n) {
v.each(t, function(t, r) {
var s = r[0],
o = e[t];
i[r[1]](v.isFunction(o) ?
function() {
var e = o.apply(this, arguments);
e && v.isFunction(e.promise) ? e.promise().done(n.resolve).fail(n.reject).progress(n.notify) : n[s + "With"](this === i ? n : this, [e])
} : n[s])
}), e = null
}).promise()
},
promise: function(e) {
return e != null ? v.extend(e, r) : r
}
},
i = {};
return r.pipe = r.then, v.each(t, function(e, s) {
var o = s[2],
u = s[3];
r[s[1]] = o.add, u && o.add(function() {
n = u
}, t[e ^ 1][2].disable, t[2][2].lock), i[s[0]] = o.fire, i[s[0] + "With"] = o.fireWith
}), r.promise(i), e && e.call(i, i), i
},
when: function(e) {
var t = 0,
n = l.call(arguments),
r = n.length,
i = r !== 1 || e && v.isFunction(e.promise) ? r : 0,
s = i === 1 ? e : v.Deferred(),
o = function(e, t, n) {
return function(r) {
t[e] = this, n[e] = arguments.length > 1 ? l.call(arguments) : r, n === u ? s.notifyWith(t, n) : --i || s.resolveWith(t, n)
}
},
u, a, f;
if (r > 1) {
u = new Array(r), a = new Array(r), f = new Array(r);
for (; t < r; t++) n[t] && v.isFunction(n[t].promise) ? n[t].promise().done(o(t, f, n)).fail(s.reject).progress(o(t, a, u)) : --i
}
return i || s.resolveWith(f, n), s.promise()
}
}), v.support = function() {
var t, n, r, s, o, u, a, f, l, c, h, p = i.createElement("div");
p.setAttribute("className", "t"), p.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>", n = p.getElementsByTagName("*"), r = p.getElementsByTagName("a")[0];
if (!n || !r || !n.length) return {};
s = i.createElement("select"), o = s.appendChild(i.createElement("option")), u = p.getElementsByTagName("input")[0], r.style.cssText = "top:1px;float:left;opacity:.5", t = {
leadingWhitespace: p.firstChild.nodeType === 3,
tbody: !p.getElementsByTagName("tbody").length,
htmlSerialize: !! p.getElementsByTagName("link").length,
style: /top/.test(r.getAttribute("style")),
hrefNormalized: r.getAttribute("href") === "/a",
opacity: /^0.5/.test(r.style.opacity),
cssFloat: !! r.style.cssFloat,
checkOn: u.value === "on",
optSelected: o.selected,
getSetAttribute: p.className !== "t",
enctype: !! i.createElement("form").enctype,
html5Clone: i.createElement("nav").cloneNode(!0).outerHTML !== "<:nav></:nav>",
boxModel: i.compatMode === "CSS1Compat",
submitBubbles: !0,
changeBubbles: !0,
focusinBubbles: !1,
deleteExpando: !0,
noCloneEvent: !0,
inlineBlockNeedsLayout: !1,
shrinkWrapBlocks: !1,
reliableMarginRight: !0,
boxSizingReliable: !0,
pixelPosition: !1
}, u.checked = !0, t.noCloneChecked = u.cloneNode(!0).checked, s.disabled = !0, t.optDisabled = !o.disabled;
try {
delete p.test
} catch (d) {
t.deleteExpando = !1
}!p.addEventListener && p.attachEvent && p.fireEvent && (p.attachEvent("onclick", h = function() {
t.noCloneEvent = !1
}), p.cloneNode(!0).fireEvent("onclick"), p.detachEvent("onclick", h)), u = i.createElement("input"), u.value = "t", u.setAttribute("type", "radio"), t.radioValue = u.value === "t", u.setAttribute("checked", "checked"), u.setAttribute("name", "t"), p.appendChild(u), a = i.createDocumentFragment(), a.appendChild(p.lastChild), t.checkClone = a.cloneNode(!0).cloneNode(!0).lastChild.checked, t.appendChecked = u.checked, a.removeChild(u), a.appendChild(p);
if (p.attachEvent) for (l in {
submit: !0,
change: !0,
focusin: !0
}) f = "on" + l, c = f in p, c || (p.setAttribute(f, "return;"), c = typeof p[f] == "function"), t[l + "Bubbles"] = c;
return v(function() {
var n, r, s, o, u = "padding:0;margin:0;border:0;display:block;overflow:hidden;",
a = i.getElementsByTagName("body")[0];
if (!a) return;
n = i.createElement("div"), n.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px", a.insertBefore(n, a.firstChild), r = i.createElement("div"), n.appendChild(r), r.innerHTML = "<table><tr><td></td><td>t</td></tr></table>", s = r.getElementsByTagName("td"), s[0].style.cssText = "padding:0;margin:0;border:0;display:none", c = s[0].offsetHeight === 0, s[0].style.display = "", s[1].style.display = "none", t.reliableHiddenOffsets = c && s[0].offsetHeight === 0, r.innerHTML = "", r.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 = r.offsetWidth === 4, t.doesNotIncludeMarginInBodyOffset = a.offsetTop !== 1, e.getComputedStyle && (t.pixelPosition = (e.getComputedStyle(r, null) || {}).top !== "1%", t.boxSizingReliable = (e.getComputedStyle(r, null) || {
width: "4px"
}).width === "4px", o = i.createElement("div"), o.style.cssText = r.style.cssText = u, o.style.marginRight = o.style.width = "0", r.style.width = "1px", r.appendChild(o), t.reliableMarginRight = !parseFloat((e.getComputedStyle(o, null) || {}).marginRight)), typeof r.style.zoom != "undefined" && (r.innerHTML = "", r.style.cssText = u + "width:1px;padding:1px;display:inline;zoom:1", t.inlineBlockNeedsLayout = r.offsetWidth === 3, r.style.display = "block", r.style.overflow = "visible", r.innerHTML = "<div></div>", r.firstChild.style.width = "5px", t.shrinkWrapBlocks = r.offsetWidth !== 3, n.style.zoom = 1), a.removeChild(n), n = r = s = o = null
}), a.removeChild(p), n = r = s = o = u = a = p = null, t
}();
var D = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
P = /([A-Z])/g;
v.extend({
cache: {},
deletedIds: [],
uuid: 0,
expando: "jQuery" + (v.fn.jquery + Math.random()).replace(/\D/g, ""),
noData: {
embed: !0,
object: "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
applet: !0
},
hasData: function(e) {
return e = e.nodeType ? v.cache[e[v.expando]] : e[v.expando], !! e && !B(e)
},
data: function(e, n, r, i) {
if (!v.acceptData(e)) return;
var s, o, u = v.expando,
a = typeof n == "string",
f = e.nodeType,
l = f ? v.cache : e,
c = f ? e[u] : e[u] && u;
if ((!c || !l[c] || !i && !l[c].data) && a && r === t) return;
c || (f ? e[u] = c = v.deletedIds.pop() || v.guid++ : c = u), l[c] || (l[c] = {}, f || (l[c].toJSON = v.noop));
if (typeof n == "object" || typeof n == "function") i ? l[c] = v.extend(l[c], n) : l[c].data = v.extend(l[c].data, n);
return s = l[c], i || (s.data || (s.data = {}), s = s.data), r !== t && (s[v.camelCase(n)] = r), a ? (o = s[n], o == null && (o = s[v.camelCase(n)])) : o = s, o
},
removeData: function(e, t, n) {
if (!v.acceptData(e)) return;
var r, i, s, o = e.nodeType,
u = o ? v.cache : e,
a = o ? e[v.expando] : v.expando;
if (!u[a]) return;
if (t) {
r = n ? u[a] : u[a].data;
if (r) {
v.isArray(t) || (t in r ? t = [t] : (t = v.camelCase(t), t in r ? t = [t] : t = t.split(" ")));
for (i = 0, s = t.length; i < s; i++) delete r[t[i]];
if (!(n ? B : v.isEmptyObject)(r)) return
}
}
if (!n) {
delete u[a].data;
if (!B(u[a])) return
}
o ? v.cleanData([e], !0) : v.support.deleteExpando || u != u.window ? delete u[a] : u[a] = null
},
_data: function(e, t, n) {
return v.data(e, t, n, !0)
},
acceptData: function(e) {
var t = e.nodeName && v.noData[e.nodeName.toLowerCase()];
return !t || t !== !0 && e.getAttribute("classid") === t
}
}), v.fn.extend({
data: function(e, n) {
var r, i, s, o, u, a = this[0],
f = 0,
l = null;
if (e === t) {
if (this.length) {
l = v.data(a);
if (a.nodeType === 1 && !v._data(a, "parsedAttrs")) {
s = a.attributes;
for (u = s.length; f < u; f++) o = s[f].name, o.indexOf("data-") || (o = v.camelCase(o.substring(5)), H(a, o, l[o]));
v._data(a, "parsedAttrs", !0)
}
}
return l
}
return typeof e == "object" ? this.each(function() {
v.data(this, e)
}) : (r = e.split(".", 2), r[1] = r[1] ? "." + r[1] : "", i = r[1] + "!", v.access(this, function(n) {
if (n === t) return l = this.triggerHandler("getData" + i, [r[0]]), l === t && a && (l = v.data(a, e), l = H(a, e, l)), l === t && r[1] ? this.data(r[0]) : l;
r[1] = n, this.each(function() {
var t = v(this);
t.triggerHandler("setData" + i, r), v.data(this, e, n), t.triggerHandler("changeData" + i, r)
})
}, null, n, arguments.length > 1, null, !1))
},
removeData: function(e) {
return this.each(function() {
v.removeData(this, e)
})
}
}), v.extend({
queue: function(e, t, n) {
var r;
if (e) return t = (t || "fx") + "queue", r = v._data(e, t), n && (!r || v.isArray(n) ? r = v._data(e, t, v.makeArray(n)) : r.push(n)), r || []
},
dequeue: function(e, t) {
t = t || "fx";
var n = v.queue(e, t),
r = n.length,
i = n.shift(),
s = v._queueHooks(e, t),
o = function() {
v.dequeue(e, t)
};
i === "inprogress" && (i = n.shift(), r--), i && (t === "fx" && n.unshift("inprogress"), delete s.stop, i.call(e, o, s)), !r && s && s.empty.fire()
},
_queueHooks: function(e, t) {
var n = t + "queueHooks";
return v._data(e, n) || v._data(e, n, {
empty: v.Callbacks("once memory").add(function() {
v.removeData(e, t + "queue", !0), v.removeData(e, n, !0)
})
})
}
}), v.fn.extend({
queue: function(e, n) {
var r = 2;
return typeof e != "string" && (n = e, e = "fx", r--), arguments.length < r ? v.queue(this[0], e) : n === t ? this : this.each(function() {
var t = v.queue(this, e, n);
v._queueHooks(this, e), e === "fx" && t[0] !== "inprogress" && v.dequeue(this, e)
})
},
dequeue: function(e) {
return this.each(function() {
v.dequeue(this, e)
})
},
delay: function(e, t) {
return e = v.fx ? v.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,
s = v.Deferred(),
o = this,
u = this.length,
a = function() {
--i || s.resolveWith(o, [o])
};
typeof e != "string" && (n = e, e = t), e = e || "fx";
while (u--) r = v._data(o[u], e + "queueHooks"), r && r.empty && (i++, r.empty.add(a));
return a(), s.promise(n)
}
});
var j, F, I, q = /[\t\r\n]/g,
R = /\r/g,
U = /^(?:button|input)$/i,
z = /^(?:button|input|object|select|textarea)$/i,
W = /^a(?:rea|)$/i,
X = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
V = v.support.getSetAttribute;
v.fn.extend({
attr: function(e, t) {
return v.access(this, v.attr, e, t, arguments.length > 1)
},
removeAttr: function(e) {
return this.each(function() {
v.removeAttr(this, e)
})
},
prop: function(e, t) {
return v.access(this, v.prop, e, t, arguments.length > 1)
},
removeProp: function(e) {
return e = v.propFix[e] || e, this.each(function() {
try {
this[e] = t, delete this[e]
} catch (n) {}
})
},
addClass: function(e) {
var t, n, r, i, s, o, u;
if (v.isFunction(e)) return this.each(function(t) {
v(this).addClass(e.call(this, t, this.className))
});
if (e && typeof e == "string") {
t = e.split(y);
for (n = 0, r = this.length; n < r; n++) {
i = this[n];
if (i.nodeType === 1) if (!i.className && t.length === 1) i.className = e;
else {
s = " " + i.className + " ";
for (o = 0, u = t.length; o < u; o++) s.indexOf(" " + t[o] + " ") < 0 && (s += t[o] + " ");
i.className = v.trim(s)
}
}
}
return this
},
removeClass: function(e) {
var n, r, i, s, o, u, a;
if (v.isFunction(e)) return this.each(function(t) {
v(this).removeClass(e.call(this, t, this.className))
});
if (e && typeof e == "string" || e === t) {
n = (e || "").split(y);
for (u = 0, a = this.length; u < a; u++) {
i = this[u];
if (i.nodeType === 1 && i.className) {
r = (" " + i.className + " ").replace(q, " ");
for (s = 0, o = n.length; s < o; s++) while (r.indexOf(" " + n[s] + " ") >= 0) r = r.replace(" " + n[s] + " ", " ");
i.className = e ? v.trim(r) : ""
}
}
}
return this
},
toggleClass: function(e, t) {
var n = typeof e,
r = typeof t == "boolean";
return v.isFunction(e) ? this.each(function(n) {
v(this).toggleClass(e.call(this, n, this.className, t), t)
}) : this.each(function() {
if (n === "string") {
var i, s = 0,
o = v(this),
u = t,
a = e.split(y);
while (i = a[s++]) u = r ? u : !o.hasClass(i), o[u ? "addClass" : "removeClass"](i)
} else if (n === "undefined" || n === "boolean") this.className && v._data(this, "__className__", this.className), this.className = this.className || e === !1 ? "" : v._data(this, "__className__") || ""
})
},
hasClass: function(e) {
var t = " " + e + " ",
n = 0,
r = this.length;
for (; n < r; n++) if (this[n].nodeType === 1 && (" " + this[n].className + " ").replace(q, " ").indexOf(t) >= 0) return !0;
return !1
},
val: function(e) {
var n, r, i, s = this[0];
if (!arguments.length) {
if (s) return n = v.valHooks[s.type] || v.valHooks[s.nodeName.toLowerCase()], n && "get" in n && (r = n.get(s, "value")) !== t ? r : (r = s.value, typeof r == "string" ? r.replace(R, "") : r == null ? "" : r);
return
}
return i = v.isFunction(e), this.each(function(r) {
var s, o = v(this);
if (this.nodeType !== 1) return;
i ? s = e.call(this, r, o.val()) : s = e, s == null ? s = "" : typeof s == "number" ? s += "" : v.isArray(s) && (s = v.map(s, function(e) {
return e == null ? "" : e + ""
})), n = v.valHooks[this.type] || v.valHooks[this.nodeName.toLowerCase()];
if (!n || !("set" in n) || n.set(this, s, "value") === t) this.value = s
})
}
}), v.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,
s = e.type === "select-one" || i < 0,
o = s ? null : [],
u = s ? i + 1 : r.length,
a = i < 0 ? u : s ? i : 0;
for (; a < u; a++) {
n = r[a];
if ((n.selected || a === i) && (v.support.optDisabled ? !n.disabled : n.getAttribute("disabled") === null) && (!n.parentNode.disabled || !v.nodeName(n.parentNode, "optgroup"))) {
t = v(n).val();
if (s) return t;
o.push(t)
}
}
return o
},
set: function(e, t) {
var n = v.makeArray(t);
return v(e).find("option").each(function() {
this.selected = v.inArray(v(this).val(), n) >= 0
}), n.length || (e.selectedIndex = -1), n
}
}
},
attrFn: {},
attr: function(e, n, r, i) {
var s, o, u, a = e.nodeType;
if (!e || a === 3 || a === 8 || a === 2) return;
if (i && v.isFunction(v.fn[n])) return v(e)[n](r);
if (typeof e.getAttribute == "undefined") return v.prop(e, n, r);
u = a !== 1 || !v.isXMLDoc(e), u && (n = n.toLowerCase(), o = v.attrHooks[n] || (X.test(n) ? F : j));
if (r !== t) {
if (r === null) {
v.removeAttr(e, n);
return
}
return o && "set" in o && u && (s = o.set(e, r, n)) !== t ? s : (e.setAttribute(n, r + ""), r)
}
return o && "get" in o && u && (s = o.get(e, n)) !== null ? s : (s = e.getAttribute(n), s === null ? t : s)
},
removeAttr: function(e, t) {
var n, r, i, s, o = 0;
if (t && e.nodeType === 1) {
r = t.split(y);
for (; o < r.length; o++) i = r[o], i && (n = v.propFix[i] || i, s = X.test(i), s || v.attr(e, i, ""), e.removeAttribute(V ? i : n), s && n in e && (e[n] = !1))
}
},
attrHooks: {
type: {
set: function(e, t) {
if (U.test(e.nodeName) && e.parentNode) v.error("type property can't be changed");
else if (!v.support.radioValue && t === "radio" && v.nodeName(e, "input")) {
var n = e.value;
return e.setAttribute("type", t), n && (e.value = n), t
}
}
},
value: {
get: function(e, t) {
return j && v.nodeName(e, "button") ? j.get(e, t) : t in e ? e.value : null
},
set: function(e, t, n) {
if (j && v.nodeName(e, "button")) return j.set(e, t, n);
e.value = 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, s, o, u = e.nodeType;
if (!e || u === 3 || u === 8 || u === 2) return;
return o = u !== 1 || !v.isXMLDoc(e), o && (n = v.propFix[n] || n, s = v.propHooks[n]), r !== t ? s && "set" in s && (i = s.set(e, r, n)) !== t ? i : e[n] = r : s && "get" in s && (i = s.get(e, n)) !== null ? i : e[n]
},
propHooks: {
tabIndex: {
get: function(e) {
var n = e.getAttributeNode("tabindex");
return n && n.specified ? parseInt(n.value, 10) : z.test(e.nodeName) || W.test(e.nodeName) && e.href ? 0 : t
}
}
}
}), F = {
get: function(e, n) {
var r, i = v.prop(e, n);
return i === !0 || typeof i != "boolean" && (r = e.getAttributeNode(n)) && r.nodeValue !== !1 ? n.toLowerCase() : t
},
set: function(e, t, n) {
var r;
return t === !1 ? v.removeAttr(e, n) : (r = v.propFix[n] || n, r in e && (e[r] = !0), e.setAttribute(n, n.toLowerCase())), n
}
}, V || (I = {
name: !0,
id: !0,
coords: !0
}, j = v.valHooks.button = {
get: function(e, n) {
var r;
return r = e.getAttributeNode(n), r && (I[n] ? r.value !== "" : r.specified) ? r.value : t
},
set: function(e, t, n) {
var r = e.getAttributeNode(n);
return r || (r = i.createAttribute(n), e.setAttributeNode(r)), r.value = t + ""
}
}, v.each(["width", "height"], function(e, t) {
v.attrHooks[t] = v.extend(v.attrHooks[t], {
set: function(e, n) {
if (n === "") return e.setAttribute(t, "auto"), n
}
})
}), v.attrHooks.contenteditable = {
get: j.get,
set: function(e, t, n) {
t === "" && (t = "false"), j.set(e, t, n)
}
}), v.support.hrefNormalized || v.each(["href", "src", "width", "height"], function(e, n) {
v.attrHooks[n] = v.extend(v.attrHooks[n], {
get: function(e) {
var r = e.getAttribute(n, 2);
return r === null ? t : r
}
})
}), v.support.style || (v.attrHooks.style = {
get: function(e) {
return e.style.cssText.toLowerCase() || t
},
set: function(e, t) {
return e.style.cssText = t + ""
}
}), v.support.optSelected || (v.propHooks.selected = v.extend(v.propHooks.selected, {
get: function(e) {
var t = e.parentNode;
return t && (t.selectedIndex, t.parentNode && t.parentNode.selectedIndex), null
}
})), v.support.enctype || (v.propFix.enctype = "encoding"), v.support.checkOn || v.each(["radio", "checkbox"], function() {
v.valHooks[this] = {
get: function(e) {
return e.getAttribute("value") === null ? "on" : e.value
}
}
}), v.each(["radio", "checkbox"], function() {
v.valHooks[this] = v.extend(v.valHooks[this], {
set: function(e, t) {
if (v.isArray(t)) return e.checked = v.inArray(v(e).val(), t) >= 0
}
})
});
var $ = /^(?:textarea|input|select)$/i,
J = /^([^\.]*|)(?:\.(.+)|)$/,
K = /(?:^|\s)hover(\.\S+|)\b/,
Q = /^key/,
G = /^(?:mouse|contextmenu)|click/,
Y = /^(?:focusinfocus|focusoutblur)$/,
Z = function(e) {
return v.event.special.hover ? e : e.replace(K, "mouseenter$1 mouseleave$1")
};
v.event = {
add: function(e, n, r, i, s) {
var o, u, a, f, l, c, h, p, d, m, g;
if (e.nodeType === 3 || e.nodeType === 8 || !n || !r || !(o = v._data(e))) return;
r.handler && (d = r, r = d.handler, s = d.selector), r.guid || (r.guid = v.guid++), a = o.events, a || (o.events = a = {}), u = o.handle, u || (o.handle = u = function(e) {
return typeof v == "undefined" || !! e && v.event.triggered === e.type ? t : v.event.dispatch.apply(u.elem, arguments)
}, u.elem = e), n = v.trim(Z(n)).split(" ");
for (f = 0; f < n.length; f++) {
l = J.exec(n[f]) || [], c = l[1], h = (l[2] || "").split(".").sort(), g = v.event.special[c] || {}, c = (s ? g.delegateType : g.bindType) || c, g = v.event.special[c] || {}, p = v.extend({
type: c,
origType: l[1],
data: i,
handler: r,
guid: r.guid,
selector: s,
needsContext: s && v.expr.match.needsContext.test(s),
namespace: h.join(".")
}, d), m = a[c];
if (!m) {
m = a[c] = [], m.delegateCount = 0;
if (!g.setup || g.setup.call(e, i, h, u) === !1) e.addEventListener ? e.addEventListener(c, u, !1) : e.attachEvent && e.attachEvent("on" + c, u)
}
g.add && (g.add.call(e, p), p.handler.guid || (p.handler.guid = r.guid)), s ? m.splice(m.delegateCount++, 0, p) : m.push(p), v.event.global[c] = !0
}
e = null
},
global: {},
remove: function(e, t, n, r, i) {
var s, o, u, a, f, l, c, h, p, d, m, g = v.hasData(e) && v._data(e);
if (!g || !(h = g.events)) return;
t = v.trim(Z(t || "")).split(" ");
for (s = 0; s < t.length; s++) {
o = J.exec(t[s]) || [], u = a = o[1], f = o[2];
if (!u) {
for (u in h) v.event.remove(e, u + t[s], n, r, !0);
continue
}
p = v.event.special[u] || {}, u = (r ? p.delegateType : p.bindType) || u, d = h[u] || [], l = d.length, f = f ? new RegExp("(^|\\.)" + f.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
for (c = 0; c < d.length; c++) m = d[c], (i || a === m.origType) && (!n || n.guid === m.guid) && (!f || f.test(m.namespace)) && (!r || r === m.selector || r === "**" && m.selector) && (d.splice(c--, 1), m.selector && d.delegateCount--, p.remove && p.remove.call(e, m));
d.length === 0 && l !== d.length && ((!p.teardown || p.teardown.call(e, f, g.handle) === !1) && v.removeEvent(e, u, g.handle), delete h[u])
}
v.isEmptyObject(h) && (delete g.handle, v.removeData(e, "events", !0))
},
customEvent: {
getData: !0,
setData: !0,
changeData: !0
},
trigger: function(n, r, s, o) {
if (!s || s.nodeType !== 3 && s.nodeType !== 8) {
var u, a, f, l, c, h, p, d, m, g, y = n.type || n,
b = [];
if (Y.test(y + v.event.triggered)) return;
y.indexOf("!") >= 0 && (y = y.slice(0, -1), a = !0), y.indexOf(".") >= 0 && (b = y.split("."), y = b.shift(), b.sort());
if ((!s || v.event.customEvent[y]) && !v.event.global[y]) return;
n = typeof n == "object" ? n[v.expando] ? n : new v.Event(y, n) : new v.Event(y), n.type = y, n.isTrigger = !0, n.exclusive = a, n.namespace = b.join("."), n.namespace_re = n.namespace ? new RegExp("(^|\\.)" + b.join("\\.(?:.*\\.|)") + "(\\.|$)") : null, h = y.indexOf(":") < 0 ? "on" + y : "";
if (!s) {
u = v.cache;
for (f in u) u[f].events && u[f].events[y] && v.event.trigger(n, r, u[f].handle.elem, !0);
return
}
n.result = t, n.target || (n.target = s), r = r != null ? v.makeArray(r) : [], r.unshift(n), p = v.event.special[y] || {};
if (p.trigger && p.trigger.apply(s, r) === !1) return;
m = [
[s, p.bindType || y]
];
if (!o && !p.noBubble && !v.isWindow(s)) {
g = p.delegateType || y, l = Y.test(g + y) ? s : s.parentNode;
for (c = s; l; l = l.parentNode) m.push([l, g]), c = l;
c === (s.ownerDocument || i) && m.push([c.defaultView || c.parentWindow || e, g])
}
for (f = 0; f < m.length && !n.isPropagationStopped(); f++) l = m[f][0], n.type = m[f][1], d = (v._data(l, "events") || {})[n.type] && v._data(l, "handle"), d && d.apply(l, r), d = h && l[h], d && v.acceptData(l) && d.apply && d.apply(l, r) === !1 && n.preventDefault();
return n.type = y, !o && !n.isDefaultPrevented() && (!p._default || p._default.apply(s.ownerDocument, r) === !1) && (y !== "click" || !v.nodeName(s, "a")) && v.acceptData(s) && h && s[y] && (y !== "focus" && y !== "blur" || n.target.offsetWidth !== 0) && !v.isWindow(s) && (c = s[h], c && (s[h] = null), v.event.triggered = y, s[y](), v.event.triggered = t, c && (s[h] = c)), n.result
}
return
},
dispatch: function(n) {
n = v.event.fix(n || e.event);
var r, i, s, o, u, a, f, c, h, p, d = (v._data(this, "events") || {})[n.type] || [],
m = d.delegateCount,
g = l.call(arguments),
y = !n.exclusive && !n.namespace,
b = v.event.special[n.type] || {},
w = [];
g[0] = n, n.delegateTarget = this;
if (b.preDispatch && b.preDispatch.call(this, n) === !1) return;
if (m && (!n.button || n.type !== "click")) for (s = n.target; s != this; s = s.parentNode || this) if (s.disabled !== !0 || n.type !== "click") {
u = {}, f = [];
for (r = 0; r < m; r++) c = d[r], h = c.selector, u[h] === t && (u[h] = c.needsContext ? v(h, this).index(s) >= 0 : v.find(h, this, null, [s]).length), u[h] && f.push(c);
f.length && w.push({
elem: s,
matches: f
})
}
d.length > m && w.push({
elem: this,
matches: d.slice(m)
});
for (r = 0; r < w.length && !n.isPropagationStopped(); r++) {
a = w[r], n.currentTarget = a.elem;
for (i = 0; i < a.matches.length && !n.isImmediatePropagationStopped(); i++) {
c = a.matches[i];
if (y || !n.namespace && !c.namespace || n.namespace_re && n.namespace_re.test(c.namespace)) n.data = c.data, n.handleObj = c, o = ((v.event.special[c.origType] || {}).handle || c.handler).apply(a.elem, g), o !== t && (n.result = o, o === !1 && (n.preventDefault(), n.stopPropagation()))
}
}
return b.postDispatch && b.postDispatch.call(this, n), n.result
},
props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function(e, t) {
return e.which == null && (e.which = t.charCode != null ? 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, s, o, u = n.button,
a = n.fromElement;
return e.pageX == null && n.clientX != null && (r = e.target.ownerDocument || i, s = r.documentElement, o = r.body, e.pageX = n.clientX + (s && s.scrollLeft || o && o.scrollLeft || 0) - (s && s.clientLeft || o && o.clientLeft || 0), e.pageY = n.clientY + (s && s.scrollTop || o && o.scrollTop || 0) - (s && s.clientTop || o && o.clientTop || 0)), !e.relatedTarget && a && (e.relatedTarget = a === e.target ? n.toElement : a), !e.which && u !== t && (e.which = u & 1 ? 1 : u & 2 ? 3 : u & 4 ? 2 : 0), e
}
},
fix: function(e) {
if (e[v.expando]) return e;
var t, n, r = e,
s = v.event.fixHooks[e.type] || {},
o = s.props ? this.props.concat(s.props) : this.props;
e = v.Event(r);
for (t = o.length; t;) n = o[--t], e[n] = r[n];
return e.target || (e.target = r.srcElement || i), e.target.nodeType === 3 && (e.target = e.target.parentNode), e.metaKey = !! e.metaKey, s.filter ? s.filter(e, r) : e
},
special: {
load: {
noBubble: !0
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
},
beforeunload: {
setup: function(e, t, n) {
v.isWindow(this) && (this.onbeforeunload = n)
},
teardown: function(e, t) {
this.onbeforeunload === t && (this.onbeforeunload = null)
}
}
},
simulate: function(e, t, n, r) {
var i = v.extend(new v.Event, n, {
type: e,
isSimulated: !0,
originalEvent: {}
});
r ? v.event.trigger(i, null, t) : v.event.dispatch.call(t, i), i.isDefaultPrevented() && n.preventDefault()
}
}, v.event.handle = v.event.dispatch, v.removeEvent = i.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] == "undefined" && (e[r] = null), e.detachEvent(r, n))
}, v.Event = function(e, t) {
if (!(this instanceof v.Event)) return new v.Event(e, t);
e && e.type ? (this.originalEvent = e, this.type = e.type, this.isDefaultPrevented = e.defaultPrevented || e.returnValue === !1 || e.getPreventDefault && e.getPreventDefault() ? tt : et) : this.type = e, t && v.extend(this, t), this.timeStamp = e && e.timeStamp || v.now(), this[v.expando] = !0
}, v.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = tt;
var e = this.originalEvent;
if (!e) return;
e.preventDefault ? e.preventDefault() : e.returnValue = !1
},
stopPropagation: function() {
this.isPropagationStopped = tt;
var e = this.originalEvent;
if (!e) return;
e.stopPropagation && e.stopPropagation(), e.cancelBubble = !0
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = tt, this.stopPropagation()
},
isDefaultPrevented: et,
isPropagationStopped: et,
isImmediatePropagationStopped: et
}, v.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function(e, t) {
v.event.special[e] = {
delegateType: t,
bindType: t,
handle: function(e) {
var n, r = this,
i = e.relatedTarget,
s = e.handleObj,
o = s.selector;
if (!i || i !== r && !v.contains(r, i)) e.type = s.origType, n = s.handler.apply(this, arguments), e.type = t;
return n
}
}
}), v.support.submitBubbles || (v.event.special.submit = {
setup: function() {
if (v.nodeName(this, "form")) return !1;
v.event.add(this, "click._submit keypress._submit", function(e) {
var n = e.target,
r = v.nodeName(n, "input") || v.nodeName(n, "button") ? n.form : t;
r && !v._data(r, "_submit_attached") && (v.event.add(r, "submit._submit", function(e) {
e._submit_bubble = !0
}), v._data(r, "_submit_attached", !0))
})
},
postDispatch: function(e) {
e._submit_bubble && (delete e._submit_bubble, this.parentNode && !e.isTrigger && v.event.simulate("submit", this.parentNode, e, !0))
},
teardown: function() {
if (v.nodeName(this, "form")) return !1;
v.event.remove(this, "._submit")
}
}), v.support.changeBubbles || (v.event.special.change = {
setup: function() {
if ($.test(this.nodeName)) {
if (this.type === "checkbox" || this.type === "radio") v.event.add(this, "propertychange._change", function(e) {
e.originalEvent.propertyName === "checked" && (this._just_changed = !0)
}), v.event.add(this, "click._change", function(e) {
this._just_changed && !e.isTrigger && (this._just_changed = !1), v.event.simulate("change", this, e, !0)
});
return !1
}
v.event.add(this, "beforeactivate._change", function(e) {
var t = e.target;
$.test(t.nodeName) && !v._data(t, "_change_attached") && (v.event.add(t, "change._change", function(e) {
this.parentNode && !e.isSimulated && !e.isTrigger && v.event.simulate("change", this.parentNode, e, !0)
}), v._data(t, "_change_attached", !0))
})
},
handle: function(e) {
var t = e.target;
if (this !== t || e.isSimulated || e.isTrigger || t.type !== "radio" && t.type !== "checkbox") return e.handleObj.handler.apply(this, arguments)
},
teardown: function() {
return v.event.remove(this, "._change"), !$.test(this.nodeName)
}
}), v.support.focusinBubbles || v.each({
focus: "focusin",
blur: "focusout"
}, function(e, t) {
var n = 0,
r = function(e) {
v.event.simulate(t, e.target, v.event.fix(e), !0)
};
v.event.special[t] = {
setup: function() {
n++ === 0 && i.addEventListener(e, r, !0)
},
teardown: function() {
--n === 0 && i.removeEventListener(e, r, !0)
}
}
}), v.fn.extend({
on: function(e, n, r, i, s) {
var o, u;
if (typeof e == "object") {
typeof n != "string" && (r = r || n, n = t);
for (u in e) this.on(u, n, r, e[u], s);
return this
}
r == null && i == null ? (i = n, r = n = t) : i == null && (typeof n == "string" ? (i = r, r = t) : (i = r, r = n, n = t));
if (i === !1) i = et;
else if (!i) return this;
return s === 1 && (o = i, i = function(e) {
return v().off(e), o.apply(this, arguments)
}, i.guid = o.guid || (o.guid = v.guid++)), this.each(function() {
v.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, s;
if (e && e.preventDefault && e.handleObj) return i = e.handleObj, v(e.delegateTarget).off(i.namespace ? i.origType + "." + i.namespace : i.origType, i.selector, i.handler), this;
if (typeof e == "object") {
for (s in e) this.off(s, n, e[s]);
return this
}
if (n === !1 || typeof n == "function") r = n, n = t;
return r === !1 && (r = et), this.each(function() {
v.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)
},
live: function(e, t, n) {
return v(this.context).on(e, this.selector, t, n), this
},
die: function(e, t) {
return v(this.context).off(e, this.selector || "**", t), this
},
delegate: function(e, t, n, r) {
return this.on(t, e, n, r)
},
undelegate: function(e, t, n) {
return arguments.length === 1 ? this.off(e, "**") : this.off(t, e || "**", n)
},
trigger: function(e, t) {
return this.each(function() {
v.event.trigger(e, t, this)
})
},
triggerHandler: function(e, t) {
if (this[0]) return v.event.trigger(e, t, this[0], !0)
},
toggle: function(e) {
var t = arguments,
n = e.guid || v.guid++,
r = 0,
i = function(n) {
var i = (v._data(this, "lastToggle" + e.guid) || 0) % r;
return v._data(this, "lastToggle" + e.guid, i + 1), n.preventDefault(), t[i].apply(this, arguments) || !1
};
i.guid = n;
while (r < t.length) t[r++].guid = n;
return this.click(i)
},
hover: function(e, t) {
return this.mouseenter(e).mouseleave(t || e)
}
}), v.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) {
v.fn[t] = function(e, n) {
return n == null && (n = e, e = null), arguments.length > 0 ? this.on(t, null, e, n) : this.trigger(t)
}, Q.test(t) && (v.event.fixHooks[t] = v.event.keyHooks), G.test(t) && (v.event.fixHooks[t] = v.event.mouseHooks)
}), function(e, t) {
function nt(e, t, n, r) {
n = n || [], t = t || g;
var i, s, a, f, l = t.nodeType;
if (!e || typeof e != "string") return n;
if (l !== 1 && l !== 9) return [];
a = o(t);
if (!a && !r) if (i = R.exec(e)) if (f = i[1]) {
if (l === 9) {
s = t.getElementById(f);
if (!s || !s.parentNode) return n;
if (s.id === f) return n.push(s), n
} else if (t.ownerDocument && (s = t.ownerDocument.getElementById(f)) && u(t, s) && s.id === f) return n.push(s), n
} else {
if (i[2]) return S.apply(n, x.call(t.getElementsByTagName(e), 0)), n;
if ((f = i[3]) && Z && t.getElementsByClassName) return S.apply(n, x.call(t.getElementsByClassName(f), 0)), n
}
return vt(e.replace(j, "$1"), t, n, r, a)
}
function rt(e) {
return function(t) {
var n = t.nodeName.toLowerCase();
return n === "input" && t.type === e
}
}
function it(e) {
return function(t) {
var n = t.nodeName.toLowerCase();
return (n === "input" || n === "button") && t.type === e
}
}
function st(e) {
return N(function(t) {
return t = +t, N(function(n, r) {
var i, s = e([], n.length, t),
o = s.length;
while (o--) n[i = s[o]] && (n[i] = !(r[i] = n[i]))
})
})
}
function ot(e, t, n) {
if (e === t) return n;
var r = e.nextSibling;
while (r) {
if (r === t) return -1;
r = r.nextSibling
}
return 1
}
function ut(e, t) {
var n, r, s, o, u, a, f, l = L[d][e + " "];
if (l) return t ? 0 : l.slice(0);
u = e, a = [], f = i.preFilter;
while (u) {
if (!n || (r = F.exec(u))) r && (u = u.slice(r[0].length) || u), a.push(s = []);
n = !1;
if (r = I.exec(u)) s.push(n = new m(r.shift())), u = u.slice(n.length), n.type = r[0].replace(j, " ");
for (o in i.filter)(r = J[o].exec(u)) && (!f[o] || (r = f[o](r))) && (s.push(n = new m(r.shift())), u = u.slice(n.length), n.type = o, n.matches = r);
if (!n) break
}
return t ? u.length : u ? nt.error(e) : L(e, a).slice(0)
}
function at(e, t, r) {
var i = t.dir,
s = r && t.dir === "parentNode",
o = w++;
return t.first ?
function(t, n, r) {
while (t = t[i]) if (s || t.nodeType === 1) return e(t, n, r)
} : function(t, r, u) {
if (!u) {
var a, f = b + " " + o + " ",
l = f + n;
while (t = t[i]) if (s || t.nodeType === 1) {
if ((a = t[d]) === l) return t.sizset;
if (typeof a == "string" && a.indexOf(f) === 0) {
if (t.sizset) return t
} else {
t[d] = l;
if (e(t, r, u)) return t.sizset = !0, t;
t.sizset = !1
}
}
} else while (t = t[i]) if (s || t.nodeType === 1) if (e(t, r, u)) return t
}
}
function ft(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 lt(e, t, n, r, i) {
var s, o = [],
u = 0,
a = e.length,
f = t != null;
for (; u < a; u++) if (s = e[u]) if (!n || n(s, r, i)) o.push(s), f && t.push(u);
return o
}
function ct(e, t, n, r, i, s) {
return r && !r[d] && (r = ct(r)), i && !i[d] && (i = ct(i, s)), N(function(s, o, u, a) {
var f, l, c, h = [],
p = [],
d = o.length,
v = s || dt(t || "*", u.nodeType ? [u] : u, []),
m = e && (s || !t) ? lt(v, h, e, u, a) : v,
g = n ? i || (s ? e : d || r) ? [] : o : m;
n && n(m, g, u, a);
if (r) {
f = lt(g, p), r(f, [], u, a), l = f.length;
while (l--) if (c = f[l]) g[p[l]] = !(m[p[l]] = c)
}
if (s) {
if (i || e) {
if (i) {
f = [], l = g.length;
while (l--)(c = g[l]) && f.push(m[l] = c);
i(null, g = [], f, a)
}
l = g.length;
while (l--)(c = g[l]) && (f = i ? T.call(s, c) : h[l]) > -1 && (s[f] = !(o[f] = c))
}
} else g = lt(g === o ? g.splice(d, g.length) : g), i ? i(null, o, g, a) : S.apply(o, g)
})
}
function ht(e) {
var t, n, r, s = e.length,
o = i.relative[e[0].type],
u = o || i.relative[" "],
a = o ? 1 : 0,
f = at(function(e) {
return e === t
}, u, !0),
l = at(function(e) {
return T.call(t, e) > -1
}, u, !0),
h = [function(e, n, r) {
return !o && (r || n !== c) || ((t = n).nodeType ? f(e, n, r) : l(e, n, r))
}];
for (; a < s; a++) if (n = i.relative[e[a].type]) h = [at(ft(h), n)];
else {
n = i.filter[e[a].type].apply(null, e[a].matches);
if (n[d]) {
r = ++a;
for (; r < s; r++) if (i.relative[e[r].type]) break;
return ct(a > 1 && ft(h), a > 1 && e.slice(0, a - 1).join("").replace(j, "$1"), n, a < r && ht(e.slice(a, r)), r < s && ht(e = e.slice(r)), r < s && e.join(""))
}
h.push(n)
}
return ft(h)
}
function pt(e, t) {
var r = t.length > 0,
s = e.length > 0,
o = function(u, a, f, l, h) {
var p, d, v, m = [],
y = 0,
w = "0",
x = u && [],
T = h != null,
N = c,
C = u || s && i.find.TAG("*", h && a.parentNode || a),
k = b += N == null ? 1 : Math.E;
T && (c = a !== g && a, n = o.el);
for (;
(p = C[w]) != null; w++) {
if (s && p) {
for (d = 0; v = e[d]; d++) if (v(p, a, f)) {
l.push(p);
break
}
T && (b = k, n = ++o.el)
}
r && ((p = !v && p) && y--, u && x.push(p))
}
y += w;
if (r && w !== y) {
for (d = 0; v = t[d]; d++) v(x, m, a, f);
if (u) {
if (y > 0) while (w--)!x[w] && !m[w] && (m[w] = E.call(l));
m = lt(m)
}
S.apply(l, m), T && !u && m.length > 0 && y + t.length > 1 && nt.uniqueSort(l)
}
return T && (b = k, c = N), x
};
return o.el = 0, r ? N(o) : o
}
function dt(e, t, n) {
var r = 0,
i = t.length;
for (; r < i; r++) nt(e, t[r], n);
return n
}
function vt(e, t, n, r, s) {
var o, u, f, l, c, h = ut(e),
p = h.length;
if (!r && h.length === 1) {
u = h[0] = h[0].slice(0);
if (u.length > 2 && (f = u[0]).type === "ID" && t.nodeType === 9 && !s && i.relative[u[1].type]) {
t = i.find.ID(f.matches[0].replace($, ""), t, s)[0];
if (!t) return n;
e = e.slice(u.shift().length)
}
for (o = J.POS.test(e) ? -1 : u.length - 1; o >= 0; o--) {
f = u[o];
if (i.relative[l = f.type]) break;
if (c = i.find[l]) if (r = c(f.matches[0].replace($, ""), z.test(u[0].type) && t.parentNode || t, s)) {
u.splice(o, 1), e = r.length && u.join("");
if (!e) return S.apply(n, x.call(r, 0)), n;
break
}
}
}
return a(e, h)(r, t, s, n, z.test(e)), n
}
function mt() {}
var n, r, i, s, o, u, a, f, l, c, h = !0,
p = "undefined",
d = ("sizcache" + Math.random()).replace(".", ""),
m = String,
g = e.document,
y = g.documentElement,
b = 0,
w = 0,
E = [].pop,
S = [].push,
x = [].slice,
T = [].indexOf ||
function(e) {
var t = 0,
n = this.length;
for (; t < n; t++) if (this[t] === e) return t;
return -1
},
N = function(e, t) {
return e[d] = t == null || t, e
},
C = function() {
var e = {},
t = [];
return N(function(n, r) {
return t.push(n) > i.cacheLength && delete e[t.shift()], e[n + " "] = r
}, e)
},
k = C(),
L = C(),
A = C(),
O = "[\\x20\\t\\r\\n\\f]",
M = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",
_ = M.replace("w", "w#"),
D = "([*^$|!~]?=)",
P = "\\[" + O + "*(" + M + ")" + O + "*(?:" + D + O + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + _ + ")|)|)" + O + "*\\]",
H = ":(" + M + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + P + ")|[^:]|\\\\.)*|.*))\\)|)",
B = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + O + "*((?:-\\d)?\\d*)" + O + "*\\)|)(?=[^-]|$)",
j = new RegExp("^" + O + "+|((?:^|[^\\\\])(?:\\\\.)*)" + O + "+$", "g"),
F = new RegExp("^" + O + "*," + O + "*"),
I = new RegExp("^" + O + "*([\\x20\\t\\r\\n\\f>+~])" + O + "*"),
q = new RegExp(H),
R = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,
U = /^:not/,
z = /[\x20\t\r\n\f]*[+~]/,
W = /:not\($/,
X = /h\d/i,
V = /input|select|textarea|button/i,
$ = /\\(?!\\)/g,
J = {
ID: new RegExp("^#(" + M + ")"),
CLASS: new RegExp("^\\.(" + M + ")"),
NAME: new RegExp("^\\[name=['\"]?(" + M + ")['\"]?\\]"),
TAG: new RegExp("^(" + M.replace("w", "w*") + ")"),
ATTR: new RegExp("^" + P),
PSEUDO: new RegExp("^" + H),
POS: new RegExp(B, "i"),
CHILD: new RegExp("^:(only|nth|first|last)-child(?:\\(" + O + "*(even|odd|(([+-]|)(\\d*)n|)" + O + "*(?:([+-]|)" + O + "*(\\d+)|))" + O + "*\\)|)", "i"),
needsContext: new RegExp("^" + O + "*[>+~]|" + B, "i")
},
K = function(e) {
var t = g.createElement("div");
try {
return e(t)
} catch (n) {
return !1
} finally {
t = null
}
},
Q = K(function(e) {
return e.appendChild(g.createComment("")), !e.getElementsByTagName("*").length
}),
G = K(function(e) {
return e.innerHTML = "<a href='#'></a>", e.firstChild && typeof e.firstChild.getAttribute !== p && e.firstChild.getAttribute("href") === "#"
}),
Y = K(function(e) {
e.innerHTML = "<select></select>";
var t = typeof e.lastChild.getAttribute("multiple");
return t !== "boolean" && t !== "string"
}),
Z = K(function(e) {
return e.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>", !e.getElementsByClassName || !e.getElementsByClassName("e").length ? !1 : (e.lastChild.className = "e", e.getElementsByClassName("e").length === 2)
}),
et = K(function(e) {
e.id = d + 0, e.innerHTML = "<a name='" + d + "'></a><div name='" + d + "'></div>", y.insertBefore(e, y.firstChild);
var t = g.getElementsByName && g.getElementsByName(d).length === 2 + g.getElementsByName(d + 0).length;
return r = !g.getElementById(d), y.removeChild(e), t
});
try {
x.call(y.childNodes, 0)[0].nodeType
} catch (tt) {
x = function(e) {
var t, n = [];
for (; t = this[e]; e++) n.push(t);
return n
}
}
nt.matches = function(e, t) {
return nt(e, null, null, t)
}, nt.matchesSelector = function(e, t) {
return nt(t, null, null, [e]).length > 0
}, s = nt.getText = function(e) {
var t, n = "",
r = 0,
i = e.nodeType;
if (i) {
if (i === 1 || i === 9 || i === 11) {
if (typeof e.textContent == "string") return e.textContent;
for (e = e.firstChild; e; e = e.nextSibling) n += s(e)
} else if (i === 3 || i === 4) return e.nodeValue
} else for (; t = e[r]; r++) n += s(t);
return n
}, o = nt.isXML = function(e) {
var t = e && (e.ownerDocument || e).documentElement;
return t ? t.nodeName !== "HTML" : !1
}, u = nt.contains = y.contains ?
function(e, t) {
var n = e.nodeType === 9 ? e.documentElement : e,
r = t && t.parentNode;
return e === r || !! (r && r.nodeType === 1 && n.contains && n.contains(r))
} : y.compareDocumentPosition ?
function(e, t) {
return t && !! (e.compareDocumentPosition(t) & 16)
} : function(e, t) {
while (t = t.parentNode) if (t === e) return !0;
return !1
}, nt.attr = function(e, t) {
var n, r = o(e);
return r || (t = t.toLowerCase()), (n = i.attrHandle[t]) ? n(e) : r || Y ? e.getAttribute(t) : (n = e.getAttributeNode(t), n ? typeof e[t] == "boolean" ? e[t] ? t : null : n.specified ? n.value : null : null)
}, i = nt.selectors = {
cacheLength: 50,
createPseudo: N,
match: J,
attrHandle: G ? {} : {
href: function(e) {
return e.getAttribute("href", 2)
},
type: function(e) {
return e.getAttribute("type")
}
},
find: {
ID: r ?
function(e, t, n) {
if (typeof t.getElementById !== p && !n) {
var r = t.getElementById(e);
return r && r.parentNode ? [r] : []
}
} : function(e, n, r) {
if (typeof n.getElementById !== p && !r) {
var i = n.getElementById(e);
return i ? i.id === e || typeof i.getAttributeNode !== p && i.getAttributeNode("id").value === e ? [i] : t : []
}
},
TAG: Q ?
function(e, t) {
if (typeof t.getElementsByTagName !== p) return t.getElementsByTagName(e)
} : function(e, t) {
var n = t.getElementsByTagName(e);
if (e === "*") {
var r, i = [],
s = 0;
for (; r = n[s]; s++) r.nodeType === 1 && i.push(r);
return i
}
return n
},
NAME: et &&
function(e, t) {
if (typeof t.getElementsByName !== p) return t.getElementsByName(name)
},
CLASS: Z &&
function(e, t, n) {
if (typeof t.getElementsByClassName !== p && !n) return t.getElementsByClassName(e)
}
},
relative: {
">": {
dir: "parentNode",
first: !0
},
" ": {
dir: "parentNode"
},
"+": {
dir: "previousSibling",
first: !0
},
"~": {
dir: "previousSibling"
}
},
preFilter: {
ATTR: function(e) {
return e[1] = e[1].replace($, ""), e[3] = (e[4] || e[5] || "").replace($, ""), e[2] === "~=" && (e[3] = " " + e[3] + " "), e.slice(0, 4)
},
CHILD: function(e) {
return e[1] = e[1].toLowerCase(), e[1] === "nth" ? (e[2] || nt.error(e[0]), e[3] = +(e[3] ? e[4] + (e[5] || 1) : 2 * (e[2] === "even" || e[2] === "odd")), e[4] = +(e[6] + e[7] || e[2] === "odd")) : e[2] && nt.error(e[0]), e
},
PSEUDO: function(e) {
var t, n;
if (J.CHILD.test(e[0])) return null;
if (e[3]) e[2] = e[3];
else if (t = e[4]) q.test(t) && (n = ut(t, !0)) && (n = t.indexOf(")", t.length - n) - t.length) && (t = t.slice(0, n), e[0] = e[0].slice(0, n)), e[2] = t;
return e.slice(0, 3)
}
},
filter: {
ID: r ?
function(e) {
return e = e.replace($, ""), function(t) {
return t.getAttribute("id") === e
}
} : function(e) {
return e = e.replace($, ""), function(t) {
var n = typeof t.getAttributeNode !== p && t.getAttributeNode("id");
return n && n.value === e
}
},
TAG: function(e) {
return e === "*" ?
function() {
return !0
} : (e = e.replace($, "").toLowerCase(), function(t) {
return t.nodeName && t.nodeName.toLowerCase() === e
})
},
CLASS: function(e) {
var t = k[d][e + " "];
return t || (t = new RegExp("(^|" + O + ")" + e + "(" + O + "|$)")) && k(e, function(e) {
return t.test(e.className || typeof e.getAttribute !== p && e.getAttribute("class") || "")
})
},
ATTR: function(e, t, n) {
return function(r, i) {
var s = nt.attr(r, e);
return s == null ? t === "!=" : t ? (s += "", t === "=" ? s === n : t === "!=" ? s !== n : t === "^=" ? n && s.indexOf(n) === 0 : t === "*=" ? n && s.indexOf(n) > -1 : t === "$=" ? n && s.substr(s.length - n.length) === n : t === "~=" ? (" " + s + " ").indexOf(n) > -1 : t === "|=" ? s === n || s.substr(0, n.length + 1) === n + "-" : !1) : !0
}
},
CHILD: function(e, t, n, r) {
return e === "nth" ?
function(e) {
var t, i, s = e.parentNode;
if (n === 1 && r === 0) return !0;
if (s) {
i = 0;
for (t = s.firstChild; t; t = t.nextSibling) if (t.nodeType === 1) {
i++;
if (e === t) break
}
}
return i -= r, i === n || i % n === 0 && i / n >= 0
} : function(t) {
var n = t;
switch (e) {
case "only":
case "first":
while (n = n.previousSibling) if (n.nodeType === 1) return !1;
if (e === "first") return !0;
n = t;
case "last":
while (n = n.nextSibling) if (n.nodeType === 1) return !1;
return !0
}
}
},
PSEUDO: function(e, t) {
var n, r = i.pseudos[e] || i.setFilters[e.toLowerCase()] || nt.error("unsupported pseudo: " + e);
return r[d] ? r(t) : r.length > 1 ? (n = [e, e, "", t], i.setFilters.hasOwnProperty(e.toLowerCase()) ? N(function(e, n) {
var i, s = r(e, t),
o = s.length;
while (o--) i = T.call(e, s[o]), e[i] = !(n[i] = s[o])
}) : function(e) {
return r(e, 0, n)
}) : r
}
},
pseudos: {
not: N(function(e) {
var t = [],
n = [],
r = a(e.replace(j, "$1"));
return r[d] ? N(function(e, t, n, i) {
var s, o = r(e, null, i, []),
u = e.length;
while (u--) if (s = o[u]) e[u] = !(t[u] = s)
}) : function(e, i, s) {
return t[0] = e, r(t, null, s, n), !n.pop()
}
}),
has: N(function(e) {
return function(t) {
return nt(e, t).length > 0
}
}),
contains: N(function(e) {
return function(t) {
return (t.textContent || t.innerText || s(t)).indexOf(e) > -1
}
}),
enabled: function(e) {
return e.disabled === !1
},
disabled: function(e) {
return e.disabled === !0
},
checked: function(e) {
var t = e.nodeName.toLowerCase();
return t === "input" && !! e.checked || t === "option" && !! e.selected
},
selected: function(e) {
return e.parentNode && e.parentNode.selectedIndex, e.selected === !0
},
parent: function(e) {
return !i.pseudos.empty(e)
},
empty: function(e) {
var t;
e = e.firstChild;
while (e) {
if (e.nodeName > "@" || (t = e.nodeType) === 3 || t === 4) return !1;
e = e.nextSibling
}
return !0
},
header: function(e) {
return X.test(e.nodeName)
},
text: function(e) {
var t, n;
return e.nodeName.toLowerCase() === "input" && (t = e.type) === "text" && ((n = e.getAttribute("type")) == null || n.toLowerCase() === t)
},
radio: rt("radio"),
checkbox: rt("checkbox"),
file: rt("file"),
password: rt("password"),
image: rt("image"),
submit: it("submit"),
reset: it("reset"),
button: function(e) {
var t = e.nodeName.toLowerCase();
return t === "input" && e.type === "button" || t === "button"
},
input: function(e) {
return V.test(e.nodeName)
},
focus: function(e) {
var t = e.ownerDocument;
return e === t.activeElement && (!t.hasFocus || t.hasFocus()) && !! (e.type || e.href || ~e.tabIndex)
},
active: function(e) {
return e === e.ownerDocument.activeElement
},
first: st(function() {
return [0]
}),
last: st(function(e, t) {
return [t - 1]
}),
eq: st(function(e, t, n) {
return [n < 0 ? n + t : n]
}),
even: st(function(e, t) {
for (var n = 0; n < t; n += 2) e.push(n);
return e
}),
odd: st(function(e, t) {
for (var n = 1; n < t; n += 2) e.push(n);
return e
}),
lt: st(function(e, t, n) {
for (var r = n < 0 ? n + t : n; --r >= 0;) e.push(r);
return e
}),
gt: st(function(e, t, n) {
for (var r = n < 0 ? n + t : n; ++r < t;) e.push(r);
return e
})
}
}, f = y.compareDocumentPosition ?
function(e, t) {
return e === t ? (l = !0, 0) : (!e.compareDocumentPosition || !t.compareDocumentPosition ? e.compareDocumentPosition : e.compareDocumentPosition(t) & 4) ? -1 : 1
} : function(e, t) {
if (e === t) return l = !0, 0;
if (e.sourceIndex && t.sourceIndex) return e.sourceIndex - t.sourceIndex;
var n, r, i = [],
s = [],
o = e.parentNode,
u = t.parentNode,
a = o;
if (o === u) return ot(e, t);
if (!o) return -1;
if (!u) return 1;
while (a) i.unshift(a), a = a.parentNode;
a = u;
while (a) s.unshift(a), a = a.parentNode;
n = i.length, r = s.length;
for (var f = 0; f < n && f < r; f++) if (i[f] !== s[f]) return ot(i[f], s[f]);
return f === n ? ot(e, s[f], -1) : ot(i[f], t, 1)
}, [0, 0].sort(f), h = !l, nt.uniqueSort = function(e) {
var t, n = [],
r = 1,
i = 0;
l = h, e.sort(f);
if (l) {
for (; t = e[r]; r++) t === e[r - 1] && (i = n.push(r));
while (i--) e.splice(n[i], 1)
}
return e
}, nt.error = function(e) {
throw new Error("Syntax error, unrecognized expression: " + e)
}, a = nt.compile = function(e, t) {
var n, r = [],
i = [],
s = A[d][e + " "];
if (!s) {
t || (t = ut(e)), n = t.length;
while (n--) s = ht(t[n]), s[d] ? r.push(s) : i.push(s);
s = A(e, pt(i, r))
}
return s
}, g.querySelectorAll &&
function() {
var e, t = vt,
n = /'|\\/g,
r = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
i = [":focus"],
s = [":active"],
u = y.matchesSelector || y.mozMatchesSelector || y.webkitMatchesSelector || y.oMatchesSelector || y.msMatchesSelector;
K(function(e) {
e.innerHTML = "<select><option selected=''></option></select>", e.querySelectorAll("[selected]").length || i.push("\\[" + O + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)"), e.querySelectorAll(":checked").length || i.push(":checked")
}), K(function(e) {
e.innerHTML = "<p test=''></p>", e.querySelectorAll("[test^='']").length && i.push("[*^$]=" + O + "*(?:\"\"|'')"), e.innerHTML = "<input type='hidden'/>", e.querySelectorAll(":enabled").length || i.push(":enabled", ":disabled")
}), i = new RegExp(i.join("|")), vt = function(e, r, s, o, u) {
if (!o && !u && !i.test(e)) {
var a, f, l = !0,
c = d,
h = r,
p = r.nodeType === 9 && e;
if (r.nodeType === 1 && r.nodeName.toLowerCase() !== "object") {
a = ut(e), (l = r.getAttribute("id")) ? c = l.replace(n, "\\$&") : r.setAttribute("id", c), c = "[id='" + c + "'] ", f = a.length;
while (f--) a[f] = c + a[f].join("");
h = z.test(e) && r.parentNode || r, p = a.join(",")
}
if (p) try {
return S.apply(s, x.call(h.querySelectorAll(p), 0)), s
} catch (v) {} finally {
l || r.removeAttribute("id")
}
}
return t(e, r, s, o, u)
}, u && (K(function(t) {
e = u.call(t, "div");
try {
u.call(t, "[test!='']:sizzle"), s.push("!=", H)
} catch (n) {}
}), s = new RegExp(s.join("|")), nt.matchesSelector = function(t, n) {
n = n.replace(r, "='$1']");
if (!o(t) && !s.test(n) && !i.test(n)) try {
var a = u.call(t, n);
if (a || e || t.document && t.document.nodeType !== 11) return a
} catch (f) {}
return nt(n, null, null, [t]).length > 0
})
}(), i.pseudos.nth = i.pseudos.eq, i.filters = mt.prototype = i.pseudos, i.setFilters = new mt, nt.attr = v.attr, v.find = nt, v.expr = nt.selectors, v.expr[":"] = v.expr.pseudos, v.unique = nt.uniqueSort, v.text = nt.getText, v.isXMLDoc = nt.isXML, v.contains = nt.contains
}(e);
var nt = /Until$/,
rt = /^(?:parents|prev(?:Until|All))/,
it = /^.[^:#\[\.,]*$/,
st = v.expr.match.needsContext,
ot = {
children: !0,
contents: !0,
next: !0,
prev: !0
};
v.fn.extend({
find: function(e) {
var t, n, r, i, s, o, u = this;
if (typeof e != "string") return v(e).filter(function() {
for (t = 0, n = u.length; t < n; t++) if (v.contains(u[t], this)) return !0
});
o = this.pushStack("", "find", e);
for (t = 0, n = this.length; t < n; t++) {
r = o.length, v.find(e, this[t], o);
if (t > 0) for (i = r; i < o.length; i++) for (s = 0; s < r; s++) if (o[s] === o[i]) {
o.splice(i--, 1);
break
}
}
return o
},
has: function(e) {
var t, n = v(e, this),
r = n.length;
return this.filter(function() {
for (t = 0; t < r; t++) if (v.contains(this, n[t])) return !0
})
},
not: function(e) {
return this.pushStack(ft(this, e, !1), "not", e)
},
filter: function(e) {
return this.pushStack(ft(this, e, !0), "filter", e)
},
is: function(e) {
return !!e && (typeof e == "string" ? st.test(e) ? v(e, this.context).index(this[0]) >= 0 : v.filter(e, this).length > 0 : this.filter(e).length > 0)
},
closest: function(e, t) {
var n, r = 0,
i = this.length,
s = [],
o = st.test(e) || typeof e != "string" ? v(e, t || this.context) : 0;
for (; r < i; r++) {
n = this[r];
while (n && n.ownerDocument && n !== t && n.nodeType !== 11) {
if (o ? o.index(n) > -1 : v.find.matchesSelector(n, e)) {
s.push(n);
break
}
n = n.parentNode
}
}
return s = s.length > 1 ? v.unique(s) : s, this.pushStack(s, "closest", e)
},
index: function(e) {
return e ? typeof e == "string" ? v.inArray(this[0], v(e)) : v.inArray(e.jquery ? e[0] : e, this) : this[0] && this[0].parentNode ? this.prevAll().length : -1
},
add: function(e, t) {
var n = typeof e == "string" ? v(e, t) : v.makeArray(e && e.nodeType ? [e] : e),
r = v.merge(this.get(), n);
return this.pushStack(ut(n[0]) || ut(r[0]) ? r : v.unique(r))
},
addBack: function(e) {
return this.add(e == null ? this.prevObject : this.prevObject.filter(e))
}
}), v.fn.andSelf = v.fn.addBack, v.each({
parent: function(e) {
var t = e.parentNode;
return t && t.nodeType !== 11 ? t : null
},
parents: function(e) {
return v.dir(e, "parentNode")
},
parentsUntil: function(e, t, n) {
return v.dir(e, "parentNode", n)
},
next: function(e) {
return at(e, "nextSibling")
},
prev: function(e) {
return at(e, "previousSibling")
},
nextAll: function(e) {
return v.dir(e, "nextSibling")
},
prevAll: function(e) {
return v.dir(e, "previousSibling")
},
nextUntil: function(e, t, n) {
return v.dir(e, "nextSibling", n)
},
prevUntil: function(e, t, n) {
return v.dir(e, "previousSibling", n)
},
siblings: function(e) {
return v.sibling((e.parentNode || {}).firstChild, e)
},
children: function(e) {
return v.sibling(e.firstChild)
},
contents: function(e) {
return v.nodeName(e, "iframe") ? e.contentDocument || e.contentWindow.document : v.merge([], e.childNodes)
}
}, function(e, t) {
v.fn[e] = function(n, r) {
var i = v.map(this, t, n);
return nt.test(e) || (r = n), r && typeof r == "string" && (i = v.filter(r, i)), i = this.length > 1 && !ot[e] ? v.unique(i) : i, this.length > 1 && rt.test(e) && (i = i.reverse()), this.pushStack(i, e, l.call(arguments).join(","))
}
}), v.extend({
filter: function(e, t, n) {
return n && (e = ":not(" + e + ")"), t.length === 1 ? v.find.matchesSelector(t[0], e) ? [t[0]] : [] : v.find.matches(e, t)
},
dir: function(e, n, r) {
var i = [],
s = e[n];
while (s && s.nodeType !== 9 && (r === t || s.nodeType !== 1 || !v(s).is(r))) s.nodeType === 1 && i.push(s), s = s[n];
return i
},
sibling: function(e, t) {
var n = [];
for (; e; e = e.nextSibling) e.nodeType === 1 && e !== t && n.push(e);
return n
}
});
var ct = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
ht = / jQuery\d+="(?:null|\d+)"/g,
pt = /^\s+/,
dt = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
vt = /<([\w:]+)/,
mt = /<tbody/i,
gt = /<|&#?\w+;/,
yt = /<(?:script|style|link)/i,
bt = /<(?:script|object|embed|option|style)/i,
wt = new RegExp("<(?:" + ct + ")[\\s/>]", "i"),
Et = /^(?:checkbox|radio)$/,
St = /checked\s*(?:[^=]|=\s*.checked.)/i,
xt = /\/(java|ecma)script/i,
Tt = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,
Nt = {
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, "", ""]
},
Ct = lt(i),
kt = Ct.appendChild(i.createElement("div"));
Nt.optgroup = Nt.option, Nt.tbody = Nt.tfoot = Nt.colgroup = Nt.caption = Nt.thead, Nt.th = Nt.td, v.support.htmlSerialize || (Nt._default = [1, "X<div>", "</div>"]), v.fn.extend({
text: function(e) {
return v.access(this, function(e) {
return e === t ? v.text(this) : this.empty().append((this[0] && this[0].ownerDocument || i).createTextNode(e))
}, null, e, arguments.length)
},
wrapAll: function(e) {
if (v.isFunction(e)) return this.each(function(t) {
v(this).wrapAll(e.call(this, t))
});
if (this[0]) {
var t = v(e, this[0].ownerDocument).eq(0).clone(!0);
this[0].parentNode && t.insertBefore(this[0]), t.map(function() {
var e = this;
while (e.firstChild && e.firstChild.nodeType === 1) e = e.firstChild;
return e
}).append(this)
}
return this
},
wrapInner: function(e) {
return v.isFunction(e) ? this.each(function(t) {
v(this).wrapInner(e.call(this, t))
}) : this.each(function() {
var t = v(this),
n = t.contents();
n.length ? n.wrapAll(e) : t.append(e)
})
},
wrap: function(e) {
var t = v.isFunction(e);
return this.each(function(n) {
v(this).wrapAll(t ? e.call(this, n) : e)
})
},
unwrap: function() {
return this.parent().each(function() {
v.nodeName(this, "body") || v(this).replaceWith(this.childNodes)
}).end()
},
append: function() {
return this.domManip(arguments, !0, function(e) {
(this.nodeType === 1 || this.nodeType === 11) && this.appendChild(e)
})
},
prepend: function() {
return this.domManip(arguments, !0, function(e) {
(this.nodeType === 1 || this.nodeType === 11) && this.insertBefore(e, this.firstChild)
})
},
before: function() {
if (!ut(this[0])) return this.domManip(arguments, !1, function(e) {
this.parentNode.insertBefore(e, this)
});
if (arguments.length) {
var e = v.clean(arguments);
return this.pushStack(v.merge(e, this), "before", this.selector)
}
},
after: function() {
if (!ut(this[0])) return this.domManip(arguments, !1, function(e) {
this.parentNode.insertBefore(e, this.nextSibling)
});
if (arguments.length) {
var e = v.clean(arguments);
return this.pushStack(v.merge(this, e), "after", this.selector)
}
},
remove: function(e, t) {
var n, r = 0;
for (;
(n = this[r]) != null; r++) if (!e || v.filter(e, [n]).length)!t && n.nodeType === 1 && (v.cleanData(n.getElementsByTagName("*")), v.cleanData([n])), n.parentNode && n.parentNode.removeChild(n);
return this
},
empty: function() {
var e, t = 0;
for (;
(e = this[t]) != null; t++) {
e.nodeType === 1 && v.cleanData(e.getElementsByTagName("*"));
while (e.firstChild) e.removeChild(e.firstChild)
}
return this
},
clone: function(e, t) {
return e = e == null ? !1 : e, t = t == null ? e : t, this.map(function() {
return v.clone(this, e, t)
})
},
html: function(e) {
return v.access(this, function(e) {
var n = this[0] || {},
r = 0,
i = this.length;
if (e === t) return n.nodeType === 1 ? n.innerHTML.replace(ht, "") : t;
if (typeof e == "string" && !yt.test(e) && (v.support.htmlSerialize || !wt.test(e)) && (v.support.leadingWhitespace || !pt.test(e)) && !Nt[(vt.exec(e) || ["", ""])[1].toLowerCase()]) {
e = e.replace(dt, "<$1></$2>");
try {
for (; r < i; r++) n = this[r] || {}, n.nodeType === 1 && (v.cleanData(n.getElementsByTagName("*")), n.innerHTML = e);
n = 0
} catch (s) {}
}
n && this.empty().append(e)
}, null, e, arguments.length)
},
replaceWith: function(e) {
return ut(this[0]) ? this.length ? this.pushStack(v(v.isFunction(e) ? e() : e), "replaceWith", e) : this : v.isFunction(e) ? this.each(function(t) {
var n = v(this),
r = n.html();
n.replaceWith(e.call(this, t, r))
}) : (typeof e != "string" && (e = v(e).detach()), this.each(function() {
var t = this.nextSibling,
n = this.parentNode;
v(this).remove(), t ? v(t).before(e) : v(n).append(e)
}))
},
detach: function(e) {
return this.remove(e, !0)
},
domManip: function(e, n, r) {
e = [].concat.apply([], e);
var i, s, o, u, a = 0,
f = e[0],
l = [],
c = this.length;
if (!v.support.checkClone && c > 1 && typeof f == "string" && St.test(f)) return this.each(function() {
v(this).domManip(e, n, r)
});
if (v.isFunction(f)) return this.each(function(i) {
var s = v(this);
e[0] = f.call(this, i, n ? s.html() : t), s.domManip(e, n, r)
});
if (this[0]) {
i = v.buildFragment(e, this, l), o = i.fragment, s = o.firstChild, o.childNodes.length === 1 && (o = s);
if (s) {
n = n && v.nodeName(s, "tr");
for (u = i.cacheable || c - 1; a < c; a++) r.call(n && v.nodeName(this[a], "table") ? Lt(this[a], "tbody") : this[a], a === u ? o : v.clone(o, !0, !0))
}
o = s = null, l.length && v.each(l, function(e, t) {
t.src ? v.ajax ? v.ajax({
url: t.src,
type: "GET",
dataType: "script",
async: !1,
global: !1,
"throws": !0
}) : v.error("no ajax") : v.globalEval((t.text || t.textContent || t.innerHTML || "").replace(Tt, "")), t.parentNode && t.parentNode.removeChild(t)
})
}
return this
}
}), v.buildFragment = function(e, n, r) {
var s, o, u, a = e[0];
return n = n || i, n = !n.nodeType && n[0] || n, n = n.ownerDocument || n, e.length === 1 && typeof a == "string" && a.length < 512 && n === i && a.charAt(0) === "<" && !bt.test(a) && (v.support.checkClone || !St.test(a)) && (v.support.html5Clone || !wt.test(a)) && (o = !0, s = v.fragments[a], u = s !== t), s || (s = n.createDocumentFragment(), v.clean(e, n, s, r), o && (v.fragments[a] = u && s)), {
fragment: s,
cacheable: o
}
}, v.fragments = {}, v.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function(e, t) {
v.fn[e] = function(n) {
var r, i = 0,
s = [],
o = v(n),
u = o.length,
a = this.length === 1 && this[0].parentNode;
if ((a == null || a && a.nodeType === 11 && a.childNodes.length === 1) && u === 1) return o[t](this[0]), this;
for (; i < u; i++) r = (i > 0 ? this.clone(!0) : this).get(), v(o[i])[t](r), s = s.concat(r);
return this.pushStack(s, e, o.selector)
}
}), v.extend({
clone: function(e, t, n) {
var r, i, s, o;
v.support.html5Clone || v.isXMLDoc(e) || !wt.test("<" + e.nodeName + ">") ? o = e.cloneNode(!0) : (kt.innerHTML = e.outerHTML, kt.removeChild(o = kt.firstChild));
if ((!v.support.noCloneEvent || !v.support.noCloneChecked) && (e.nodeType === 1 || e.nodeType === 11) && !v.isXMLDoc(e)) {
Ot(e, o), r = Mt(e), i = Mt(o);
for (s = 0; r[s]; ++s) i[s] && Ot(r[s], i[s])
}
if (t) {
At(e, o);
if (n) {
r = Mt(e), i = Mt(o);
for (s = 0; r[s]; ++s) At(r[s], i[s])
}
}
return r = i = null, o
},
clean: function(e, t, n, r) {
var s, o, u, a, f, l, c, h, p, d, m, g, y = t === i && Ct,
b = [];
if (!t || typeof t.createDocumentFragment == "undefined") t = i;
for (s = 0;
(u = e[s]) != null; s++) {
typeof u == "number" && (u += "");
if (!u) continue;
if (typeof u == "string") if (!gt.test(u)) u = t.createTextNode(u);
else {
y = y || lt(t), c = t.createElement("div"), y.appendChild(c), u = u.replace(dt, "<$1></$2>"), a = (vt.exec(u) || ["", ""])[1].toLowerCase(), f = Nt[a] || Nt._default, l = f[0], c.innerHTML = f[1] + u + f[2];
while (l--) c = c.lastChild;
if (!v.support.tbody) {
h = mt.test(u), p = a === "table" && !h ? c.firstChild && c.firstChild.childNodes : f[1] === "<table>" && !h ? c.childNodes : [];
for (o = p.length - 1; o >= 0; --o) v.nodeName(p[o], "tbody") && !p[o].childNodes.length && p[o].parentNode.removeChild(p[o])
}!v.support.leadingWhitespace && pt.test(u) && c.insertBefore(t.createTextNode(pt.exec(u)[0]), c.firstChild), u = c.childNodes, c.parentNode.removeChild(c)
}
u.nodeType ? b.push(u) : v.merge(b, u)
}
c && (u = c = y = null);
if (!v.support.appendChecked) for (s = 0;
(u = b[s]) != null; s++) v.nodeName(u, "input") ? _t(u) : typeof u.getElementsByTagName != "undefined" && v.grep(u.getElementsByTagName("input"), _t);
if (n) {
m = function(e) {
if (!e.type || xt.test(e.type)) return r ? r.push(e.parentNode ? e.parentNode.removeChild(e) : e) : n.appendChild(e)
};
for (s = 0;
(u = b[s]) != null; s++) if (!v.nodeName(u, "script") || !m(u)) n.appendChild(u), typeof u.getElementsByTagName != "undefined" && (g = v.grep(v.merge([], u.getElementsByTagName("script")), m), b.splice.apply(b, [s + 1, 0].concat(g)), s += g.length)
}
return b
},
cleanData: function(e, t) {
var n, r, i, s, o = 0,
u = v.expando,
a = v.cache,
f = v.support.deleteExpando,
l = v.event.special;
for (;
(i = e[o]) != null; o++) if (t || v.acceptData(i)) {
r = i[u], n = r && a[r];
if (n) {
if (n.events) for (s in n.events) l[s] ? v.event.remove(i, s) : v.removeEvent(i, s, n.handle);
a[r] && (delete a[r], f ? delete i[u] : i.removeAttribute ? i.removeAttribute(u) : i[u] = null, v.deletedIds.push(r))
}
}
}
}), function() {
var e, t;
v.uaMatch = function(e) {
e = e.toLowerCase();
var t = /(chrome)[ \/]([\w.]+)/.exec(e) || /(webkit)[ \/]([\w.]+)/.exec(e) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e) || /(msie) ([\w.]+)/.exec(e) || e.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e) || [];
return {
browser: t[1] || "",
version: t[2] || "0"
}
}, e = v.uaMatch(o.userAgent), t = {}, e.browser && (t[e.browser] = !0, t.version = e.version), t.chrome ? t.webkit = !0 : t.webkit && (t.safari = !0), v.browser = t, v.sub = function() {
function e(t, n) {
return new e.fn.init(t, n)
}
v.extend(!0, e, this), e.superclass = this, e.fn = e.prototype = this(), e.fn.constructor = e, e.sub = this.sub, e.fn.init = function(r, i) {
return i && i instanceof v && !(i instanceof e) && (i = e(i)), v.fn.init.call(this, r, i, t)
}, e.fn.init.prototype = e.fn;
var t = e(i);
return e
}
}();
var Dt, Pt, Ht, Bt = /alpha\([^)]*\)/i,
jt = /opacity=([^)]*)/,
Ft = /^(top|right|bottom|left)$/,
It = /^(none|table(?!-c[ea]).+)/,
qt = /^margin/,
Rt = new RegExp("^(" + m + ")(.*)$", "i"),
Ut = new RegExp("^(" + m + ")(?!px)[a-z%]+$", "i"),
zt = new RegExp("^([-+])=(" + m + ")", "i"),
Wt = {
BODY: "block"
},
Xt = {
position: "absolute",
visibility: "hidden",
display: "block"
},
Vt = {
letterSpacing: 0,
fontWeight: 400
},
$t = ["Top", "Right", "Bottom", "Left"],
Jt = ["Webkit", "O", "Moz", "ms"],
Kt = v.fn.toggle;
v.fn.extend({
css: function(e, n) {
return v.access(this, function(e, n, r) {
return r !== t ? v.style(e, n, r) : v.css(e, n)
}, e, n, arguments.length > 1)
},
show: function() {
return Yt(this, !0)
},
hide: function() {
return Yt(this)
},
toggle: function(e, t) {
var n = typeof e == "boolean";
return v.isFunction(e) && v.isFunction(t) ? Kt.apply(this, arguments) : this.each(function() {
(n ? e : Gt(this)) ? v(this).show() : v(this).hide()
})
}
}), v.extend({
cssHooks: {
opacity: {
get: function(e, t) {
if (t) {
var n = Dt(e, "opacity");
return n === "" ? "1" : n
}
}
}
},
cssNumber: {
fillOpacity: !0,
fontWeight: !0,
lineHeight: !0,
opacity: !0,
orphans: !0,
widows: !0,
zIndex: !0,
zoom: !0
},
cssProps: {
"float": v.support.cssFloat ? "cssFloat" : "styleFloat"
},
style: function(e, n, r, i) {
if (!e || e.nodeType === 3 || e.nodeType === 8 || !e.style) return;
var s, o, u, a = v.camelCase(n),
f = e.style;
n = v.cssProps[a] || (v.cssProps[a] = Qt(f, a)), u = v.cssHooks[n] || v.cssHooks[a];
if (r === t) return u && "get" in u && (s = u.get(e, !1, i)) !== t ? s : f[n];
o = typeof r, o === "string" && (s = zt.exec(r)) && (r = (s[1] + 1) * s[2] + parseFloat(v.css(e, n)), o = "number");
if (r == null || o === "number" && isNaN(r)) return;
o === "number" && !v.cssNumber[a] && (r += "px");
if (!u || !("set" in u) || (r = u.set(e, r, i)) !== t) try {
f[n] = r
} catch (l) {}
},
css: function(e, n, r, i) {
var s, o, u, a = v.camelCase(n);
return n = v.cssProps[a] || (v.cssProps[a] = Qt(e.style, a)), u = v.cssHooks[n] || v.cssHooks[a], u && "get" in u && (s = u.get(e, !0, i)), s === t && (s = Dt(e, n)), s === "normal" && n in Vt && (s = Vt[n]), r || i !== t ? (o = parseFloat(s), r || v.isNumeric(o) ? o || 0 : s) : s
},
swap: function(e, t, n) {
var r, i, s = {};
for (i in t) s[i] = e.style[i], e.style[i] = t[i];
r = n.call(e);
for (i in t) e.style[i] = s[i];
return r
}
}), e.getComputedStyle ? Dt = function(t, n) {
var r, i, s, o, u = e.getComputedStyle(t, null),
a = t.style;
return u && (r = u.getPropertyValue(n) || u[n], r === "" && !v.contains(t.ownerDocument, t) && (r = v.style(t, n)), Ut.test(r) && qt.test(n) && (i = a.width, s = a.minWidth, o = a.maxWidth, a.minWidth = a.maxWidth = a.width = r, r = u.width, a.width = i, a.minWidth = s, a.maxWidth = o)), r
} : i.documentElement.currentStyle && (Dt = function(e, t) {
var n, r, i = e.currentStyle && e.currentStyle[t],
s = e.style;
return i == null && s && s[t] && (i = s[t]), Ut.test(i) && !Ft.test(t) && (n = s.left, r = e.runtimeStyle && e.runtimeStyle.left, r && (e.runtimeStyle.left = e.currentStyle.left), s.left = t === "fontSize" ? "1em" : i, i = s.pixelLeft + "px", s.left = n, r && (e.runtimeStyle.left = r)), i === "" ? "auto" : i
}), v.each(["height", "width"], function(e, t) {
v.cssHooks[t] = {
get: function(e, n, r) {
if (n) return e.offsetWidth === 0 && It.test(Dt(e, "display")) ? v.swap(e, Xt, function() {
return tn(e, t, r)
}) : tn(e, t, r)
},
set: function(e, n, r) {
return Zt(e, n, r ? en(e, t, r, v.support.boxSizing && v.css(e, "boxSizing") === "border-box") : 0)
}
}
}), v.support.opacity || (v.cssHooks.opacity = {
get: function(e, t) {
return jt.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 = v.isNumeric(t) ? "alpha(opacity=" + t * 100 + ")" : "",
s = r && r.filter || n.filter || "";
n.zoom = 1;
if (t >= 1 && v.trim(s.replace(Bt, "")) === "" && n.removeAttribute) {
n.removeAttribute("filter");
if (r && !r.filter) return
}
n.filter = Bt.test(s) ? s.replace(Bt, i) : s + " " + i
}
}), v(function() {
v.support.reliableMarginRight || (v.cssHooks.marginRight = {
get: function(e, t) {
return v.swap(e, {
display: "inline-block"
}, function() {
if (t) return Dt(e, "marginRight")
})
}
}), !v.support.pixelPosition && v.fn.position && v.each(["top", "left"], function(e, t) {
v.cssHooks[t] = {
get: function(e, n) {
if (n) {
var r = Dt(e, t);
return Ut.test(r) ? v(e).position()[t] + "px" : r
}
}
}
})
}), v.expr && v.expr.filters && (v.expr.filters.hidden = function(e) {
return e.offsetWidth === 0 && e.offsetHeight === 0 || !v.support.reliableHiddenOffsets && (e.style && e.style.display || Dt(e, "display")) === "none"
}, v.expr.filters.visible = function(e) {
return !v.expr.filters.hidden(e)
}), v.each({
margin: "",
padding: "",
border: "Width"
}, function(e, t) {
v.cssHooks[e + t] = {
expand: function(n) {
var r, i = typeof n == "string" ? n.split(" ") : [n],
s = {};
for (r = 0; r < 4; r++) s[e + $t[r] + t] = i[r] || i[r - 2] || i[0];
return s
}
}, qt.test(e) || (v.cssHooks[e + t].set = Zt)
});
var rn = /%20/g,
sn = /\[\]$/,
on = /\r?\n/g,
un = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
an = /^(?:select|textarea)/i;
v.fn.extend({
serialize: function() {
return v.param(this.serializeArray())
},
serializeArray: function() {
return this.map(function() {
return this.elements ? v.makeArray(this.elements) : this
}).filter(function() {
return this.name && !this.disabled && (this.checked || an.test(this.nodeName) || un.test(this.type))
}).map(function(e, t) {
var n = v(this).val();
return n == null ? null : v.isArray(n) ? v.map(n, function(e, n) {
return {
name: t.name,
value: e.replace(on, "\r\n")
}
}) : {
name: t.name,
value: n.replace(on, "\r\n")
}
}).get()
}
}), v.param = function(e, n) {
var r, i = [],
s = function(e, t) {
t = v.isFunction(t) ? t() : t == null ? "" : t, i[i.length] = encodeURIComponent(e) + "=" + encodeURIComponent(t)
};
n === t && (n = v.ajaxSettings && v.ajaxSettings.traditional);
if (v.isArray(e) || e.jquery && !v.isPlainObject(e)) v.each(e, function() {
s(this.name, this.value)
});
else for (r in e) fn(r, e[r], n, s);
return i.join("&").replace(rn, "+")
};
var ln, cn, hn = /#.*$/,
pn = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg,
dn = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
vn = /^(?:GET|HEAD)$/,
mn = /^\/\//,
gn = /\?/,
yn = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
bn = /([?&])_=[^&]*/,
wn = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
En = v.fn.load,
Sn = {},
xn = {},
Tn = ["*/"] + ["*"];
try {
cn = s.href
} catch (Nn) {
cn = i.createElement("a"), cn.href = "", cn = cn.href
}
ln = wn.exec(cn.toLowerCase()) || [], v.fn.load = function(e, n, r) {
if (typeof e != "string" && En) return En.apply(this, arguments);
if (!this.length) return this;
var i, s, o, u = this,
a = e.indexOf(" ");
return a >= 0 && (i = e.slice(a, e.length), e = e.slice(0, a)), v.isFunction(n) ? (r = n, n = t) : n && typeof n == "object" && (s = "POST"), v.ajax({
url: e,
type: s,
dataType: "html",
data: n,
complete: function(e, t) {
r && u.each(r, o || [e.responseText, t, e])
}
}).done(function(e) {
o = arguments, u.html(i ? v("<div>").append(e.replace(yn, "")).find(i) : e)
}), this
}, v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function(e, t) {
v.fn[t] = function(e) {
return this.on(t, e)
}
}), v.each(["get", "post"], function(e, n) {
v[n] = function(e, r, i, s) {
return v.isFunction(r) && (s = s || i, i = r, r = t), v.ajax({
type: n,
url: e,
data: r,
success: i,
dataType: s
})
}
}), v.extend({
getScript: function(e, n) {
return v.get(e, t, n, "script")
},
getJSON: function(e, t, n) {
return v.get(e, t, n, "json")
},
ajaxSetup: function(e, t) {
return t ? Ln(e, v.ajaxSettings) : (t = e, e = v.ajaxSettings), Ln(e, t), e
},
ajaxSettings: {
url: cn,
isLocal: dn.test(ln[1]),
global: !0,
type: "GET",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
processData: !0,
async: !0,
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": Tn
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
converters: {
"* text": e.String,
"text html": !0,
"text json": v.parseJSON,
"text xml": v.parseXML
},
flatOptions: {
context: !0,
url: !0
}
},
ajaxPrefilter: Cn(Sn),
ajaxTransport: Cn(xn),
ajax: function(e, n) {
function T(e, n, s, a) {
var l, y, b, w, S, T = n;
if (E === 2) return;
E = 2, u && clearTimeout(u), o = t, i = a || "", x.readyState = e > 0 ? 4 : 0, s && (w = An(c, x, s));
if (e >= 200 && e < 300 || e === 304) c.ifModified && (S = x.getResponseHeader("Last-Modified"), S && (v.lastModified[r] = S), S = x.getResponseHeader("Etag"), S && (v.etag[r] = S)), e === 304 ? (T = "notmodified", l = !0) : (l = On(c, w), T = l.state, y = l.data, b = l.error, l = !b);
else {
b = T;
if (!T || e) T = "error", e < 0 && (e = 0)
}
x.status = e, x.statusText = (n || T) + "", l ? d.resolveWith(h, [y, T, x]) : d.rejectWith(h, [x, T, b]), x.statusCode(g), g = t, f && p.trigger("ajax" + (l ? "Success" : "Error"), [x, c, l ? y : b]), m.fireWith(h, [x, T]), f && (p.trigger("ajaxComplete", [x, c]), --v.active || v.event.trigger("ajaxStop"))
}
typeof e == "object" && (n = e, e = t), n = n || {};
var r, i, s, o, u, a, f, l, c = v.ajaxSetup({}, n),
h = c.context || c,
p = h !== c && (h.nodeType || h instanceof v) ? v(h) : v.event,
d = v.Deferred(),
m = v.Callbacks("once memory"),
g = c.statusCode || {},
b = {},
w = {},
E = 0,
S = "canceled",
x = {
readyState: 0,
setRequestHeader: function(e, t) {
if (!E) {
var n = e.toLowerCase();
e = w[n] = w[n] || e, b[e] = t
}
return this
},
getAllResponseHeaders: function() {
return E === 2 ? i : null
},
getResponseHeader: function(e) {
var n;
if (E === 2) {
if (!s) {
s = {};
while (n = pn.exec(i)) s[n[1].toLowerCase()] = n[2]
}
n = s[e.toLowerCase()]
}
return n === t ? null : n
},
overrideMimeType: function(e) {
return E || (c.mimeType = e), this
},
abort: function(e) {
return e = e || S, o && o.abort(e), T(0, e), this
}
};
d.promise(x), x.success = x.done, x.error = x.fail, x.complete = m.add, x.statusCode = function(e) {
if (e) {
var t;
if (E < 2) for (t in e) g[t] = [g[t], e[t]];
else t = e[x.status], x.always(t)
}
return this
}, c.url = ((e || c.url) + "").replace(hn, "").replace(mn, ln[1] + "//"), c.dataTypes = v.trim(c.dataType || "*").toLowerCase().split(y), c.crossDomain == null && (a = wn.exec(c.url.toLowerCase()), c.crossDomain = !(!a || a[1] === ln[1] && a[2] === ln[2] && (a[3] || (a[1] === "http:" ? 80 : 443)) == (ln[3] || (ln[1] === "http:" ? 80 : 443)))), c.data && c.processData && typeof c.data != "string" && (c.data = v.param(c.data, c.traditional)), kn(Sn, c, n, x);
if (E === 2) return x;
f = c.global, c.type = c.type.toUpperCase(), c.hasContent = !vn.test(c.type), f && v.active++ === 0 && v.event.trigger("ajaxStart");
if (!c.hasContent) {
c.data && (c.url += (gn.test(c.url) ? "&" : "?") + c.data, delete c.data), r = c.url;
if (c.cache === !1) {
var N = v.now(),
C = c.url.replace(bn, "$1_=" + N);
c.url = C + (C === c.url ? (gn.test(c.url) ? "&" : "?") + "_=" + N : "")
}
}(c.data && c.hasContent && c.contentType !== !1 || n.contentType) && x.setRequestHeader("Content-Type", c.contentType), c.ifModified && (r = r || c.url, v.lastModified[r] && x.setRequestHeader("If-Modified-Since", v.lastModified[r]), v.etag[r] && x.setRequestHeader("If-None-Match", v.etag[r])), x.setRequestHeader("Accept", c.dataTypes[0] && c.accepts[c.dataTypes[0]] ? c.accepts[c.dataTypes[0]] + (c.dataTypes[0] !== "*" ? ", " + Tn + "; q=0.01" : "") : c.accepts["*"]);
for (l in c.headers) x.setRequestHeader(l, c.headers[l]);
if (!c.beforeSend || c.beforeSend.call(h, x, c) !== !1 && E !== 2) {
S = "abort";
for (l in {
success: 1,
error: 1,
complete: 1
}) x[l](c[l]);
o = kn(xn, c, n, x);
if (!o) T(-1, "No Transport");
else {
x.readyState = 1, f && p.trigger("ajaxSend", [x, c]), c.async && c.timeout > 0 && (u = setTimeout(function() {
x.abort("timeout")
}, c.timeout));
try {
E = 1, o.send(b, T)
} catch (k) {
if (!(E < 2)) throw k;
T(-1, k)
}
}
return x
}
return x.abort()
},
active: 0,
lastModified: {},
etag: {}
});
var Mn = [],
_n = /\?/,
Dn = /(=)\?(?=&|$)|\?\?/,
Pn = v.now();
v.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var e = Mn.pop() || v.expando + "_" + Pn++;
return this[e] = !0, e
}
}), v.ajaxPrefilter("json jsonp", function(n, r, i) {
var s, o, u, a = n.data,
f = n.url,
l = n.jsonp !== !1,
c = l && Dn.test(f),
h = l && !c && typeof a == "string" && !(n.contentType || "").indexOf("application/x-www-form-urlencoded") && Dn.test(a);
if (n.dataTypes[0] === "jsonp" || c || h) return s = n.jsonpCallback = v.isFunction(n.jsonpCallback) ? n.jsonpCallback() : n.jsonpCallback, o = e[s], c ? n.url = f.replace(Dn, "$1" + s) : h ? n.data = a.replace(Dn, "$1" + s) : l && (n.url += (_n.test(f) ? "&" : "?") + n.jsonp + "=" + s), n.converters["script json"] = function() {
return u || v.error(s + " was not called"), u[0]
}, n.dataTypes[0] = "json", e[s] = function() {
u = arguments
}, i.always(function() {
e[s] = o, n[s] && (n.jsonpCallback = r.jsonpCallback, Mn.push(s)), u && v.isFunction(o) && o(u[0]), u = o = t
}), "script"
}), v.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function(e) {
return v.globalEval(e), e
}
}
}), v.ajaxPrefilter("script", function(e) {
e.cache === t && (e.cache = !1), e.crossDomain && (e.type = "GET", e.global = !1)
}), v.ajaxTransport("script", function(e) {
if (e.crossDomain) {
var n, r = i.head || i.getElementsByTagName("head")[0] || i.documentElement;
return {
send: function(s, o) {
n = i.createElement("script"), n.async = "async", e.scriptCharset && (n.charset = e.scriptCharset), n.src = e.url, n.onload = n.onreadystatechange = function(e, i) {
if (i || !n.readyState || /loaded|complete/.test(n.readyState)) n.onload = n.onreadystatechange = null, r && n.parentNode && r.removeChild(n), n = t, i || o(200, "success")
}, r.insertBefore(n, r.firstChild)
},
abort: function() {
n && n.onload(0, 1)
}
}
}
});
var Hn, Bn = e.ActiveXObject ?
function() {
for (var e in Hn) Hn[e](0, 1)
} : !1,
jn = 0;
v.ajaxSettings.xhr = e.ActiveXObject ?
function() {
return !this.isLocal && Fn() || In()
} : Fn, function(e) {
v.extend(v.support, {
ajax: !! e,
cors: !! e && "withCredentials" in e
})
}(v.ajaxSettings.xhr()), v.support.ajax && v.ajaxTransport(function(n) {
if (!n.crossDomain || v.support.cors) {
var r;
return {
send: function(i, s) {
var o, u, a = n.xhr();
n.username ? a.open(n.type, n.url, n.async, n.username, n.password) : a.open(n.type, n.url, n.async);
if (n.xhrFields) for (u in n.xhrFields) a[u] = n.xhrFields[u];
n.mimeType && a.overrideMimeType && a.overrideMimeType(n.mimeType), !n.crossDomain && !i["X-Requested-With"] && (i["X-Requested-With"] = "XMLHttpRequest");
try {
for (u in i) a.setRequestHeader(u, i[u])
} catch (f) {}
a.send(n.hasContent && n.data || null), r = function(e, i) {
var u, f, l, c, h;
try {
if (r && (i || a.readyState === 4)) {
r = t, o && (a.onreadystatechange = v.noop, Bn && delete Hn[o]);
if (i) a.readyState !== 4 && a.abort();
else {
u = a.status, l = a.getAllResponseHeaders(), c = {}, h = a.responseXML, h && h.documentElement && (c.xml = h);
try {
c.text = a.responseText
} catch (p) {}
try {
f = a.statusText
} catch (p) {
f = ""
}!u && n.isLocal && !n.crossDomain ? u = c.text ? 200 : 404 : u === 1223 && (u = 204)
}
}
} catch (d) {
i || s(-1, d)
}
c && s(u, f, c, l)
}, n.async ? a.readyState === 4 ? setTimeout(r, 0) : (o = ++jn, Bn && (Hn || (Hn = {}, v(e).unload(Bn)), Hn[o] = r), a.onreadystatechange = r) : r()
},
abort: function() {
r && r(0, 1)
}
}
}
});
var qn, Rn, Un = /^(?:toggle|show|hide)$/,
zn = new RegExp("^(?:([-+])=|)(" + m + ")([a-z%]*)$", "i"),
Wn = /queueHooks$/,
Xn = [Gn],
Vn = {
"*": [function(e, t) {
var n, r, i = this.createTween(e, t),
s = zn.exec(t),
o = i.cur(),
u = +o || 0,
a = 1,
f = 20;
if (s) {
n = +s[2], r = s[3] || (v.cssNumber[e] ? "" : "px");
if (r !== "px" && u) {
u = v.css(i.elem, e, !0) || n || 1;
do a = a || ".5", u /= a, v.style(i.elem, e, u + r);
while (a !== (a = i.cur() / o) && a !== 1 && --f)
}
i.unit = r, i.start = u, i.end = s[1] ? u + (s[1] + 1) * n : n
}
return i
}]
};
v.Animation = v.extend(Kn, {
tweener: function(e, t) {
v.isFunction(e) ? (t = e, e = ["*"]) : e = e.split(" ");
var n, r = 0,
i = e.length;
for (; r < i; r++) n = e[r], Vn[n] = Vn[n] || [], Vn[n].unshift(t)
},
prefilter: function(e, t) {
t ? Xn.unshift(e) : Xn.push(e)
}
}), v.Tween = Yn, Yn.prototype = {
constructor: Yn,
init: function(e, t, n, r, i, s) {
this.elem = e, this.prop = n, this.easing = i || "swing", this.options = t, this.start = this.now = this.cur(), this.end = r, this.unit = s || (v.cssNumber[n] ? "" : "px")
},
cur: function() {
var e = Yn.propHooks[this.prop];
return e && e.get ? e.get(this) : Yn.propHooks._default.get(this)
},
run: function(e) {
var t, n = Yn.propHooks[this.prop];
return this.options.duration ? this.pos = t = v.easing[this.easing](e, this.options.duration * e, 0, 1, this.options.duration) : this.pos = t = 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) : Yn.propHooks._default.set(this), this
}
}, Yn.prototype.init.prototype = Yn.prototype, Yn.propHooks = {
_default: {
get: function(e) {
var t;
return e.elem[e.prop] == null || !! e.elem.style && e.elem.style[e.prop] != null ? (t = v.css(e.elem, e.prop, !1, ""), !t || t === "auto" ? 0 : t) : e.elem[e.prop]
},
set: function(e) {
v.fx.step[e.prop] ? v.fx.step[e.prop](e) : e.elem.style && (e.elem.style[v.cssProps[e.prop]] != null || v.cssHooks[e.prop]) ? v.style(e.elem, e.prop, e.now + e.unit) : e.elem[e.prop] = e.now
}
}
}, Yn.propHooks.scrollTop = Yn.propHooks.scrollLeft = {
set: function(e) {
e.elem.nodeType && e.elem.parentNode && (e.elem[e.prop] = e.now)
}
}, v.each(["toggle", "show", "hide"], function(e, t) {
var n = v.fn[t];
v.fn[t] = function(r, i, s) {
return r == null || typeof r == "boolean" || !e && v.isFunction(r) && v.isFunction(i) ? n.apply(this, arguments) : this.animate(Zn(t, !0), r, i, s)
}
}), v.fn.extend({
fadeTo: function(e, t, n, r) {
return this.filter(Gt).css("opacity", 0).show().end().animate({
opacity: t
}, e, n, r)
},
animate: function(e, t, n, r) {
var i = v.isEmptyObject(e),
s = v.speed(t, n, r),
o = function() {
var t = Kn(this, v.extend({}, e), s);
i && t.stop(!0)
};
return i || s.queue === !1 ? this.each(o) : this.queue(s.queue, o)
},
stop: function(e, n, r) {
var i = function(e) {
var t = e.stop;
delete e.stop, t(r)
};
return typeof e != "string" && (r = n, n = e, e = t), n && e !== !1 && this.queue(e || "fx", []), this.each(function() {
var t = !0,
n = e != null && e + "queueHooks",
s = v.timers,
o = v._data(this);
if (n) o[n] && o[n].stop && i(o[n]);
else for (n in o) o[n] && o[n].stop && Wn.test(n) && i(o[n]);
for (n = s.length; n--;) s[n].elem === this && (e == null || s[n].queue === e) && (s[n].anim.stop(r), t = !1, s.splice(n, 1));
(t || !r) && v.dequeue(this, e)
})
}
}), v.each({
slideDown: Zn("show"),
slideUp: Zn("hide"),
slideToggle: Zn("toggle"),
fadeIn: {
opacity: "show"
},
fadeOut: {
opacity: "hide"
},
fadeToggle: {
opacity: "toggle"
}
}, function(e, t) {
v.fn[e] = function(e, n, r) {
return this.animate(t, e, n, r)
}
}), v.speed = function(e, t, n) {
var r = e && typeof e == "object" ? v.extend({}, e) : {
complete: n || !n && t || v.isFunction(e) && e,
duration: e,
easing: n && t || t && !v.isFunction(t) && t
};
r.duration = v.fx.off ? 0 : typeof r.duration == "number" ? r.duration : r.duration in v.fx.speeds ? v.fx.speeds[r.duration] : v.fx.speeds._default;
if (r.queue == null || r.queue === !0) r.queue = "fx";
return r.old = r.complete, r.complete = function() {
v.isFunction(r.old) && r.old.call(this), r.queue && v.dequeue(this, r.queue)
}, r
}, v.easing = {
linear: function(e) {
return e
},
swing: function(e) {
return.5 - Math.cos(e * Math.PI) / 2
}
}, v.timers = [], v.fx = Yn.prototype.init, v.fx.tick = function() {
var e, n = v.timers,
r = 0;
qn = v.now();
for (; r < n.length; r++) e = n[r], !e() && n[r] === e && n.splice(r--, 1);
n.length || v.fx.stop(), qn = t
}, v.fx.timer = function(e) {
e() && v.timers.push(e) && !Rn && (Rn = setInterval(v.fx.tick, v.fx.interval))
}, v.fx.interval = 13, v.fx.stop = function() {
clearInterval(Rn), Rn = null
}, v.fx.speeds = {
slow: 600,
fast: 200,
_default: 400
}, v.fx.step = {}, v.expr && v.expr.filters && (v.expr.filters.animated = function(e) {
return v.grep(v.timers, function(t) {
return e === t.elem
}).length
});
var er = /^(?:body|html)$/i;
v.fn.offset = function(e) {
if (arguments.length) return e === t ? this : this.each(function(t) {
v.offset.setOffset(this, e, t)
});
var n, r, i, s, o, u, a, f = {
top: 0,
left: 0
},
l = this[0],
c = l && l.ownerDocument;
if (!c) return;
return (r = c.body) === l ? v.offset.bodyOffset(l) : (n = c.documentElement, v.contains(n, l) ? (typeof l.getBoundingClientRect != "undefined" && (f = l.getBoundingClientRect()), i = tr(c), s = n.clientTop || r.clientTop || 0, o = n.clientLeft || r.clientLeft || 0, u = i.pageYOffset || n.scrollTop, a = i.pageXOffset || n.scrollLeft, {
top: f.top + u - s,
left: f.left + a - o
}) : f)
}, v.offset = {
bodyOffset: function(e) {
var t = e.offsetTop,
n = e.offsetLeft;
return v.support.doesNotIncludeMarginInBodyOffset && (t += parseFloat(v.css(e, "marginTop")) || 0, n += parseFloat(v.css(e, "marginLeft")) || 0), {
top: t,
left: n
}
},
setOffset: function(e, t, n) {
var r = v.css(e, "position");
r === "static" && (e.style.position = "relative");
var i = v(e),
s = i.offset(),
o = v.css(e, "top"),
u = v.css(e, "left"),
a = (r === "absolute" || r === "fixed") && v.inArray("auto", [o, u]) > -1,
f = {},
l = {},
c, h;
a ? (l = i.position(), c = l.top, h = l.left) : (c = parseFloat(o) || 0, h = parseFloat(u) || 0), v.isFunction(t) && (t = t.call(e, n, s)), t.top != null && (f.top = t.top - s.top + c), t.left != null && (f.left = t.left - s.left + h), "using" in t ? t.using.call(e, f) : i.css(f)
}
}, v.fn.extend({
position: function() {
if (!this[0]) return;
var e = this[0],
t = this.offsetParent(),
n = this.offset(),
r = er.test(t[0].nodeName) ? {
top: 0,
left: 0
} : t.offset();
return n.top -= parseFloat(v.css(e, "marginTop")) || 0, n.left -= parseFloat(v.css(e, "marginLeft")) || 0, r.top += parseFloat(v.css(t[0], "borderTopWidth")) || 0, r.left += parseFloat(v.css(t[0], "borderLeftWidth")) || 0, {
top: n.top - r.top,
left: n.left - r.left
}
},
offsetParent: function() {
return this.map(function() {
var e = this.offsetParent || i.body;
while (e && !er.test(e.nodeName) && v.css(e, "position") === "static") e = e.offsetParent;
return e || i.body
})
}
}), v.each({
scrollLeft: "pageXOffset",
scrollTop: "pageYOffset"
}, function(e, n) {
var r = /Y/.test(n);
v.fn[e] = function(i) {
return v.access(this, function(e, i, s) {
var o = tr(e);
if (s === t) return o ? n in o ? o[n] : o.document.documentElement[i] : e[i];
o ? o.scrollTo(r ? v(o).scrollLeft() : s, r ? s : v(o).scrollTop()) : e[i] = s
}, e, i, arguments.length, null)
}
}), v.each({
Height: "height",
Width: "width"
}, function(e, n) {
v.each({
padding: "inner" + e,
content: n,
"": "outer" + e
}, function(r, i) {
v.fn[i] = function(i, s) {
var o = arguments.length && (r || typeof i != "boolean"),
u = r || (i === !0 || s === !0 ? "margin" : "border");
return v.access(this, function(n, r, i) {
var s;
return v.isWindow(n) ? n.document.documentElement["client" + e] : n.nodeType === 9 ? (s = n.documentElement, Math.max(n.body["scroll" + e], s["scroll" + e], n.body["offset" + e], s["offset" + e], s["client" + e])) : i === t ? v.css(n, r, i, u) : v.style(n, r, i, u)
}, n, o ? i : t, o, null)
}
})
}), e.jQuery = e.$ = v, typeof define == "function" && define.amd && define.amd.jQuery && define("jquery", [], function() {
return v
})
})(window);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.